AdithyaSK HF Staff commited on
Commit
b98a72e
·
verified ·
1 Parent(s): ad211af

Stage Harbor release files 37001-37500

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-5cbfd9f64dbc/environment/source/src/transformers/models/led/modeling_led.py +0 -0
  2. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/led/modeling_tf_led.py +0 -0
  3. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/led/tokenization_led.py +454 -0
  4. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/led/tokenization_led_fast.py +322 -0
  5. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/levit/__init__.py +30 -0
  6. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/levit/configuration_levit.py +144 -0
  7. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/levit/convert_levit_timm_to_pytorch.py +181 -0
  8. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/levit/feature_extraction_levit.py +38 -0
  9. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/levit/image_processing_levit.py +312 -0
  10. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/levit/image_processing_levit_fast.py +98 -0
  11. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/levit/modeling_levit.py +677 -0
  12. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lfm2/__init__.py +27 -0
  13. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lfm2/configuration_lfm2.py +165 -0
  14. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lfm2/modeling_lfm2.py +760 -0
  15. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lfm2/modular_lfm2.py +520 -0
  16. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lightglue/__init__.py +28 -0
  17. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lightglue/configuration_lightglue.py +155 -0
  18. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lightglue/convert_lightglue_to_hf.py +280 -0
  19. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lightglue/image_processing_lightglue.py +526 -0
  20. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lightglue/modeling_lightglue.py +916 -0
  21. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lightglue/modular_lightglue.py +1074 -0
  22. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lilt/__init__.py +27 -0
  23. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lilt/configuration_lilt.py +131 -0
  24. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lilt/modeling_lilt.py +1093 -0
  25. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama/__init__.py +30 -0
  26. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama/configuration_llama.py +225 -0
  27. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama/convert_llama_weights_to_hf.py +605 -0
  28. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama/modeling_flax_llama.py +747 -0
  29. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama/modeling_llama.py +511 -0
  30. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama/tokenization_llama.py +415 -0
  31. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama/tokenization_llama_fast.py +251 -0
  32. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama4/__init__.py +29 -0
  33. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama4/configuration_llama4.py +466 -0
  34. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama4/convert_llama4_weights_to_hf.py +743 -0
  35. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama4/image_processing_llama4_fast.py +465 -0
  36. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama4/modeling_llama4.py +1409 -0
  37. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama4/processing_llama4.py +258 -0
  38. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava/__init__.py +29 -0
  39. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava/configuration_llava.py +137 -0
  40. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava/convert_llava_weights_to_hf.py +202 -0
  41. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava/image_processing_llava.py +436 -0
  42. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava/image_processing_llava_fast.py +191 -0
  43. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava/modeling_llava.py +514 -0
  44. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava/processing_llava.py +235 -0
  45. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava_next/__init__.py +30 -0
  46. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava_next/configuration_llava_next.py +150 -0
  47. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava_next/convert_llava_next_weights_to_hf.py +394 -0
  48. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava_next/image_processing_llava_next.py +724 -0
  49. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava_next/image_processing_llava_next_fast.py +295 -0
  50. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava_next/modeling_llava_next.py +797 -0
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/led/modeling_led.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/led/modeling_tf_led.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/led/tokenization_led.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Iz Beltagy, Matthew E. Peters, Arman Cohan 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 LED."""
16
+
17
+ import json
18
+ import os
19
+ from functools import lru_cache
20
+ from typing import Optional, Union
21
+
22
+ import regex as re
23
+
24
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
25
+ from ...tokenization_utils_base import BatchEncoding, EncodedInput
26
+ from ...utils import PaddingStrategy, logging
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+
32
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
33
+
34
+ # See all LED models at https://huggingface.co/models?filter=LED
35
+
36
+
37
+ @lru_cache
38
+ # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode
39
+ def bytes_to_unicode():
40
+ """
41
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
42
+ characters the bpe code barfs on.
43
+
44
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
45
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
46
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
47
+ tables between utf-8 bytes and unicode strings.
48
+ """
49
+ bs = (
50
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
51
+ )
52
+ cs = bs[:]
53
+ n = 0
54
+ for b in range(2**8):
55
+ if b not in bs:
56
+ bs.append(b)
57
+ cs.append(2**8 + n)
58
+ n += 1
59
+ cs = [chr(n) for n in cs]
60
+ return dict(zip(bs, cs))
61
+
62
+
63
+ # Copied from transformers.models.bart.tokenization_bart.get_pairs
64
+ def get_pairs(word):
65
+ """
66
+ Return set of symbol pairs in a word.
67
+
68
+ Word is represented as tuple of symbols (symbols being variable-length strings).
69
+ """
70
+ pairs = set()
71
+ prev_char = word[0]
72
+ for char in word[1:]:
73
+ pairs.add((prev_char, char))
74
+ prev_char = char
75
+ return pairs
76
+
77
+
78
+ class LEDTokenizer(PreTrainedTokenizer):
79
+ """
80
+ Constructs a LED tokenizer, which is smilar to the ROBERTa tokenizer, using byte-level Byte-Pair-Encoding.
81
+
82
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
83
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
84
+
85
+ ```python
86
+ >>> from transformers import LEDTokenizer
87
+
88
+ >>> tokenizer = LEDTokenizer.from_pretrained("allenai/led-base-16384")
89
+ >>> tokenizer("Hello world")["input_ids"]
90
+ [0, 31414, 232, 2]
91
+
92
+ >>> tokenizer(" Hello world")["input_ids"]
93
+ [0, 20920, 232, 2]
94
+ ```
95
+
96
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
97
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
98
+
99
+ <Tip>
100
+
101
+ When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
102
+
103
+ </Tip>
104
+
105
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
106
+ this superclass for more information regarding those methods.
107
+
108
+ Args:
109
+ vocab_file (`str`):
110
+ Path to the vocabulary file.
111
+ merges_file (`str`):
112
+ Path to the merges file.
113
+ errors (`str`, *optional*, defaults to `"replace"`):
114
+ Paradigm to follow when decoding bytes to UTF-8. See
115
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
116
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
117
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
118
+
119
+ <Tip>
120
+
121
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
122
+ sequence. The token used is the `cls_token`.
123
+
124
+ </Tip>
125
+
126
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
127
+ The end of sequence token.
128
+
129
+ <Tip>
130
+
131
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
132
+ The token used is the `sep_token`.
133
+
134
+ </Tip>
135
+
136
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
137
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
138
+ sequence classification or for a text and a question for question answering. It is also used as the last
139
+ token of a sequence built with special tokens.
140
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
141
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
142
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
143
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
144
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
145
+ token instead.
146
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
147
+ The token used for padding, for example when batching sequences of different lengths.
148
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
149
+ The token used for masking values. This is the token used when training this model with masked language
150
+ modeling. This is the token which the model will try to predict.
151
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
152
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
153
+ other word. (BART tokenizer detect beginning of words by the preceding space).
154
+ """
155
+
156
+ vocab_files_names = VOCAB_FILES_NAMES
157
+ model_input_names = ["input_ids", "attention_mask"]
158
+
159
+ # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.__init__
160
+ def __init__(
161
+ self,
162
+ vocab_file,
163
+ merges_file,
164
+ errors="replace",
165
+ bos_token="<s>",
166
+ eos_token="</s>",
167
+ sep_token="</s>",
168
+ cls_token="<s>",
169
+ unk_token="<unk>",
170
+ pad_token="<pad>",
171
+ mask_token="<mask>",
172
+ add_prefix_space=False,
173
+ **kwargs,
174
+ ):
175
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
176
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
177
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
178
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
179
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
180
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
181
+
182
+ # Mask token behave like a normal word, i.e. include the space before it
183
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
184
+
185
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
186
+ self.encoder = json.load(vocab_handle)
187
+ self.decoder = {v: k for k, v in self.encoder.items()}
188
+ self.errors = errors # how to handle errors in decoding
189
+ self.byte_encoder = bytes_to_unicode()
190
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
191
+ with open(merges_file, encoding="utf-8") as merges_handle:
192
+ bpe_merges = merges_handle.read().split("\n")[1:-1]
193
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
194
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
195
+ self.cache = {}
196
+ self.add_prefix_space = add_prefix_space
197
+
198
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
199
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
200
+
201
+ super().__init__(
202
+ errors=errors,
203
+ bos_token=bos_token,
204
+ eos_token=eos_token,
205
+ unk_token=unk_token,
206
+ sep_token=sep_token,
207
+ cls_token=cls_token,
208
+ pad_token=pad_token,
209
+ mask_token=mask_token,
210
+ add_prefix_space=add_prefix_space,
211
+ **kwargs,
212
+ )
213
+
214
+ @property
215
+ # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size
216
+ def vocab_size(self):
217
+ return len(self.encoder)
218
+
219
+ # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.get_vocab
220
+ def get_vocab(self):
221
+ return dict(self.encoder, **self.added_tokens_encoder)
222
+
223
+ # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.bpe
224
+ def bpe(self, token):
225
+ if token in self.cache:
226
+ return self.cache[token]
227
+ word = tuple(token)
228
+ pairs = get_pairs(word)
229
+
230
+ if not pairs:
231
+ return token
232
+
233
+ while True:
234
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
235
+ if bigram not in self.bpe_ranks:
236
+ break
237
+ first, second = bigram
238
+ new_word = []
239
+ i = 0
240
+ while i < len(word):
241
+ try:
242
+ j = word.index(first, i)
243
+ except ValueError:
244
+ new_word.extend(word[i:])
245
+ break
246
+ else:
247
+ new_word.extend(word[i:j])
248
+ i = j
249
+
250
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
251
+ new_word.append(first + second)
252
+ i += 2
253
+ else:
254
+ new_word.append(word[i])
255
+ i += 1
256
+ new_word = tuple(new_word)
257
+ word = new_word
258
+ if len(word) == 1:
259
+ break
260
+ else:
261
+ pairs = get_pairs(word)
262
+ word = " ".join(word)
263
+ self.cache[token] = word
264
+ return word
265
+
266
+ # Copied from transformers.models.bart.tokenization_bart.BartTokenizer._tokenize
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
+ # Copied from transformers.models.bart.tokenization_bart.BartTokenizer._convert_token_to_id
278
+ def _convert_token_to_id(self, token):
279
+ """Converts a token (str) in an id using the vocab."""
280
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
281
+
282
+ # Copied from transformers.models.bart.tokenization_bart.BartTokenizer._convert_id_to_token
283
+ def _convert_id_to_token(self, index):
284
+ """Converts an index (integer) in a token (str) using the vocab."""
285
+ return self.decoder.get(index)
286
+
287
+ # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.convert_tokens_to_string
288
+ def convert_tokens_to_string(self, tokens):
289
+ """Converts a sequence of tokens (string) in a single string."""
290
+ text = "".join(tokens)
291
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
292
+ return text
293
+
294
+ # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.save_vocabulary
295
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
296
+ if not os.path.isdir(save_directory):
297
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
298
+ return
299
+ vocab_file = os.path.join(
300
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
301
+ )
302
+ merge_file = os.path.join(
303
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
304
+ )
305
+
306
+ with open(vocab_file, "w", encoding="utf-8") as f:
307
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
308
+
309
+ index = 0
310
+ with open(merge_file, "w", encoding="utf-8") as writer:
311
+ writer.write("#version: 0.2\n")
312
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
313
+ if index != token_index:
314
+ logger.warning(
315
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
316
+ " Please check that the tokenizer is not corrupted!"
317
+ )
318
+ index = token_index
319
+ writer.write(" ".join(bpe_tokens) + "\n")
320
+ index += 1
321
+
322
+ return vocab_file, merge_file
323
+
324
+ # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.build_inputs_with_special_tokens with BART->LED
325
+ def build_inputs_with_special_tokens(
326
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
327
+ ) -> list[int]:
328
+ """
329
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
330
+ adding special tokens. A LED sequence has the following format:
331
+
332
+ - single sequence: `<s> X </s>`
333
+ - pair of sequences: `<s> A </s></s> B </s>`
334
+
335
+ Args:
336
+ token_ids_0 (`list[int]`):
337
+ List of IDs to which the special tokens will be added.
338
+ token_ids_1 (`list[int]`, *optional*):
339
+ Optional second list of IDs for sequence pairs.
340
+
341
+ Returns:
342
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
343
+ """
344
+ if token_ids_1 is None:
345
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
346
+ cls = [self.cls_token_id]
347
+ sep = [self.sep_token_id]
348
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
349
+
350
+ # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.get_special_tokens_mask
351
+ def get_special_tokens_mask(
352
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
353
+ ) -> list[int]:
354
+ """
355
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
356
+ special tokens using the tokenizer `prepare_for_model` method.
357
+
358
+ Args:
359
+ token_ids_0 (`list[int]`):
360
+ List of IDs.
361
+ token_ids_1 (`list[int]`, *optional*):
362
+ Optional second list of IDs for sequence pairs.
363
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
364
+ Whether or not the token list is already formatted with special tokens for the model.
365
+
366
+ Returns:
367
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
368
+ """
369
+ if already_has_special_tokens:
370
+ return super().get_special_tokens_mask(
371
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
372
+ )
373
+
374
+ if token_ids_1 is None:
375
+ return [1] + ([0] * len(token_ids_0)) + [1]
376
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
377
+
378
+ # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.create_token_type_ids_from_sequences with BART->LED
379
+ def create_token_type_ids_from_sequences(
380
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
381
+ ) -> list[int]:
382
+ """
383
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. LED does not
384
+ make use of token type ids, therefore a list of zeros is returned.
385
+
386
+ Args:
387
+ token_ids_0 (`list[int]`):
388
+ List of IDs.
389
+ token_ids_1 (`list[int]`, *optional*):
390
+ Optional second list of IDs for sequence pairs.
391
+
392
+ Returns:
393
+ `list[int]`: List of zeros.
394
+ """
395
+ sep = [self.sep_token_id]
396
+ cls = [self.cls_token_id]
397
+
398
+ if token_ids_1 is None:
399
+ return len(cls + token_ids_0 + sep) * [0]
400
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
401
+
402
+ # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.prepare_for_tokenization
403
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
404
+ add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
405
+ if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
406
+ text = " " + text
407
+ return (text, kwargs)
408
+
409
+ def _pad(
410
+ self,
411
+ encoded_inputs: Union[dict[str, EncodedInput], BatchEncoding],
412
+ max_length: Optional[int] = None,
413
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
414
+ pad_to_multiple_of: Optional[int] = None,
415
+ padding_side: Optional[str] = None,
416
+ return_attention_mask: Optional[bool] = None,
417
+ ) -> dict:
418
+ encoded_inputs = super()._pad(
419
+ encoded_inputs=encoded_inputs,
420
+ max_length=max_length,
421
+ padding_strategy=padding_strategy,
422
+ pad_to_multiple_of=pad_to_multiple_of,
423
+ padding_side=padding_side,
424
+ return_attention_mask=return_attention_mask,
425
+ )
426
+
427
+ # Load from model defaults
428
+ if return_attention_mask is None:
429
+ return_attention_mask = "attention_mask" in self.model_input_names
430
+
431
+ if return_attention_mask and "global_attention_mask" in encoded_inputs:
432
+ required_input = encoded_inputs[self.model_input_names[0]]
433
+ # `global_attention_mask` need to have the same length as other (sequential) inputs.
434
+ needs_to_be_padded = len(encoded_inputs["global_attention_mask"]) != len(required_input)
435
+
436
+ if needs_to_be_padded:
437
+ difference = len(required_input) - len(encoded_inputs["global_attention_mask"])
438
+
439
+ if self.padding_side == "right":
440
+ # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
441
+ encoded_inputs["global_attention_mask"] = (
442
+ encoded_inputs["global_attention_mask"] + [-1] * difference
443
+ )
444
+ elif self.padding_side == "left":
445
+ encoded_inputs["global_attention_mask"] = [-1] * difference + encoded_inputs[
446
+ "global_attention_mask"
447
+ ]
448
+ else:
449
+ raise ValueError("Invalid padding strategy:" + str(self.padding_side))
450
+
451
+ return encoded_inputs
452
+
453
+
454
+ __all__ = ["LEDTokenizer"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/led/tokenization_led_fast.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Iz Beltagy, Matthew E. Peters, Arman Cohan 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 LED."""
16
+
17
+ import json
18
+ from typing import Optional, Union
19
+
20
+ from tokenizers import processors
21
+
22
+ from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput
23
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
24
+ from ...utils import PaddingStrategy, logging
25
+ from .tokenization_led import LEDTokenizer
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
32
+
33
+
34
+ class LEDTokenizerFast(PreTrainedTokenizerFast):
35
+ r"""
36
+ Construct a "fast" LED tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2 tokenizer,
37
+ 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 LEDTokenizerFast
44
+
45
+ >>> tokenizer = LEDTokenizerFast.from_pretrained("allenai/led-base-16384")
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. (LED 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
+ slow_tokenizer_class = LEDTokenizer
117
+ model_input_names = ["input_ids", "attention_mask"]
118
+
119
+ # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.__init__
120
+ def __init__(
121
+ self,
122
+ vocab_file=None,
123
+ merges_file=None,
124
+ tokenizer_file=None,
125
+ errors="replace",
126
+ bos_token="<s>",
127
+ eos_token="</s>",
128
+ sep_token="</s>",
129
+ cls_token="<s>",
130
+ unk_token="<unk>",
131
+ pad_token="<pad>",
132
+ mask_token="<mask>",
133
+ add_prefix_space=False,
134
+ trim_offsets=True,
135
+ **kwargs,
136
+ ):
137
+ # we have to specify that this tokens is special otherwise adding it will reset the normalized flag to `False` in `add_special_tokens`
138
+ mask_token = (
139
+ AddedToken(mask_token, lstrip=True, normalized=True, special=True)
140
+ if isinstance(mask_token, str)
141
+ else mask_token
142
+ )
143
+ super().__init__(
144
+ vocab_file,
145
+ merges_file,
146
+ tokenizer_file=tokenizer_file,
147
+ errors=errors,
148
+ bos_token=bos_token,
149
+ eos_token=eos_token,
150
+ sep_token=sep_token,
151
+ cls_token=cls_token,
152
+ unk_token=unk_token,
153
+ pad_token=pad_token,
154
+ mask_token=mask_token,
155
+ add_prefix_space=add_prefix_space,
156
+ trim_offsets=trim_offsets,
157
+ **kwargs,
158
+ )
159
+
160
+ # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
161
+ tokenizer_component = "post_processor"
162
+ tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
163
+ if tokenizer_component_instance:
164
+ state = json.loads(tokenizer_component_instance.__getstate__())
165
+
166
+ # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
167
+ if "sep" in state:
168
+ state["sep"] = tuple(state["sep"])
169
+ if "cls" in state:
170
+ state["cls"] = tuple(state["cls"])
171
+
172
+ changes_to_apply = False
173
+
174
+ if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
175
+ state["add_prefix_space"] = add_prefix_space
176
+ changes_to_apply = True
177
+
178
+ if state.get("trim_offsets", trim_offsets) != trim_offsets:
179
+ state["trim_offsets"] = trim_offsets
180
+ changes_to_apply = True
181
+
182
+ if changes_to_apply:
183
+ component_class = getattr(processors, state.pop("type"))
184
+ new_value = component_class(**state)
185
+ setattr(self.backend_tokenizer, tokenizer_component, new_value)
186
+
187
+ @property
188
+ # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED
189
+ def mask_token(self) -> str:
190
+ """
191
+ `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
192
+ having been set.
193
+
194
+ LED tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
195
+ comprise the space before the *<mask>*.
196
+ """
197
+ if self._mask_token is None:
198
+ if self.verbose:
199
+ logger.error("Using mask_token, but it is not set yet.")
200
+ return None
201
+ return str(self._mask_token)
202
+
203
+ @mask_token.setter
204
+ def mask_token(self, value):
205
+ """
206
+ Overriding the default behavior of the mask token to have it eat the space before it.
207
+
208
+ This is needed to preserve backward compatibility with all the previously used models based on LED.
209
+ """
210
+ # Mask token behave like a normal word, i.e. include the space before it
211
+ # So we set lstrip to True
212
+ value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
213
+ self._mask_token = value
214
+
215
+ # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast._batch_encode_plus
216
+ def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
217
+ is_split_into_words = kwargs.get("is_split_into_words", False)
218
+
219
+ if is_split_into_words and not self.add_prefix_space:
220
+ raise ValueError(
221
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
222
+ "to use it with pretokenized inputs."
223
+ )
224
+
225
+ return super()._batch_encode_plus(*args, **kwargs)
226
+
227
+ # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast._encode_plus
228
+ def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
229
+ is_split_into_words = kwargs.get("is_split_into_words", False)
230
+
231
+ if is_split_into_words and not self.add_prefix_space:
232
+ raise ValueError(
233
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
234
+ "to use it with pretokenized inputs."
235
+ )
236
+
237
+ return super()._encode_plus(*args, **kwargs)
238
+
239
+ # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.save_vocabulary
240
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
241
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
242
+ return tuple(files)
243
+
244
+ # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.build_inputs_with_special_tokens
245
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
246
+ output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
247
+ if token_ids_1 is None:
248
+ return output
249
+
250
+ return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
251
+
252
+ # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.create_token_type_ids_from_sequences with BART->LED
253
+ def create_token_type_ids_from_sequences(
254
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
255
+ ) -> list[int]:
256
+ """
257
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. LED does not
258
+ make use of token type ids, therefore a list of zeros is returned.
259
+
260
+ Args:
261
+ token_ids_0 (`list[int]`):
262
+ List of IDs.
263
+ token_ids_1 (`list[int]`, *optional*):
264
+ Optional second list of IDs for sequence pairs.
265
+
266
+ Returns:
267
+ `list[int]`: List of zeros.
268
+ """
269
+ sep = [self.sep_token_id]
270
+ cls = [self.cls_token_id]
271
+
272
+ if token_ids_1 is None:
273
+ return len(cls + token_ids_0 + sep) * [0]
274
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
275
+
276
+ # Copied from transformers.models.led.tokenization_led.LEDTokenizer._pad
277
+ def _pad(
278
+ self,
279
+ encoded_inputs: Union[dict[str, EncodedInput], BatchEncoding],
280
+ max_length: Optional[int] = None,
281
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
282
+ pad_to_multiple_of: Optional[int] = None,
283
+ padding_side: Optional[str] = None,
284
+ return_attention_mask: Optional[bool] = None,
285
+ ) -> dict:
286
+ encoded_inputs = super()._pad(
287
+ encoded_inputs=encoded_inputs,
288
+ max_length=max_length,
289
+ padding_strategy=padding_strategy,
290
+ pad_to_multiple_of=pad_to_multiple_of,
291
+ padding_side=padding_side,
292
+ return_attention_mask=return_attention_mask,
293
+ )
294
+
295
+ # Load from model defaults
296
+ if return_attention_mask is None:
297
+ return_attention_mask = "attention_mask" in self.model_input_names
298
+
299
+ if return_attention_mask and "global_attention_mask" in encoded_inputs:
300
+ required_input = encoded_inputs[self.model_input_names[0]]
301
+ # `global_attention_mask` need to have the same length as other (sequential) inputs.
302
+ needs_to_be_padded = len(encoded_inputs["global_attention_mask"]) != len(required_input)
303
+
304
+ if needs_to_be_padded:
305
+ difference = len(required_input) - len(encoded_inputs["global_attention_mask"])
306
+
307
+ if self.padding_side == "right":
308
+ # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
309
+ encoded_inputs["global_attention_mask"] = (
310
+ encoded_inputs["global_attention_mask"] + [-1] * difference
311
+ )
312
+ elif self.padding_side == "left":
313
+ encoded_inputs["global_attention_mask"] = [-1] * difference + encoded_inputs[
314
+ "global_attention_mask"
315
+ ]
316
+ else:
317
+ raise ValueError("Invalid padding strategy:" + str(self.padding_side))
318
+
319
+ return encoded_inputs
320
+
321
+
322
+ __all__ = ["LEDTokenizerFast"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/levit/__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_levit import *
22
+ from .feature_extraction_levit import *
23
+ from .image_processing_levit import *
24
+ from .image_processing_levit_fast import *
25
+ from .modeling_levit 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-5cbfd9f64dbc/environment/source/src/transformers/models/levit/configuration_levit.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """LeViT model configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from collections.abc import Mapping
19
+
20
+ from packaging import version
21
+
22
+ from ...configuration_utils import PretrainedConfig
23
+ from ...onnx import OnnxConfig
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ class LevitConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`LevitModel`]. It is used to instantiate a LeViT
33
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
34
+ defaults will yield a similar configuration to that of the LeViT
35
+ [facebook/levit-128S](https://huggingface.co/facebook/levit-128S) 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
+ Args:
41
+ image_size (`int`, *optional*, defaults to 224):
42
+ The size of the input image.
43
+ num_channels (`int`, *optional*, defaults to 3):
44
+ Number of channels in the input image.
45
+ kernel_size (`int`, *optional*, defaults to 3):
46
+ The kernel size for the initial convolution layers of patch embedding.
47
+ stride (`int`, *optional*, defaults to 2):
48
+ The stride size for the initial convolution layers of patch embedding.
49
+ padding (`int`, *optional*, defaults to 1):
50
+ The padding size for the initial convolution layers of patch embedding.
51
+ patch_size (`int`, *optional*, defaults to 16):
52
+ The patch size for embeddings.
53
+ hidden_sizes (`list[int]`, *optional*, defaults to `[128, 256, 384]`):
54
+ Dimension of each of the encoder blocks.
55
+ num_attention_heads (`list[int]`, *optional*, defaults to `[4, 8, 12]`):
56
+ Number of attention heads for each attention layer in each block of the Transformer encoder.
57
+ depths (`list[int]`, *optional*, defaults to `[4, 4, 4]`):
58
+ The number of layers in each encoder block.
59
+ key_dim (`list[int]`, *optional*, defaults to `[16, 16, 16]`):
60
+ The size of key in each of the encoder blocks.
61
+ drop_path_rate (`int`, *optional*, defaults to 0):
62
+ The dropout probability for stochastic depths, used in the blocks of the Transformer encoder.
63
+ mlp_ratios (`list[int]`, *optional*, defaults to `[2, 2, 2]`):
64
+ Ratio of the size of the hidden layer compared to the size of the input layer of the Mix FFNs in the
65
+ encoder blocks.
66
+ attention_ratios (`list[int]`, *optional*, defaults to `[2, 2, 2]`):
67
+ Ratio of the size of the output dimension compared to input dimension of attention layers.
68
+ initializer_range (`float`, *optional*, defaults to 0.02):
69
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
70
+
71
+ Example:
72
+
73
+ ```python
74
+ >>> from transformers import LevitConfig, LevitModel
75
+
76
+ >>> # Initializing a LeViT levit-128S style configuration
77
+ >>> configuration = LevitConfig()
78
+
79
+ >>> # Initializing a model (with random weights) from the levit-128S style configuration
80
+ >>> model = LevitModel(configuration)
81
+
82
+ >>> # Accessing the model configuration
83
+ >>> configuration = model.config
84
+ ```"""
85
+
86
+ model_type = "levit"
87
+
88
+ def __init__(
89
+ self,
90
+ image_size=224,
91
+ num_channels=3,
92
+ kernel_size=3,
93
+ stride=2,
94
+ padding=1,
95
+ patch_size=16,
96
+ hidden_sizes=[128, 256, 384],
97
+ num_attention_heads=[4, 8, 12],
98
+ depths=[4, 4, 4],
99
+ key_dim=[16, 16, 16],
100
+ drop_path_rate=0,
101
+ mlp_ratio=[2, 2, 2],
102
+ attention_ratio=[2, 2, 2],
103
+ initializer_range=0.02,
104
+ **kwargs,
105
+ ):
106
+ super().__init__(**kwargs)
107
+ self.image_size = image_size
108
+ self.num_channels = num_channels
109
+ self.kernel_size = kernel_size
110
+ self.stride = stride
111
+ self.padding = padding
112
+ self.hidden_sizes = hidden_sizes
113
+ self.num_attention_heads = num_attention_heads
114
+ self.depths = depths
115
+ self.key_dim = key_dim
116
+ self.drop_path_rate = drop_path_rate
117
+ self.patch_size = patch_size
118
+ self.attention_ratio = attention_ratio
119
+ self.mlp_ratio = mlp_ratio
120
+ self.initializer_range = initializer_range
121
+ self.down_ops = [
122
+ ["Subsample", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
123
+ ["Subsample", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
124
+ ]
125
+
126
+
127
+ # Copied from transformers.models.vit.configuration_vit.ViTOnnxConfig
128
+ class LevitOnnxConfig(OnnxConfig):
129
+ torch_onnx_minimum_version = version.parse("1.11")
130
+
131
+ @property
132
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
133
+ return OrderedDict(
134
+ [
135
+ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
136
+ ]
137
+ )
138
+
139
+ @property
140
+ def atol_for_validation(self) -> float:
141
+ return 1e-4
142
+
143
+
144
+ __all__ = ["LevitConfig", "LevitOnnxConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/levit/convert_levit_timm_to_pytorch.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Convert LeViT checkpoints from timm."""
16
+
17
+ import argparse
18
+ import json
19
+ from collections import OrderedDict
20
+ from functools import partial
21
+ from pathlib import Path
22
+ from typing import Optional
23
+
24
+ import timm
25
+ import torch
26
+ from huggingface_hub import hf_hub_download
27
+
28
+ from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor
29
+ from transformers.utils import logging
30
+
31
+
32
+ logging.set_verbosity_info()
33
+ logger = logging.get_logger()
34
+
35
+
36
+ def convert_weight_and_push(
37
+ hidden_sizes: int, name: str, config: LevitConfig, save_directory: Path, push_to_hub: bool = True
38
+ ):
39
+ print(f"Converting {name}...")
40
+
41
+ with torch.no_grad():
42
+ if hidden_sizes == 128:
43
+ if name[-1] == "S":
44
+ from_model = timm.create_model("levit_128s", pretrained=True)
45
+ else:
46
+ from_model = timm.create_model("levit_128", pretrained=True)
47
+ if hidden_sizes == 192:
48
+ from_model = timm.create_model("levit_192", pretrained=True)
49
+ if hidden_sizes == 256:
50
+ from_model = timm.create_model("levit_256", pretrained=True)
51
+ if hidden_sizes == 384:
52
+ from_model = timm.create_model("levit_384", pretrained=True)
53
+
54
+ from_model.eval()
55
+ our_model = LevitForImageClassificationWithTeacher(config).eval()
56
+ huggingface_weights = OrderedDict()
57
+
58
+ weights = from_model.state_dict()
59
+ og_keys = list(from_model.state_dict().keys())
60
+ new_keys = list(our_model.state_dict().keys())
61
+ print(len(og_keys), len(new_keys))
62
+ for i in range(len(og_keys)):
63
+ huggingface_weights[new_keys[i]] = weights[og_keys[i]]
64
+ our_model.load_state_dict(huggingface_weights)
65
+
66
+ x = torch.randn((2, 3, 224, 224))
67
+ out1 = from_model(x)
68
+ out2 = our_model(x).logits
69
+
70
+ assert torch.allclose(out1, out2), "The model logits don't match the original one."
71
+
72
+ checkpoint_name = name
73
+ print(checkpoint_name)
74
+
75
+ if push_to_hub:
76
+ our_model.save_pretrained(save_directory / checkpoint_name)
77
+ image_processor = LevitImageProcessor()
78
+ image_processor.save_pretrained(save_directory / checkpoint_name)
79
+
80
+ print(f"Pushed {checkpoint_name}")
81
+
82
+
83
+ def convert_weights_and_push(save_directory: Path, model_name: Optional[str] = None, push_to_hub: bool = True):
84
+ filename = "imagenet-1k-id2label.json"
85
+ num_labels = 1000
86
+ expected_shape = (1, num_labels)
87
+
88
+ repo_id = "huggingface/label-files"
89
+ num_labels = num_labels
90
+ id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
91
+ id2label = {int(k): v for k, v in id2label.items()}
92
+
93
+ id2label = id2label
94
+ label2id = {v: k for k, v in id2label.items()}
95
+
96
+ ImageNetPreTrainedConfig = partial(LevitConfig, num_labels=num_labels, id2label=id2label, label2id=label2id)
97
+
98
+ names_to_hidden_sizes = {
99
+ "levit-128S": 128,
100
+ "levit-128": 128,
101
+ "levit-192": 192,
102
+ "levit-256": 256,
103
+ "levit-384": 384,
104
+ }
105
+
106
+ names_to_config = {
107
+ "levit-128S": ImageNetPreTrainedConfig(
108
+ hidden_sizes=[128, 256, 384],
109
+ num_attention_heads=[4, 6, 8],
110
+ depths=[2, 3, 4],
111
+ key_dim=[16, 16, 16],
112
+ drop_path_rate=0,
113
+ ),
114
+ "levit-128": ImageNetPreTrainedConfig(
115
+ hidden_sizes=[128, 256, 384],
116
+ num_attention_heads=[4, 8, 12],
117
+ depths=[4, 4, 4],
118
+ key_dim=[16, 16, 16],
119
+ drop_path_rate=0,
120
+ ),
121
+ "levit-192": ImageNetPreTrainedConfig(
122
+ hidden_sizes=[192, 288, 384],
123
+ num_attention_heads=[3, 5, 6],
124
+ depths=[4, 4, 4],
125
+ key_dim=[32, 32, 32],
126
+ drop_path_rate=0,
127
+ ),
128
+ "levit-256": ImageNetPreTrainedConfig(
129
+ hidden_sizes=[256, 384, 512],
130
+ num_attention_heads=[4, 6, 8],
131
+ depths=[4, 4, 4],
132
+ key_dim=[32, 32, 32],
133
+ drop_path_rate=0,
134
+ ),
135
+ "levit-384": ImageNetPreTrainedConfig(
136
+ hidden_sizes=[384, 512, 768],
137
+ num_attention_heads=[6, 9, 12],
138
+ depths=[4, 4, 4],
139
+ key_dim=[32, 32, 32],
140
+ drop_path_rate=0.1,
141
+ ),
142
+ }
143
+
144
+ if model_name:
145
+ convert_weight_and_push(
146
+ names_to_hidden_sizes[model_name], model_name, names_to_config[model_name], save_directory, push_to_hub
147
+ )
148
+ else:
149
+ for model_name, config in names_to_config.items():
150
+ convert_weight_and_push(names_to_hidden_sizes[model_name], model_name, config, save_directory, push_to_hub)
151
+ return config, expected_shape
152
+
153
+
154
+ if __name__ == "__main__":
155
+ parser = argparse.ArgumentParser()
156
+ # Required parameters
157
+ parser.add_argument(
158
+ "--model_name",
159
+ default=None,
160
+ type=str,
161
+ help="The name of the model you wish to convert, it must be one of the supported Levit* architecture,",
162
+ )
163
+ parser.add_argument(
164
+ "--pytorch_dump_folder_path",
165
+ default="levit-dump-folder/",
166
+ type=Path,
167
+ required=False,
168
+ help="Path to the output PyTorch model directory.",
169
+ )
170
+ parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub")
171
+ parser.add_argument(
172
+ "--no-push_to_hub",
173
+ dest="push_to_hub",
174
+ action="store_false",
175
+ help="Do not push model and image processor to the hub",
176
+ )
177
+
178
+ args = parser.parse_args()
179
+ pytorch_dump_folder_path: Path = args.pytorch_dump_folder_path
180
+ pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
181
+ convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/levit/feature_extraction_levit.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Feature extractor class for LeViT."""
16
+
17
+ import warnings
18
+
19
+ from ...utils import logging
20
+ from ...utils.import_utils import requires
21
+ from .image_processing_levit import LevitImageProcessor
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ @requires(backends=("vision",))
28
+ class LevitFeatureExtractor(LevitImageProcessor):
29
+ def __init__(self, *args, **kwargs) -> None:
30
+ warnings.warn(
31
+ "The class LevitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
32
+ " use LevitImageProcessor instead.",
33
+ FutureWarning,
34
+ )
35
+ super().__init__(*args, **kwargs)
36
+
37
+
38
+ __all__ = ["LevitFeatureExtractor"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/levit/image_processing_levit.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Image processor class for LeViT."""
16
+
17
+ from collections.abc import Iterable
18
+ from typing import Optional, Union
19
+
20
+ import numpy as np
21
+
22
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
23
+ from ...image_transforms import (
24
+ get_resize_output_image_size,
25
+ resize,
26
+ to_channel_dimension_format,
27
+ )
28
+ from ...image_utils import (
29
+ IMAGENET_DEFAULT_MEAN,
30
+ IMAGENET_DEFAULT_STD,
31
+ ChannelDimension,
32
+ ImageInput,
33
+ PILImageResampling,
34
+ infer_channel_dimension_format,
35
+ is_scaled_image,
36
+ make_list_of_images,
37
+ to_numpy_array,
38
+ valid_images,
39
+ validate_preprocess_arguments,
40
+ )
41
+ from ...utils import TensorType, filter_out_non_signature_kwargs, logging
42
+ from ...utils.import_utils import requires
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+
48
+ @requires(backends=("vision",))
49
+ class LevitImageProcessor(BaseImageProcessor):
50
+ r"""
51
+ Constructs a LeViT image processor.
52
+
53
+ Args:
54
+ do_resize (`bool`, *optional*, defaults to `True`):
55
+ Wwhether to resize the shortest edge of the input to int(256/224 *`size`). Can be overridden by the
56
+ `do_resize` parameter in the `preprocess` method.
57
+ size (`dict[str, int]`, *optional*, defaults to `{"shortest_edge": 224}`):
58
+ Size of the output image after resizing. If size is a dict with keys "width" and "height", the image will
59
+ be resized to `(size["height"], size["width"])`. If size is a dict with key "shortest_edge", the shortest
60
+ edge value `c` is rescaled to `int(c * (256/224))`. The smaller edge of the image will be matched to this
61
+ value i.e, if height > width, then image will be rescaled to `(size["shortest_egde"] * height / width,
62
+ size["shortest_egde"])`. Can be overridden by the `size` parameter in the `preprocess` method.
63
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
64
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
65
+ `preprocess` method.
66
+ do_center_crop (`bool`, *optional*, defaults to `True`):
67
+ Whether or not to center crop the input to `(crop_size["height"], crop_size["width"])`. Can be overridden
68
+ by the `do_center_crop` parameter in the `preprocess` method.
69
+ crop_size (`Dict`, *optional*, defaults to `{"height": 224, "width": 224}`):
70
+ Desired image size after `center_crop`. Can be overridden by the `crop_size` parameter in the `preprocess`
71
+ method.
72
+ do_rescale (`bool`, *optional*, defaults to `True`):
73
+ Controls whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
74
+ `do_rescale` parameter in the `preprocess` method.
75
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
76
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
77
+ `preprocess` method.
78
+ do_normalize (`bool`, *optional*, defaults to `True`):
79
+ Controls whether to normalize the image. Can be overridden by the `do_normalize` parameter in the
80
+ `preprocess` method.
81
+ image_mean (`list[int]`, *optional*, defaults to `[0.485, 0.456, 0.406]`):
82
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
83
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
84
+ image_std (`list[int]`, *optional*, defaults to `[0.229, 0.224, 0.225]`):
85
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
86
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
87
+ """
88
+
89
+ model_input_names = ["pixel_values"]
90
+
91
+ def __init__(
92
+ self,
93
+ do_resize: bool = True,
94
+ size: Optional[dict[str, int]] = None,
95
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
96
+ do_center_crop: bool = True,
97
+ crop_size: Optional[dict[str, int]] = None,
98
+ do_rescale: bool = True,
99
+ rescale_factor: Union[int, float] = 1 / 255,
100
+ do_normalize: bool = True,
101
+ image_mean: Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN,
102
+ image_std: Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD,
103
+ **kwargs,
104
+ ) -> None:
105
+ super().__init__(**kwargs)
106
+ size = size if size is not None else {"shortest_edge": 224}
107
+ size = get_size_dict(size, default_to_square=False)
108
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
109
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
110
+
111
+ self.do_resize = do_resize
112
+ self.size = size
113
+ self.resample = resample
114
+ self.do_center_crop = do_center_crop
115
+ self.crop_size = crop_size
116
+ self.do_rescale = do_rescale
117
+ self.rescale_factor = rescale_factor
118
+ self.do_normalize = do_normalize
119
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
120
+ self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
121
+
122
+ def resize(
123
+ self,
124
+ image: np.ndarray,
125
+ size: dict[str, int],
126
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
127
+ data_format: Optional[Union[str, ChannelDimension]] = None,
128
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
129
+ **kwargs,
130
+ ) -> np.ndarray:
131
+ """
132
+ Resize an image.
133
+
134
+ If size is a dict with keys "width" and "height", the image will be resized to `(size["height"],
135
+ size["width"])`.
136
+
137
+ If size is a dict with key "shortest_edge", the shortest edge value `c` is rescaled to `int(c * (256/224))`.
138
+ The smaller edge of the image will be matched to this value i.e, if height > width, then image will be rescaled
139
+ to `(size["shortest_egde"] * height / width, size["shortest_egde"])`.
140
+
141
+ Args:
142
+ image (`np.ndarray`):
143
+ Image to resize.
144
+ size (`dict[str, int]`):
145
+ Size of the output image after resizing. If size is a dict with keys "width" and "height", the image
146
+ will be resized to (height, width). If size is a dict with key "shortest_edge", the shortest edge value
147
+ `c` is rescaled to int(`c` * (256/224)). The smaller edge of the image will be matched to this value
148
+ i.e, if height > width, then image will be rescaled to (size * height / width, size).
149
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
150
+ Resampling filter to use when resiizing the image.
151
+ data_format (`str` or `ChannelDimension`, *optional*):
152
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
153
+ input_data_format (`ChannelDimension` or `str`, *optional*):
154
+ The channel dimension format of the input image. If not provided, it will be inferred.
155
+ """
156
+ size_dict = get_size_dict(size, default_to_square=False)
157
+ # size_dict is a dict with either keys "height" and "width" or "shortest_edge"
158
+ if "shortest_edge" in size:
159
+ shortest_edge = int((256 / 224) * size["shortest_edge"])
160
+ output_size = get_resize_output_image_size(
161
+ image, size=shortest_edge, default_to_square=False, input_data_format=input_data_format
162
+ )
163
+ size_dict = {"height": output_size[0], "width": output_size[1]}
164
+ if "height" not in size_dict or "width" not in size_dict:
165
+ raise ValueError(
166
+ f"Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}"
167
+ )
168
+ return resize(
169
+ image,
170
+ size=(size_dict["height"], size_dict["width"]),
171
+ resample=resample,
172
+ data_format=data_format,
173
+ input_data_format=input_data_format,
174
+ **kwargs,
175
+ )
176
+
177
+ @filter_out_non_signature_kwargs()
178
+ def preprocess(
179
+ self,
180
+ images: ImageInput,
181
+ do_resize: Optional[bool] = None,
182
+ size: Optional[dict[str, int]] = None,
183
+ resample: PILImageResampling = None,
184
+ do_center_crop: Optional[bool] = None,
185
+ crop_size: Optional[dict[str, int]] = None,
186
+ do_rescale: Optional[bool] = None,
187
+ rescale_factor: Optional[float] = None,
188
+ do_normalize: Optional[bool] = None,
189
+ image_mean: Optional[Union[float, Iterable[float]]] = None,
190
+ image_std: Optional[Union[float, Iterable[float]]] = None,
191
+ return_tensors: Optional[TensorType] = None,
192
+ data_format: ChannelDimension = ChannelDimension.FIRST,
193
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
194
+ ) -> BatchFeature:
195
+ """
196
+ Preprocess an image or batch of images to be used as input to a LeViT model.
197
+
198
+ Args:
199
+ images (`ImageInput`):
200
+ Image or batch of images to preprocess. Expects a single or batch of images with pixel values ranging
201
+ from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.
202
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
203
+ Whether to resize the image.
204
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
205
+ Size of the output image after resizing. If size is a dict with keys "width" and "height", the image
206
+ will be resized to (height, width). If size is a dict with key "shortest_edge", the shortest edge value
207
+ `c` is rescaled to int(`c` * (256/224)). The smaller edge of the image will be matched to this value
208
+ i.e, if height > width, then image will be rescaled to (size * height / width, size).
209
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
210
+ Resampling filter to use when resiizing the image.
211
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
212
+ Whether to center crop the image.
213
+ crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`):
214
+ Size of the output image after center cropping. Crops images to (crop_size["height"],
215
+ crop_size["width"]).
216
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
217
+ Whether to rescale the image pixel values by `rescaling_factor` - typical to values between 0 and 1.
218
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
219
+ Factor to rescale the image pixel values by.
220
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
221
+ Whether to normalize the image pixel values by `image_mean` and `image_std`.
222
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
223
+ Mean to normalize the image pixel values by.
224
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
225
+ Standard deviation to normalize the image pixel values by.
226
+ return_tensors (`str` or `TensorType`, *optional*):
227
+ The type of tensors to return. Can be one of:
228
+ - Unset: Return a list of `np.ndarray`.
229
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
230
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
231
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
232
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
233
+ data_format (`str` or `ChannelDimension`, *optional*, defaults to `ChannelDimension.FIRST`):
234
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
235
+ image is used. Can be one of:
236
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
237
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
238
+ input_data_format (`ChannelDimension` or `str`, *optional*):
239
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
240
+ from the input image. Can be one of:
241
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
242
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
243
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
244
+ """
245
+ do_resize = do_resize if do_resize is not None else self.do_resize
246
+ resample = resample if resample is not None else self.resample
247
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
248
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
249
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
250
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
251
+ image_mean = image_mean if image_mean is not None else self.image_mean
252
+ image_std = image_std if image_std is not None else self.image_std
253
+
254
+ size = size if size is not None else self.size
255
+ size = get_size_dict(size, default_to_square=False)
256
+ crop_size = crop_size if crop_size is not None else self.crop_size
257
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
258
+ images = make_list_of_images(images)
259
+
260
+ if not valid_images(images):
261
+ raise ValueError(
262
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
263
+ "torch.Tensor, tf.Tensor or jax.ndarray."
264
+ )
265
+ validate_preprocess_arguments(
266
+ do_rescale=do_rescale,
267
+ rescale_factor=rescale_factor,
268
+ do_normalize=do_normalize,
269
+ image_mean=image_mean,
270
+ image_std=image_std,
271
+ do_center_crop=do_center_crop,
272
+ crop_size=crop_size,
273
+ do_resize=do_resize,
274
+ size=size,
275
+ resample=resample,
276
+ )
277
+ # All transformations expect numpy arrays.
278
+ images = [to_numpy_array(image) for image in images]
279
+
280
+ if do_rescale and is_scaled_image(images[0]):
281
+ logger.warning_once(
282
+ "It looks like you are trying to rescale already rescaled images. If the input"
283
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
284
+ )
285
+
286
+ if input_data_format is None:
287
+ # We assume that all images have the same channel dimension format.
288
+ input_data_format = infer_channel_dimension_format(images[0])
289
+
290
+ if do_resize:
291
+ images = [self.resize(image, size, resample, input_data_format=input_data_format) for image in images]
292
+
293
+ if do_center_crop:
294
+ images = [self.center_crop(image, crop_size, input_data_format=input_data_format) for image in images]
295
+
296
+ if do_rescale:
297
+ images = [self.rescale(image, rescale_factor, input_data_format=input_data_format) for image in images]
298
+
299
+ if do_normalize:
300
+ images = [
301
+ self.normalize(image, image_mean, image_std, input_data_format=input_data_format) for image in images
302
+ ]
303
+
304
+ images = [
305
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
306
+ ]
307
+
308
+ data = {"pixel_values": images}
309
+ return BatchFeature(data=data, tensor_type=return_tensors)
310
+
311
+
312
+ __all__ = ["LevitImageProcessor"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/levit/image_processing_levit_fast.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Fast Image processor class for LeViT."""
16
+
17
+ from ...image_processing_utils_fast import BaseImageProcessorFast, SizeDict
18
+ from ...image_transforms import (
19
+ ChannelDimension,
20
+ get_resize_output_image_size,
21
+ )
22
+ from ...image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling
23
+ from ...utils import auto_docstring, is_torch_available, is_torchvision_available, is_torchvision_v2_available
24
+
25
+
26
+ if is_torch_available():
27
+ import torch
28
+
29
+ if is_torchvision_available():
30
+ if is_torchvision_v2_available():
31
+ from torchvision.transforms.v2 import functional as F
32
+ else:
33
+ from torchvision.transforms import functional as F
34
+
35
+
36
+ @auto_docstring
37
+ class LevitImageProcessorFast(BaseImageProcessorFast):
38
+ resample = PILImageResampling.BICUBIC
39
+ image_mean = IMAGENET_DEFAULT_MEAN
40
+ image_std = IMAGENET_DEFAULT_STD
41
+ size = {"shortest_edge": 224}
42
+ default_to_square = False
43
+ crop_size = {"height": 224, "width": 224}
44
+ do_resize = True
45
+ do_center_crop = True
46
+ do_rescale = True
47
+ do_normalize = True
48
+ do_convert_rgb = None
49
+
50
+ def resize(
51
+ self,
52
+ image: torch.Tensor,
53
+ size: SizeDict,
54
+ interpolation: "F.InterpolationMode" = None,
55
+ **kwargs,
56
+ ) -> torch.Tensor:
57
+ """
58
+ Resize an image.
59
+
60
+ If size is a dict with keys "width" and "height", the image will be resized to `(size["height"],
61
+ size["width"])`.
62
+
63
+ If size is a dict with key "shortest_edge", the shortest edge value `c` is rescaled to `int(c * (256/224))`.
64
+ The smaller edge of the image will be matched to this value i.e, if height > width, then image will be rescaled
65
+ to `(size["shortest_egde"] * height / width, size["shortest_egde"])`.
66
+
67
+ Args:
68
+ image (`torch.Tensor`):
69
+ Image to resize.
70
+ size (`SizeDict`):
71
+ Size of the output image after resizing. If size is a dict with keys "width" and "height", the image
72
+ will be resized to (height, width). If size is a dict with key "shortest_edge", the shortest edge value
73
+ `c` is rescaled to int(`c` * (256/224)). The smaller edge of the image will be matched to this value
74
+ i.e, if height > width, then image will be rescaled to (size * height / width, size).
75
+ interpolation (`InterpolationMode`, *optional*, defaults to `InterpolationMode.BICUBIC`):
76
+ Resampling filter to use when resiizing the image.
77
+ """
78
+ interpolation = interpolation if interpolation is not None else F.InterpolationMode.BICUBIC
79
+ if size.shortest_edge:
80
+ shortest_edge = int((256 / 224) * size["shortest_edge"])
81
+ new_size = get_resize_output_image_size(
82
+ image, size=shortest_edge, default_to_square=False, input_data_format=ChannelDimension.FIRST
83
+ )
84
+ elif size.height and size.width:
85
+ new_size = (size.height, size.width)
86
+ else:
87
+ raise ValueError(
88
+ f"Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size.keys()} {size.keys()}."
89
+ )
90
+ return F.resize(
91
+ image,
92
+ size=new_size,
93
+ interpolation=interpolation,
94
+ **kwargs,
95
+ )
96
+
97
+
98
+ __all__ = ["LevitImageProcessorFast"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/levit/modeling_levit.py ADDED
@@ -0,0 +1,677 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """PyTorch LeViT model."""
16
+
17
+ import itertools
18
+ from dataclasses import dataclass
19
+ from typing import Optional, 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 ...modeling_outputs import (
27
+ BaseModelOutputWithNoAttention,
28
+ BaseModelOutputWithPoolingAndNoAttention,
29
+ ImageClassifierOutputWithNoAttention,
30
+ ModelOutput,
31
+ )
32
+ from ...modeling_utils import PreTrainedModel
33
+ from ...utils import auto_docstring, logging
34
+ from .configuration_levit import LevitConfig
35
+
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+
40
+ @dataclass
41
+ @auto_docstring(
42
+ custom_intro="""
43
+ Output type of [`LevitForImageClassificationWithTeacher`].
44
+ """
45
+ )
46
+ class LevitForImageClassificationWithTeacherOutput(ModelOutput):
47
+ r"""
48
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
49
+ Prediction scores as the average of the `cls_logits` and `distillation_logits`.
50
+ cls_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
51
+ Prediction scores of the classification head (i.e. the linear layer on top of the final hidden state of the
52
+ class token).
53
+ distillation_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
54
+ Prediction scores of the distillation head (i.e. the linear layer on top of the final hidden state of the
55
+ distillation token).
56
+ """
57
+
58
+ logits: Optional[torch.FloatTensor] = None
59
+ cls_logits: Optional[torch.FloatTensor] = None
60
+ distillation_logits: Optional[torch.FloatTensor] = None
61
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
62
+
63
+
64
+ class LevitConvEmbeddings(nn.Module):
65
+ """
66
+ LeViT Conv Embeddings with Batch Norm, used in the initial patch embedding layer.
67
+ """
68
+
69
+ def __init__(
70
+ self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, groups=1, bn_weight_init=1
71
+ ):
72
+ super().__init__()
73
+ self.convolution = nn.Conv2d(
74
+ in_channels, out_channels, kernel_size, stride, padding, dilation=dilation, groups=groups, bias=False
75
+ )
76
+ self.batch_norm = nn.BatchNorm2d(out_channels)
77
+
78
+ def forward(self, embeddings):
79
+ embeddings = self.convolution(embeddings)
80
+ embeddings = self.batch_norm(embeddings)
81
+ return embeddings
82
+
83
+
84
+ class LevitPatchEmbeddings(nn.Module):
85
+ """
86
+ LeViT patch embeddings, for final embeddings to be passed to transformer blocks. It consists of multiple
87
+ `LevitConvEmbeddings`.
88
+ """
89
+
90
+ def __init__(self, config):
91
+ super().__init__()
92
+ self.embedding_layer_1 = LevitConvEmbeddings(
93
+ config.num_channels, config.hidden_sizes[0] // 8, config.kernel_size, config.stride, config.padding
94
+ )
95
+ self.activation_layer_1 = nn.Hardswish()
96
+
97
+ self.embedding_layer_2 = LevitConvEmbeddings(
98
+ config.hidden_sizes[0] // 8, config.hidden_sizes[0] // 4, config.kernel_size, config.stride, config.padding
99
+ )
100
+ self.activation_layer_2 = nn.Hardswish()
101
+
102
+ self.embedding_layer_3 = LevitConvEmbeddings(
103
+ config.hidden_sizes[0] // 4, config.hidden_sizes[0] // 2, config.kernel_size, config.stride, config.padding
104
+ )
105
+ self.activation_layer_3 = nn.Hardswish()
106
+
107
+ self.embedding_layer_4 = LevitConvEmbeddings(
108
+ config.hidden_sizes[0] // 2, config.hidden_sizes[0], config.kernel_size, config.stride, config.padding
109
+ )
110
+ self.num_channels = config.num_channels
111
+
112
+ def forward(self, pixel_values):
113
+ num_channels = pixel_values.shape[1]
114
+ if num_channels != self.num_channels:
115
+ raise ValueError(
116
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
117
+ )
118
+ embeddings = self.embedding_layer_1(pixel_values)
119
+ embeddings = self.activation_layer_1(embeddings)
120
+ embeddings = self.embedding_layer_2(embeddings)
121
+ embeddings = self.activation_layer_2(embeddings)
122
+ embeddings = self.embedding_layer_3(embeddings)
123
+ embeddings = self.activation_layer_3(embeddings)
124
+ embeddings = self.embedding_layer_4(embeddings)
125
+ return embeddings.flatten(2).transpose(1, 2)
126
+
127
+
128
+ class MLPLayerWithBN(nn.Module):
129
+ def __init__(self, input_dim, output_dim, bn_weight_init=1):
130
+ super().__init__()
131
+ self.linear = nn.Linear(in_features=input_dim, out_features=output_dim, bias=False)
132
+ self.batch_norm = nn.BatchNorm1d(output_dim)
133
+
134
+ def forward(self, hidden_state):
135
+ hidden_state = self.linear(hidden_state)
136
+ hidden_state = self.batch_norm(hidden_state.flatten(0, 1)).reshape_as(hidden_state)
137
+ return hidden_state
138
+
139
+
140
+ class LevitSubsample(nn.Module):
141
+ def __init__(self, stride, resolution):
142
+ super().__init__()
143
+ self.stride = stride
144
+ self.resolution = resolution
145
+
146
+ def forward(self, hidden_state):
147
+ batch_size, _, channels = hidden_state.shape
148
+ hidden_state = hidden_state.view(batch_size, self.resolution, self.resolution, channels)[
149
+ :, :: self.stride, :: self.stride
150
+ ].reshape(batch_size, -1, channels)
151
+ return hidden_state
152
+
153
+
154
+ class LevitAttention(nn.Module):
155
+ def __init__(self, hidden_sizes, key_dim, num_attention_heads, attention_ratio, resolution):
156
+ super().__init__()
157
+ self.num_attention_heads = num_attention_heads
158
+ self.scale = key_dim**-0.5
159
+ self.key_dim = key_dim
160
+ self.attention_ratio = attention_ratio
161
+ self.out_dim_keys_values = attention_ratio * key_dim * num_attention_heads + key_dim * num_attention_heads * 2
162
+ self.out_dim_projection = attention_ratio * key_dim * num_attention_heads
163
+
164
+ self.queries_keys_values = MLPLayerWithBN(hidden_sizes, self.out_dim_keys_values)
165
+ self.activation = nn.Hardswish()
166
+ self.projection = MLPLayerWithBN(self.out_dim_projection, hidden_sizes, bn_weight_init=0)
167
+
168
+ points = list(itertools.product(range(resolution), range(resolution)))
169
+ len_points = len(points)
170
+ attention_offsets, indices = {}, []
171
+ for p1 in points:
172
+ for p2 in points:
173
+ offset = (abs(p1[0] - p2[0]), abs(p1[1] - p2[1]))
174
+ if offset not in attention_offsets:
175
+ attention_offsets[offset] = len(attention_offsets)
176
+ indices.append(attention_offsets[offset])
177
+
178
+ self.attention_bias_cache = {}
179
+ self.attention_biases = torch.nn.Parameter(torch.zeros(num_attention_heads, len(attention_offsets)))
180
+ self.register_buffer(
181
+ "attention_bias_idxs", torch.LongTensor(indices).view(len_points, len_points), persistent=False
182
+ )
183
+
184
+ @torch.no_grad()
185
+ def train(self, mode=True):
186
+ super().train(mode)
187
+ if mode and self.attention_bias_cache:
188
+ self.attention_bias_cache = {} # clear ab cache
189
+
190
+ def get_attention_biases(self, device):
191
+ if self.training:
192
+ return self.attention_biases[:, self.attention_bias_idxs]
193
+ else:
194
+ device_key = str(device)
195
+ if device_key not in self.attention_bias_cache:
196
+ self.attention_bias_cache[device_key] = self.attention_biases[:, self.attention_bias_idxs]
197
+ return self.attention_bias_cache[device_key]
198
+
199
+ def forward(self, hidden_state):
200
+ batch_size, seq_length, _ = hidden_state.shape
201
+ queries_keys_values = self.queries_keys_values(hidden_state)
202
+ query, key, value = queries_keys_values.view(batch_size, seq_length, self.num_attention_heads, -1).split(
203
+ [self.key_dim, self.key_dim, self.attention_ratio * self.key_dim], dim=3
204
+ )
205
+ query = query.permute(0, 2, 1, 3)
206
+ key = key.permute(0, 2, 1, 3)
207
+ value = value.permute(0, 2, 1, 3)
208
+
209
+ attention = query @ key.transpose(-2, -1) * self.scale + self.get_attention_biases(hidden_state.device)
210
+ attention = attention.softmax(dim=-1)
211
+ hidden_state = (attention @ value).transpose(1, 2).reshape(batch_size, seq_length, self.out_dim_projection)
212
+ hidden_state = self.projection(self.activation(hidden_state))
213
+ return hidden_state
214
+
215
+
216
+ class LevitAttentionSubsample(nn.Module):
217
+ def __init__(
218
+ self,
219
+ input_dim,
220
+ output_dim,
221
+ key_dim,
222
+ num_attention_heads,
223
+ attention_ratio,
224
+ stride,
225
+ resolution_in,
226
+ resolution_out,
227
+ ):
228
+ super().__init__()
229
+ self.num_attention_heads = num_attention_heads
230
+ self.scale = key_dim**-0.5
231
+ self.key_dim = key_dim
232
+ self.attention_ratio = attention_ratio
233
+ self.out_dim_keys_values = attention_ratio * key_dim * num_attention_heads + key_dim * num_attention_heads
234
+ self.out_dim_projection = attention_ratio * key_dim * num_attention_heads
235
+ self.resolution_out = resolution_out
236
+ # resolution_in is the initial resolution, resolution_out is final resolution after downsampling
237
+ self.keys_values = MLPLayerWithBN(input_dim, self.out_dim_keys_values)
238
+ self.queries_subsample = LevitSubsample(stride, resolution_in)
239
+ self.queries = MLPLayerWithBN(input_dim, key_dim * num_attention_heads)
240
+ self.activation = nn.Hardswish()
241
+ self.projection = MLPLayerWithBN(self.out_dim_projection, output_dim)
242
+
243
+ self.attention_bias_cache = {}
244
+
245
+ points = list(itertools.product(range(resolution_in), range(resolution_in)))
246
+ points_ = list(itertools.product(range(resolution_out), range(resolution_out)))
247
+ len_points, len_points_ = len(points), len(points_)
248
+ attention_offsets, indices = {}, []
249
+ for p1 in points_:
250
+ for p2 in points:
251
+ size = 1
252
+ offset = (abs(p1[0] * stride - p2[0] + (size - 1) / 2), abs(p1[1] * stride - p2[1] + (size - 1) / 2))
253
+ if offset not in attention_offsets:
254
+ attention_offsets[offset] = len(attention_offsets)
255
+ indices.append(attention_offsets[offset])
256
+
257
+ self.attention_biases = torch.nn.Parameter(torch.zeros(num_attention_heads, len(attention_offsets)))
258
+ self.register_buffer(
259
+ "attention_bias_idxs", torch.LongTensor(indices).view(len_points_, len_points), persistent=False
260
+ )
261
+
262
+ @torch.no_grad()
263
+ def train(self, mode=True):
264
+ super().train(mode)
265
+ if mode and self.attention_bias_cache:
266
+ self.attention_bias_cache = {} # clear ab cache
267
+
268
+ def get_attention_biases(self, device):
269
+ if self.training:
270
+ return self.attention_biases[:, self.attention_bias_idxs]
271
+ else:
272
+ device_key = str(device)
273
+ if device_key not in self.attention_bias_cache:
274
+ self.attention_bias_cache[device_key] = self.attention_biases[:, self.attention_bias_idxs]
275
+ return self.attention_bias_cache[device_key]
276
+
277
+ def forward(self, hidden_state):
278
+ batch_size, seq_length, _ = hidden_state.shape
279
+ key, value = (
280
+ self.keys_values(hidden_state)
281
+ .view(batch_size, seq_length, self.num_attention_heads, -1)
282
+ .split([self.key_dim, self.attention_ratio * self.key_dim], dim=3)
283
+ )
284
+ key = key.permute(0, 2, 1, 3)
285
+ value = value.permute(0, 2, 1, 3)
286
+
287
+ query = self.queries(self.queries_subsample(hidden_state))
288
+ query = query.view(batch_size, self.resolution_out**2, self.num_attention_heads, self.key_dim).permute(
289
+ 0, 2, 1, 3
290
+ )
291
+
292
+ attention = query @ key.transpose(-2, -1) * self.scale + self.get_attention_biases(hidden_state.device)
293
+ attention = attention.softmax(dim=-1)
294
+ hidden_state = (attention @ value).transpose(1, 2).reshape(batch_size, -1, self.out_dim_projection)
295
+ hidden_state = self.projection(self.activation(hidden_state))
296
+ return hidden_state
297
+
298
+
299
+ class LevitMLPLayer(nn.Module):
300
+ """
301
+ MLP Layer with `2X` expansion in contrast to ViT with `4X`.
302
+ """
303
+
304
+ def __init__(self, input_dim, hidden_dim):
305
+ super().__init__()
306
+ self.linear_up = MLPLayerWithBN(input_dim, hidden_dim)
307
+ self.activation = nn.Hardswish()
308
+ self.linear_down = MLPLayerWithBN(hidden_dim, input_dim)
309
+
310
+ def forward(self, hidden_state):
311
+ hidden_state = self.linear_up(hidden_state)
312
+ hidden_state = self.activation(hidden_state)
313
+ hidden_state = self.linear_down(hidden_state)
314
+ return hidden_state
315
+
316
+
317
+ class LevitResidualLayer(nn.Module):
318
+ """
319
+ Residual Block for LeViT
320
+ """
321
+
322
+ def __init__(self, module, drop_rate):
323
+ super().__init__()
324
+ self.module = module
325
+ self.drop_rate = drop_rate
326
+
327
+ def forward(self, hidden_state):
328
+ if self.training and self.drop_rate > 0:
329
+ rnd = torch.rand(hidden_state.size(0), 1, 1, device=hidden_state.device)
330
+ rnd = rnd.ge_(self.drop_rate).div(1 - self.drop_rate).detach()
331
+ hidden_state = hidden_state + self.module(hidden_state) * rnd
332
+ return hidden_state
333
+ else:
334
+ hidden_state = hidden_state + self.module(hidden_state)
335
+ return hidden_state
336
+
337
+
338
+ class LevitStage(nn.Module):
339
+ """
340
+ LeViT Stage consisting of `LevitMLPLayer` and `LevitAttention` layers.
341
+ """
342
+
343
+ def __init__(
344
+ self,
345
+ config,
346
+ idx,
347
+ hidden_sizes,
348
+ key_dim,
349
+ depths,
350
+ num_attention_heads,
351
+ attention_ratio,
352
+ mlp_ratio,
353
+ down_ops,
354
+ resolution_in,
355
+ ):
356
+ super().__init__()
357
+ self.layers = []
358
+ self.config = config
359
+ self.resolution_in = resolution_in
360
+ # resolution_in is the initial resolution, resolution_out is final resolution after downsampling
361
+ for _ in range(depths):
362
+ self.layers.append(
363
+ LevitResidualLayer(
364
+ LevitAttention(hidden_sizes, key_dim, num_attention_heads, attention_ratio, resolution_in),
365
+ self.config.drop_path_rate,
366
+ )
367
+ )
368
+ if mlp_ratio > 0:
369
+ hidden_dim = hidden_sizes * mlp_ratio
370
+ self.layers.append(
371
+ LevitResidualLayer(LevitMLPLayer(hidden_sizes, hidden_dim), self.config.drop_path_rate)
372
+ )
373
+
374
+ if down_ops[0] == "Subsample":
375
+ self.resolution_out = (self.resolution_in - 1) // down_ops[5] + 1
376
+ self.layers.append(
377
+ LevitAttentionSubsample(
378
+ *self.config.hidden_sizes[idx : idx + 2],
379
+ key_dim=down_ops[1],
380
+ num_attention_heads=down_ops[2],
381
+ attention_ratio=down_ops[3],
382
+ stride=down_ops[5],
383
+ resolution_in=resolution_in,
384
+ resolution_out=self.resolution_out,
385
+ )
386
+ )
387
+ self.resolution_in = self.resolution_out
388
+ if down_ops[4] > 0:
389
+ hidden_dim = self.config.hidden_sizes[idx + 1] * down_ops[4]
390
+ self.layers.append(
391
+ LevitResidualLayer(
392
+ LevitMLPLayer(self.config.hidden_sizes[idx + 1], hidden_dim), self.config.drop_path_rate
393
+ )
394
+ )
395
+
396
+ self.layers = nn.ModuleList(self.layers)
397
+
398
+ def get_resolution(self):
399
+ return self.resolution_in
400
+
401
+ def forward(self, hidden_state):
402
+ for layer in self.layers:
403
+ hidden_state = layer(hidden_state)
404
+ return hidden_state
405
+
406
+
407
+ class LevitEncoder(nn.Module):
408
+ """
409
+ LeViT Encoder consisting of multiple `LevitStage` stages.
410
+ """
411
+
412
+ def __init__(self, config):
413
+ super().__init__()
414
+ self.config = config
415
+ resolution = self.config.image_size // self.config.patch_size
416
+ self.stages = []
417
+ self.config.down_ops.append([""])
418
+
419
+ for stage_idx in range(len(config.depths)):
420
+ stage = LevitStage(
421
+ config,
422
+ stage_idx,
423
+ config.hidden_sizes[stage_idx],
424
+ config.key_dim[stage_idx],
425
+ config.depths[stage_idx],
426
+ config.num_attention_heads[stage_idx],
427
+ config.attention_ratio[stage_idx],
428
+ config.mlp_ratio[stage_idx],
429
+ config.down_ops[stage_idx],
430
+ resolution,
431
+ )
432
+ resolution = stage.get_resolution()
433
+ self.stages.append(stage)
434
+
435
+ self.stages = nn.ModuleList(self.stages)
436
+
437
+ def forward(self, hidden_state, output_hidden_states=False, return_dict=True):
438
+ all_hidden_states = () if output_hidden_states else None
439
+
440
+ for stage in self.stages:
441
+ if output_hidden_states:
442
+ all_hidden_states = all_hidden_states + (hidden_state,)
443
+ hidden_state = stage(hidden_state)
444
+
445
+ if output_hidden_states:
446
+ all_hidden_states = all_hidden_states + (hidden_state,)
447
+ if not return_dict:
448
+ return tuple(v for v in [hidden_state, all_hidden_states] if v is not None)
449
+
450
+ return BaseModelOutputWithNoAttention(last_hidden_state=hidden_state, hidden_states=all_hidden_states)
451
+
452
+
453
+ class LevitClassificationLayer(nn.Module):
454
+ """
455
+ LeViT Classification Layer
456
+ """
457
+
458
+ def __init__(self, input_dim, output_dim):
459
+ super().__init__()
460
+ self.batch_norm = nn.BatchNorm1d(input_dim)
461
+ self.linear = nn.Linear(input_dim, output_dim)
462
+
463
+ def forward(self, hidden_state):
464
+ hidden_state = self.batch_norm(hidden_state)
465
+ logits = self.linear(hidden_state)
466
+ return logits
467
+
468
+
469
+ @auto_docstring
470
+ class LevitPreTrainedModel(PreTrainedModel):
471
+ config: LevitConfig
472
+ base_model_prefix = "levit"
473
+ main_input_name = "pixel_values"
474
+ _no_split_modules = ["LevitResidualLayer"]
475
+
476
+ def _init_weights(self, module):
477
+ """Initialize the weights"""
478
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
479
+ # Slightly different from the TF version which uses truncated_normal for initialization
480
+ # cf https://github.com/pytorch/pytorch/pull/5617
481
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
482
+ if module.bias is not None:
483
+ module.bias.data.zero_()
484
+ elif isinstance(module, (nn.BatchNorm1d, nn.BatchNorm2d)):
485
+ module.bias.data.zero_()
486
+ module.weight.data.fill_(1.0)
487
+
488
+
489
+ @auto_docstring
490
+ class LevitModel(LevitPreTrainedModel):
491
+ def __init__(self, config):
492
+ super().__init__(config)
493
+ self.config = config
494
+ self.patch_embeddings = LevitPatchEmbeddings(config)
495
+ self.encoder = LevitEncoder(config)
496
+ # Initialize weights and apply final processing
497
+ self.post_init()
498
+
499
+ @auto_docstring
500
+ def forward(
501
+ self,
502
+ pixel_values: Optional[torch.FloatTensor] = None,
503
+ output_hidden_states: Optional[bool] = None,
504
+ return_dict: Optional[bool] = None,
505
+ ) -> Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
506
+ output_hidden_states = (
507
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
508
+ )
509
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
510
+
511
+ if pixel_values is None:
512
+ raise ValueError("You have to specify pixel_values")
513
+
514
+ embeddings = self.patch_embeddings(pixel_values)
515
+ encoder_outputs = self.encoder(
516
+ embeddings,
517
+ output_hidden_states=output_hidden_states,
518
+ return_dict=return_dict,
519
+ )
520
+
521
+ last_hidden_state = encoder_outputs[0]
522
+
523
+ # global average pooling, (batch_size, seq_length, hidden_sizes) -> (batch_size, hidden_sizes)
524
+ pooled_output = last_hidden_state.mean(dim=1)
525
+
526
+ if not return_dict:
527
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
528
+
529
+ return BaseModelOutputWithPoolingAndNoAttention(
530
+ last_hidden_state=last_hidden_state,
531
+ pooler_output=pooled_output,
532
+ hidden_states=encoder_outputs.hidden_states,
533
+ )
534
+
535
+
536
+ @auto_docstring(
537
+ custom_intro="""
538
+ Levit Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
539
+ ImageNet.
540
+ """
541
+ )
542
+ class LevitForImageClassification(LevitPreTrainedModel):
543
+ def __init__(self, config):
544
+ super().__init__(config)
545
+ self.config = config
546
+ self.num_labels = config.num_labels
547
+ self.levit = LevitModel(config)
548
+
549
+ # Classifier head
550
+ self.classifier = (
551
+ LevitClassificationLayer(config.hidden_sizes[-1], config.num_labels)
552
+ if config.num_labels > 0
553
+ else torch.nn.Identity()
554
+ )
555
+
556
+ # Initialize weights and apply final processing
557
+ self.post_init()
558
+
559
+ @auto_docstring
560
+ def forward(
561
+ self,
562
+ pixel_values: Optional[torch.FloatTensor] = None,
563
+ labels: Optional[torch.LongTensor] = None,
564
+ output_hidden_states: Optional[bool] = None,
565
+ return_dict: Optional[bool] = None,
566
+ ) -> Union[tuple, ImageClassifierOutputWithNoAttention]:
567
+ r"""
568
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
569
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
570
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
571
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
572
+ """
573
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
574
+
575
+ outputs = self.levit(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
576
+
577
+ sequence_output = outputs[0]
578
+ sequence_output = sequence_output.mean(1)
579
+ logits = self.classifier(sequence_output)
580
+
581
+ loss = None
582
+ if labels is not None:
583
+ if self.config.problem_type is None:
584
+ if self.num_labels == 1:
585
+ self.config.problem_type = "regression"
586
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
587
+ self.config.problem_type = "single_label_classification"
588
+ else:
589
+ self.config.problem_type = "multi_label_classification"
590
+
591
+ if self.config.problem_type == "regression":
592
+ loss_fct = MSELoss()
593
+ if self.num_labels == 1:
594
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
595
+ else:
596
+ loss = loss_fct(logits, labels)
597
+ elif self.config.problem_type == "single_label_classification":
598
+ loss_fct = CrossEntropyLoss()
599
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
600
+ elif self.config.problem_type == "multi_label_classification":
601
+ loss_fct = BCEWithLogitsLoss()
602
+ loss = loss_fct(logits, labels)
603
+ if not return_dict:
604
+ output = (logits,) + outputs[2:]
605
+ return ((loss,) + output) if loss is not None else output
606
+
607
+ return ImageClassifierOutputWithNoAttention(
608
+ loss=loss,
609
+ logits=logits,
610
+ hidden_states=outputs.hidden_states,
611
+ )
612
+
613
+
614
+ @auto_docstring(
615
+ custom_intro="""
616
+ LeViT Model transformer with image classification heads on top (a linear layer on top of the final hidden state and
617
+ a linear layer on top of the final hidden state of the distillation token) e.g. for ImageNet. .. warning::
618
+ This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet
619
+ supported.
620
+ """
621
+ )
622
+ class LevitForImageClassificationWithTeacher(LevitPreTrainedModel):
623
+ def __init__(self, config):
624
+ super().__init__(config)
625
+ self.config = config
626
+ self.num_labels = config.num_labels
627
+ self.levit = LevitModel(config)
628
+
629
+ # Classifier head
630
+ self.classifier = (
631
+ LevitClassificationLayer(config.hidden_sizes[-1], config.num_labels)
632
+ if config.num_labels > 0
633
+ else torch.nn.Identity()
634
+ )
635
+ self.classifier_distill = (
636
+ LevitClassificationLayer(config.hidden_sizes[-1], config.num_labels)
637
+ if config.num_labels > 0
638
+ else torch.nn.Identity()
639
+ )
640
+
641
+ # Initialize weights and apply final processing
642
+ self.post_init()
643
+
644
+ @auto_docstring
645
+ def forward(
646
+ self,
647
+ pixel_values: Optional[torch.FloatTensor] = None,
648
+ output_hidden_states: Optional[bool] = None,
649
+ return_dict: Optional[bool] = None,
650
+ ) -> Union[tuple, LevitForImageClassificationWithTeacherOutput]:
651
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
652
+
653
+ outputs = self.levit(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
654
+
655
+ sequence_output = outputs[0]
656
+ sequence_output = sequence_output.mean(1)
657
+ cls_logits, distill_logits = self.classifier(sequence_output), self.classifier_distill(sequence_output)
658
+ logits = (cls_logits + distill_logits) / 2
659
+
660
+ if not return_dict:
661
+ output = (logits, cls_logits, distill_logits) + outputs[2:]
662
+ return output
663
+
664
+ return LevitForImageClassificationWithTeacherOutput(
665
+ logits=logits,
666
+ cls_logits=cls_logits,
667
+ distillation_logits=distill_logits,
668
+ hidden_states=outputs.hidden_states,
669
+ )
670
+
671
+
672
+ __all__ = [
673
+ "LevitForImageClassification",
674
+ "LevitForImageClassificationWithTeacher",
675
+ "LevitModel",
676
+ "LevitPreTrainedModel",
677
+ ]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lfm2/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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_lfm2 import *
22
+ from .modeling_lfm2 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-5cbfd9f64dbc/environment/source/src/transformers/models/lfm2/configuration_lfm2.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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 Optional
15
+
16
+ from ...configuration_utils import PretrainedConfig
17
+
18
+
19
+ class Lfm2Config(PretrainedConfig):
20
+ r"""
21
+ This is the configuration class to store the configuration of a [`Lfm2Model`]. It is used to instantiate a LFM2
22
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
23
+ defaults will yield a similar configuration to that of the LFM2-1.2B model.
24
+ e.g. [LiquidAI/LFM2-1.2B](https://huggingface.co/LiquidAI/LFM2-1.2B)
25
+
26
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
27
+ documentation from [`PretrainedConfig`] for more information.
28
+
29
+
30
+ Args:
31
+ vocab_size (`int`, *optional*, defaults to 65536):
32
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
33
+ `inputs_ids` passed when calling [`Lfm2Model`]
34
+ hidden_size (`int`, *optional*, defaults to 2560):
35
+ Dimension of the hidden representations.
36
+ intermediate_size (`int`, *optional*, defaults to 12288):
37
+ Dimension of the MLP representations.
38
+ num_hidden_layers (`int`, *optional*, defaults to 32):
39
+ Number of hidden layers in the Transformer decoder.
40
+ num_attention_heads (`int`, *optional*, defaults to 32):
41
+ Number of attention heads for each attention layer in the Transformer decoder.
42
+ num_key_value_heads (`int`, *optional*, defaults to 8):
43
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
44
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
45
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
46
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
47
+ by meanpooling all the original heads within that group. For more details, check out [this
48
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
49
+ `num_attention_heads`.
50
+ max_position_embeddings (`int`, *optional*, defaults to 128000):
51
+ The maximum sequence length that this model might ever be used with. Lfm2 1 supports up to 2048 tokens,
52
+ Lfm2 2 up to 4096, CodeLfm2 up to 16384.
53
+ initializer_range (`float`, *optional*, defaults to 0.02):
54
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
55
+ norm_eps (`float`, *optional*, defaults to 1e-05):
56
+ The epsilon used by the rms normalization layers.
57
+ use_cache (`bool`, *optional*, defaults to `True`):
58
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
59
+ relevant if `config.is_decoder=True`.
60
+ pad_token_id (`int`, *optional*, defaults to 0):
61
+ Padding token id.
62
+ bos_token_id (`int`, *optional*, defaults to 1):
63
+ Beginning of stream token id.
64
+ eos_token_id (`int`, *optional*, defaults to 2):
65
+ End of stream token id.
66
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
67
+ Whether to tie weight embeddings
68
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
69
+ The base period of the RoPE embeddings.
70
+ conv_bias (`bool`, *optional*, defaults to `False`):
71
+ Whether to use bias in the conv layers.
72
+ conv_L_cache (`int`, *optional*, defaults to 3):
73
+ L_cache dim in the conv layers.
74
+ block_multiple_of (`int`, *optional*, defaults to 256):
75
+ Multiple for the `intermediate_size`.
76
+ block_ffn_dim_multiplier (`float`, *optional*, defaults to 1.0):
77
+ Multiplier for the `intermediate_size`.
78
+ block_auto_adjust_ff_dim (`bool`, *optional*, defaults to `True`):
79
+ Whether to adjust the dim of the `intermediate_size`.
80
+ full_attn_idxs (`Optional`, *optional*):
81
+ Index of the layers which use attention.
82
+ layer_types (`Optional`, *optional*):
83
+ Type of each layers.
84
+
85
+ ```python
86
+ >>> from transformers import Lfm2Model, Lfm2Config
87
+
88
+ >>> # Initializing a LFM2 model
89
+ >>> configuration = Lfm2Config()
90
+
91
+ >>> # Initializing a model from the LFM2-1.2B style configuration
92
+ >>> model = Lfm2Model(configuration)
93
+
94
+ >>> # Accessing the model configuration
95
+ >>> configuration = model.config
96
+ ```"""
97
+
98
+ model_type = "lfm2"
99
+ keys_to_ignore_at_inference = ["past_key_values"]
100
+
101
+ def __init__(
102
+ self,
103
+ vocab_size: int = 65536,
104
+ hidden_size: int = 2560,
105
+ intermediate_size: int = 12288,
106
+ num_hidden_layers: int = 32,
107
+ num_attention_heads: int = 32,
108
+ num_key_value_heads: int = 8,
109
+ max_position_embeddings: int = 128_000,
110
+ initializer_range: float = 0.02,
111
+ norm_eps: float = 0.00001,
112
+ use_cache: bool = True,
113
+ pad_token_id: int = 0,
114
+ bos_token_id: int = 1,
115
+ eos_token_id: int = 2,
116
+ tie_word_embeddings: bool = True,
117
+ rope_theta: float = 1000000.0,
118
+ conv_bias: bool = False,
119
+ conv_L_cache: int = 3,
120
+ block_multiple_of: int = 256,
121
+ block_ffn_dim_multiplier: float = 1.0,
122
+ block_auto_adjust_ff_dim: bool = True,
123
+ full_attn_idxs: Optional[list[int]] = None,
124
+ layer_types: Optional[list[str]] = None,
125
+ **kwargs,
126
+ ):
127
+ self.vocab_size = vocab_size
128
+ self.hidden_size = hidden_size
129
+ self.num_hidden_layers = num_hidden_layers
130
+ self.rope_theta = kwargs.get("theta", rope_theta) # to fit original config keys
131
+ self.max_position_embeddings = max_position_embeddings
132
+ self.use_cache = use_cache
133
+ self.norm_eps = norm_eps
134
+ self.initializer_range = initializer_range
135
+
136
+ # attn operator config
137
+ self.num_attention_heads = num_attention_heads
138
+ self.num_key_value_heads = num_key_value_heads
139
+
140
+ # custom operator config
141
+ self.conv_bias = conv_bias
142
+ self.conv_L_cache = conv_L_cache
143
+
144
+ # MLP config
145
+ self.intermediate_size = kwargs.get("block_ff_dim", intermediate_size) # to fit original config keys
146
+ self.block_multiple_of = block_multiple_of
147
+ self.block_ffn_dim_multiplier = block_ffn_dim_multiplier
148
+ self.block_auto_adjust_ff_dim = block_auto_adjust_ff_dim
149
+
150
+ self.layer_types = layer_types
151
+ if self.layer_types is None:
152
+ full_attn_idxs = full_attn_idxs if full_attn_idxs is not None else list(range(num_hidden_layers))
153
+ self.layer_types = ["full_attention" if i in full_attn_idxs else "conv" for i in range(num_hidden_layers)]
154
+
155
+ tie_word_embeddings = kwargs.get("tie_embedding", tie_word_embeddings) # to fit original config keys
156
+ super().__init__(
157
+ pad_token_id=pad_token_id,
158
+ bos_token_id=bos_token_id,
159
+ eos_token_id=eos_token_id,
160
+ tie_word_embeddings=tie_word_embeddings,
161
+ **kwargs,
162
+ )
163
+
164
+
165
+ __all__ = ["Lfm2Config"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lfm2/modeling_lfm2.py ADDED
@@ -0,0 +1,760 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/lfm2/modular_lfm2.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_lfm2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ from typing import Any, Callable, Optional, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ from torch import nn
25
+
26
+ from ...cache_utils import Cache
27
+ from ...generation import GenerationMixin
28
+ from ...integrations import use_kernel_forward_from_hub
29
+ from ...masking_utils import create_causal_mask
30
+ from ...modeling_layers import GradientCheckpointingLayer
31
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
32
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
33
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
34
+ from ...processing_utils import Unpack
35
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
36
+ from ...utils.deprecation import deprecate_kwarg
37
+ from ...utils.generic import check_model_inputs
38
+ from ...utils.import_utils import is_causal_conv1d_available
39
+ from .configuration_lfm2 import Lfm2Config
40
+
41
+
42
+ if is_causal_conv1d_available():
43
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
44
+ else:
45
+ causal_conv1d_fn, causal_conv1d_update = None, None
46
+
47
+
48
+ @use_kernel_forward_from_hub("RMSNorm")
49
+ class Lfm2RMSNorm(nn.Module):
50
+ def __init__(self, hidden_size, eps=1e-6):
51
+ """
52
+ Lfm2RMSNorm is equivalent to T5LayerNorm
53
+ """
54
+ super().__init__()
55
+ self.weight = nn.Parameter(torch.ones(hidden_size))
56
+ self.variance_epsilon = eps
57
+
58
+ def forward(self, hidden_states):
59
+ input_dtype = hidden_states.dtype
60
+ hidden_states = hidden_states.to(torch.float32)
61
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
62
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
63
+ return self.weight * hidden_states.to(input_dtype)
64
+
65
+ def extra_repr(self):
66
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
67
+
68
+
69
+ class Lfm2RotaryEmbedding(nn.Module):
70
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
71
+
72
+ def __init__(self, config: Lfm2Config, device=None):
73
+ super().__init__()
74
+ # BC: "rope_type" was originally "type"
75
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
76
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
77
+ else:
78
+ self.rope_type = "default"
79
+ self.max_seq_len_cached = config.max_position_embeddings
80
+ self.original_max_seq_len = config.max_position_embeddings
81
+
82
+ self.config = config
83
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
84
+
85
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
86
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
87
+ self.original_inv_freq = self.inv_freq
88
+
89
+ @torch.no_grad()
90
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
91
+ def forward(self, x, position_ids):
92
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
93
+ position_ids_expanded = position_ids[:, None, :].float()
94
+
95
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
96
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
97
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
98
+ emb = torch.cat((freqs, freqs), dim=-1)
99
+ cos = emb.cos() * self.attention_scaling
100
+ sin = emb.sin() * self.attention_scaling
101
+
102
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
103
+
104
+
105
+ class Lfm2MLP(nn.Module):
106
+ def __init__(self, config: Lfm2Config):
107
+ super().__init__()
108
+ intermediate_size = config.intermediate_size
109
+ if config.block_auto_adjust_ff_dim:
110
+ intermediate_size = int(2 * intermediate_size / 3)
111
+ # custom dim factor multiplier
112
+ if config.block_ffn_dim_multiplier is not None:
113
+ intermediate_size = int(config.block_ffn_dim_multiplier * intermediate_size)
114
+ intermediate_size = config.block_multiple_of * (
115
+ (intermediate_size + config.block_multiple_of - 1) // config.block_multiple_of
116
+ )
117
+ self.w1 = nn.Linear(config.hidden_size, intermediate_size, bias=False)
118
+ self.w3 = nn.Linear(config.hidden_size, intermediate_size, bias=False)
119
+ self.w2 = nn.Linear(intermediate_size, config.hidden_size, bias=False)
120
+
121
+ def forward(self, x):
122
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
123
+
124
+
125
+ class Lfm2HybridConvCache:
126
+ """
127
+ Attention and conv cache for Lfm2.
128
+
129
+ It stores the Key and Value states as a list of tensors, one for each layer.
130
+ Attention layer cache shape: `[batch_size, num_heads, seq_len, head_dim]`.
131
+ Conv layer cache shape: `[batch_size, hidden_size, L_cache-1]`.
132
+ """
133
+
134
+ # Override @property existing in Cache
135
+ max_batch_size = None
136
+ is_compileable = False
137
+ key_cache = None
138
+ value_cache = None
139
+
140
+ def __init__(
141
+ self,
142
+ config: Lfm2Config,
143
+ max_batch_size: int,
144
+ dtype: torch.dtype = torch.float32,
145
+ device: Union[torch.device, str, None] = None,
146
+ ):
147
+ self.key_cache = []
148
+ self.value_cache = []
149
+ self.max_batch_size = max_batch_size
150
+ self.layer_types = config.layer_types
151
+ self.first_attention_layer = self.layer_types.index("full_attention")
152
+ self.conv_L_cache = config.conv_L_cache
153
+ self._dtype = dtype
154
+
155
+ self.conv_cache: list[torch.Tensor] = []
156
+ device = torch.device(device) if device is not None else None
157
+
158
+ for _ in range(config.num_hidden_layers):
159
+ conv_state = torch.zeros(
160
+ self.max_batch_size,
161
+ config.hidden_size,
162
+ self.conv_L_cache,
163
+ dtype=self._dtype,
164
+ device=device,
165
+ )
166
+ torch._dynamo.mark_static_address(conv_state)
167
+ self.conv_cache.append(conv_state)
168
+
169
+ def update(
170
+ self,
171
+ key_states: torch.Tensor,
172
+ value_states: torch.Tensor,
173
+ layer_idx: int,
174
+ cache_kwargs: Optional[dict[str, Any]] = None,
175
+ ) -> tuple[torch.Tensor, torch.Tensor]:
176
+ """
177
+ Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
178
+
179
+ Parameters:
180
+ key_states (`torch.Tensor`):
181
+ The new key states to cache.
182
+ value_states (`torch.Tensor`):
183
+ The new value states to cache.
184
+ layer_idx (`int`):
185
+ The index of the layer to cache the states for.
186
+ cache_kwargs (`Dict[str, Any]`, `optional`):
187
+ Additional arguments for the cache subclass. No additional arguments are used in `DynamicCache`.
188
+
189
+ Return:
190
+ A tuple containing the updated key and value states.
191
+ """
192
+ # Update the cache
193
+ if key_states is not None:
194
+ if len(self.key_cache) <= layer_idx:
195
+ # There may be skipped layers, fill them with empty lists
196
+ for _ in range(len(self.key_cache), layer_idx):
197
+ self.key_cache.append(torch.tensor([]))
198
+ self.value_cache.append(torch.tensor([]))
199
+ self.key_cache.append(key_states)
200
+ self.value_cache.append(value_states)
201
+ elif (
202
+ not self.key_cache[layer_idx].numel() # prefers not t.numel() to len(t) == 0 to export the model
203
+ ): # fills previously skipped layers; checking for tensor causes errors
204
+ self.key_cache[layer_idx] = key_states
205
+ self.value_cache[layer_idx] = value_states
206
+ else:
207
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=-2)
208
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=-2)
209
+
210
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
211
+
212
+ def reorder_cache(self, beam_idx: torch.LongTensor):
213
+ """Reorders the cache for beam search, given the selected beam indices."""
214
+ for layer_idx in range(len(self.key_cache)):
215
+ device = self.key_cache[layer_idx].device
216
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
217
+ device = self.value_cache[layer_idx].device
218
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
219
+
220
+ device = self.conv_cache[layer_idx].device
221
+ self.conv_cache[layer_idx] = self.conv_cache[layer_idx].index_select(0, beam_idx.to(device))
222
+
223
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
224
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
225
+ # take any layer that contains cache and not empty tensor
226
+ layer_idx = self.first_attention_layer if self.layer_types[layer_idx] != "full_attention" else layer_idx
227
+ if len(self.key_cache) <= layer_idx or self.key_cache[layer_idx].numel() == 0:
228
+ return 0
229
+ return self.key_cache[layer_idx].shape[-2]
230
+
231
+ def get_mask_sizes(self, cache_position: torch.Tensor, layer_idx: int) -> tuple[int, int]:
232
+ """
233
+ Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for
234
+ the given layer at `layer_idx`.
235
+ The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns (i.e. sliding_window, chunk_size),
236
+ for each layer.
237
+ """
238
+ full_mask_kv_offset = 0
239
+ query_length = cache_position.shape[0]
240
+ past_seen_tokens = self.get_seq_length()
241
+ kv_length = query_length + past_seen_tokens
242
+ return kv_length, full_mask_kv_offset
243
+
244
+ def crop(self, max_length: int):
245
+ """Crop the cache to the given length"""
246
+ if max_length < 0:
247
+ max_length = self.get_seq_length() - abs(max_length)
248
+
249
+ if self.get_seq_length() <= max_length:
250
+ return
251
+
252
+ for idx in range(len(self.key_cache)):
253
+ if self.key_cache[idx].numel():
254
+ self.key_cache[idx] = self.key_cache[idx][..., :max_length, :]
255
+ self.value_cache[idx] = self.value_cache[idx][..., :max_length, :]
256
+
257
+ def __len__(self) -> int:
258
+ return len(self.key_cache)
259
+
260
+ def __getitem__(self, layer_idx: int) -> tuple[torch.Tensor, torch.Tensor]:
261
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
262
+
263
+ def reset(self):
264
+ for layer_idx in range(len(self.conv_cache)):
265
+ # In-place ops prevent breaking the static address
266
+ self.conv_cache[layer_idx].zero_()
267
+
268
+
269
+ def rotate_half(x):
270
+ """Rotates half the hidden dims of the input."""
271
+ x1 = x[..., : x.shape[-1] // 2]
272
+ x2 = x[..., x.shape[-1] // 2 :]
273
+ return torch.cat((-x2, x1), dim=-1)
274
+
275
+
276
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
277
+ """Applies Rotary Position Embedding to the query and key tensors.
278
+
279
+ Args:
280
+ q (`torch.Tensor`): The query tensor.
281
+ k (`torch.Tensor`): The key tensor.
282
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
283
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
284
+ position_ids (`torch.Tensor`, *optional*):
285
+ Deprecated and unused.
286
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
287
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
288
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
289
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
290
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
291
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
292
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
293
+ Returns:
294
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
295
+ """
296
+ cos = cos.unsqueeze(unsqueeze_dim)
297
+ sin = sin.unsqueeze(unsqueeze_dim)
298
+ q_embed = (q * cos) + (rotate_half(q) * sin)
299
+ k_embed = (k * cos) + (rotate_half(k) * sin)
300
+ return q_embed, k_embed
301
+
302
+
303
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
304
+ """
305
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
306
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
307
+ """
308
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
309
+ if n_rep == 1:
310
+ return hidden_states
311
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
312
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
313
+
314
+
315
+ def eager_attention_forward(
316
+ module: nn.Module,
317
+ query: torch.Tensor,
318
+ key: torch.Tensor,
319
+ value: torch.Tensor,
320
+ attention_mask: Optional[torch.Tensor],
321
+ scaling: float,
322
+ dropout: float = 0.0,
323
+ **kwargs: Unpack[TransformersKwargs],
324
+ ):
325
+ key_states = repeat_kv(key, module.num_key_value_groups)
326
+ value_states = repeat_kv(value, module.num_key_value_groups)
327
+
328
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
329
+ if attention_mask is not None:
330
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
331
+ attn_weights = attn_weights + causal_mask
332
+
333
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
334
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
335
+ attn_output = torch.matmul(attn_weights, value_states)
336
+ attn_output = attn_output.transpose(1, 2).contiguous()
337
+
338
+ return attn_output, attn_weights
339
+
340
+
341
+ class Lfm2Attention(nn.Module):
342
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
343
+
344
+ def __init__(self, config: Lfm2Config, layer_idx: int):
345
+ super().__init__()
346
+ self.config = config
347
+ self.layer_idx = layer_idx
348
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
349
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
350
+ self.scaling = self.head_dim**-0.5
351
+ self.is_causal = True
352
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
353
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
354
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
355
+ self.out_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
356
+ self.q_layernorm = Lfm2RMSNorm(self.head_dim, eps=config.norm_eps)
357
+ self.k_layernorm = Lfm2RMSNorm(self.head_dim, eps=config.norm_eps)
358
+
359
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
360
+ def forward(
361
+ self,
362
+ hidden_states: torch.Tensor,
363
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
364
+ attention_mask: Optional[torch.Tensor],
365
+ past_key_values: Optional[Lfm2HybridConvCache] = None,
366
+ cache_position: Optional[torch.LongTensor] = None,
367
+ **kwargs,
368
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
369
+ input_shape = hidden_states.shape[:-1]
370
+ hidden_shape = (*input_shape, -1, self.head_dim)
371
+
372
+ query_states = self.q_layernorm(self.q_proj(hidden_states).view(*hidden_shape)).transpose(1, 2)
373
+ key_states = self.k_layernorm(self.k_proj(hidden_states).view(*hidden_shape)).transpose(1, 2)
374
+ value_states = self.v_proj(hidden_states).view(*hidden_shape).transpose(1, 2)
375
+
376
+ cos, sin = position_embeddings
377
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
378
+
379
+ if past_key_values is not None:
380
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
381
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
382
+
383
+ attention_interface: Callable = eager_attention_forward
384
+ if self.config._attn_implementation != "eager":
385
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
386
+
387
+ attn_output, attn_weights = attention_interface(
388
+ self,
389
+ query_states,
390
+ key_states,
391
+ value_states,
392
+ attention_mask,
393
+ dropout=0.0,
394
+ scaling=self.scaling,
395
+ **kwargs,
396
+ )
397
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
398
+ output = self.out_proj(attn_output)
399
+ return output, attn_weights
400
+
401
+
402
+ def apply_mask_to_padding_states(hidden_states, attention_mask):
403
+ """
404
+ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
405
+ """
406
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
407
+ dtype = hidden_states.dtype
408
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
409
+
410
+ return hidden_states
411
+
412
+
413
+ kernel_modules = (causal_conv1d_fn, causal_conv1d_update)
414
+ is_fast_path_available = all(kernel_modules)
415
+
416
+
417
+ class Lfm2ShortConv(nn.Module):
418
+ def __init__(
419
+ self,
420
+ config: Lfm2Config,
421
+ layer_idx: int,
422
+ ):
423
+ super().__init__()
424
+ self.config = config
425
+ self.layer_idx = layer_idx
426
+ self.L_cache = config.conv_L_cache
427
+ self.bias = config.conv_bias
428
+
429
+ self.conv = nn.Conv1d(
430
+ in_channels=config.hidden_size,
431
+ out_channels=config.hidden_size,
432
+ kernel_size=self.L_cache,
433
+ groups=config.hidden_size,
434
+ bias=self.bias,
435
+ padding=self.L_cache - 1,
436
+ )
437
+ self.in_proj = nn.Linear(config.hidden_size, 3 * config.hidden_size, bias=self.bias)
438
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=self.bias)
439
+
440
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
441
+ def cuda_kernels_forward(
442
+ self,
443
+ x: torch.Tensor,
444
+ past_key_values: Optional[Lfm2HybridConvCache] = None,
445
+ cache_position: Optional[torch.LongTensor] = None,
446
+ attention_mask: Optional[torch.Tensor] = None,
447
+ ):
448
+ x = apply_mask_to_padding_states(x, attention_mask)
449
+ BCx = self.in_proj(x).transpose(-1, -2)
450
+ B, C, x = BCx.chunk(3, dim=-2)
451
+
452
+ Bx = B * x
453
+
454
+ conv_weights = self.conv.weight.view(self.conv.weight.size(0), self.conv.weight.size(2))
455
+ if past_key_values is not None and cache_position[0] > 0:
456
+ conv_out = causal_conv1d_update(
457
+ Bx.squeeze(-1),
458
+ past_key_values.conv_cache[self.layer_idx],
459
+ conv_weights,
460
+ self.conv.bias,
461
+ None,
462
+ )
463
+ conv_out = conv_out.unsqueeze(-1)
464
+ else:
465
+ if past_key_values is not None:
466
+ conv_state = nn.functional.pad(Bx, (self.L_cache - Bx.shape[-1], 0))
467
+ past_key_values.conv_cache[self.layer_idx].copy_(conv_state)
468
+
469
+ conv_out = causal_conv1d_fn(Bx, conv_weights, self.conv.bias, activation=None)
470
+
471
+ y = C * conv_out
472
+ y = self.out_proj(y.transpose(-1, -2).contiguous())
473
+ return y
474
+
475
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
476
+ def slow_forward(
477
+ self,
478
+ x: torch.Tensor,
479
+ past_key_values: Optional[Lfm2HybridConvCache] = None,
480
+ cache_position: Optional[torch.LongTensor] = None,
481
+ attention_mask: Optional[torch.Tensor] = None,
482
+ ):
483
+ seqlen = x.shape[1]
484
+
485
+ x = apply_mask_to_padding_states(x, attention_mask)
486
+ BCx = self.in_proj(x).transpose(-1, -2)
487
+ B, C, x = BCx.chunk(3, dim=-2)
488
+
489
+ Bx = B * x
490
+
491
+ if past_key_values is not None and cache_position[0] > 0:
492
+ conv_state = past_key_values.conv_cache[self.layer_idx]
493
+ cache_position = cache_position.clamp(0, self.L_cache - 1)
494
+ conv_state = conv_state.roll(shifts=-1, dims=-1)
495
+ conv_state[:, :, cache_position] = Bx.to(device=conv_state.device, dtype=conv_state.dtype)
496
+ past_key_values.conv_cache[self.layer_idx].copy_(conv_state)
497
+ conv_out = torch.sum(conv_state.to(Bx.device) * self.conv.weight[:, 0, :], dim=-1)
498
+ if self.bias:
499
+ conv_out += self.conv.bias
500
+
501
+ conv_out = conv_out.unsqueeze(-1)
502
+ else:
503
+ if past_key_values is not None:
504
+ conv_state = nn.functional.pad(Bx, (self.L_cache - Bx.shape[-1], 0))
505
+ past_key_values.conv_cache[self.layer_idx].copy_(conv_state)
506
+
507
+ conv_out = self.conv(Bx)[..., :seqlen]
508
+
509
+ y = C * conv_out
510
+ y = y.transpose(-1, -2).contiguous()
511
+ y = self.out_proj(y)
512
+ return y
513
+
514
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
515
+ def forward(
516
+ self,
517
+ hidden_states: torch.Tensor,
518
+ past_key_values: Optional[Lfm2HybridConvCache] = None,
519
+ cache_position: Optional[torch.LongTensor] = None,
520
+ attention_mask: Optional[torch.Tensor] = None,
521
+ ):
522
+ if is_fast_path_available and "cuda" in hidden_states.device.type and not torch._dynamo.is_compiling():
523
+ return self.cuda_kernels_forward(hidden_states, past_key_values, cache_position, attention_mask)
524
+ return self.slow_forward(hidden_states, past_key_values, cache_position, attention_mask)
525
+
526
+
527
+ class Lfm2DecoderLayer(GradientCheckpointingLayer):
528
+ def __init__(self, config: Lfm2Config, layer_idx: int):
529
+ super().__init__()
530
+ self.is_attention_layer = config.layer_types[layer_idx] == "full_attention"
531
+
532
+ if self.is_attention_layer:
533
+ self.self_attn = Lfm2Attention(config, layer_idx)
534
+ else:
535
+ self.conv = Lfm2ShortConv(config, layer_idx)
536
+ self.feed_forward = Lfm2MLP(config)
537
+ self.operator_norm = Lfm2RMSNorm(config.hidden_size, eps=config.norm_eps)
538
+ self.ffn_norm = Lfm2RMSNorm(config.hidden_size, eps=config.norm_eps)
539
+
540
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
541
+ def forward(
542
+ self,
543
+ hidden_states: torch.Tensor,
544
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
545
+ attention_mask: Optional[torch.Tensor] = None,
546
+ position_ids: Optional[torch.LongTensor] = None,
547
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
548
+ cache_position: Optional[torch.LongTensor] = None,
549
+ **kwargs,
550
+ ) -> torch.Tensor:
551
+ residual = hidden_states
552
+ if self.is_attention_layer:
553
+ hidden_states, _ = self.self_attn(
554
+ hidden_states=self.operator_norm(hidden_states),
555
+ position_embeddings=position_embeddings,
556
+ attention_mask=attention_mask,
557
+ position_ids=position_ids,
558
+ past_key_values=past_key_values,
559
+ cache_position=cache_position,
560
+ **kwargs,
561
+ )
562
+ else:
563
+ hidden_states = self.conv(
564
+ hidden_states=self.operator_norm(hidden_states),
565
+ past_key_values=past_key_values,
566
+ cache_position=cache_position,
567
+ attention_mask=attention_mask,
568
+ )
569
+ hidden_states = hidden_states + residual
570
+ hidden_states = hidden_states + self.feed_forward(self.ffn_norm(hidden_states))
571
+
572
+ return hidden_states
573
+
574
+
575
+ @auto_docstring
576
+ class Lfm2PreTrainedModel(PreTrainedModel):
577
+ config: Lfm2Config
578
+ base_model_prefix = "model"
579
+ supports_gradient_checkpointing = True
580
+ _no_split_modules = ["Lfm2DecoderLayer"]
581
+ _skip_keys_device_placement = ["past_key_values"]
582
+ _supports_flash_attn = True
583
+ _supports_sdpa = True
584
+ _supports_flex_attn = True
585
+ _can_compile_fullgraph = False
586
+ _supports_attention_backend = True
587
+ _can_record_outputs = {
588
+ "hidden_states": Lfm2DecoderLayer,
589
+ "attentions": Lfm2Attention,
590
+ }
591
+
592
+
593
+ @auto_docstring
594
+ class Lfm2Model(Lfm2PreTrainedModel):
595
+ def __init__(self, config: Lfm2Config):
596
+ super().__init__(config)
597
+ self.padding_idx = config.pad_token_id
598
+ self.vocab_size = config.vocab_size
599
+
600
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
601
+ self.layers = nn.ModuleList(
602
+ [Lfm2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
603
+ )
604
+ self.rotary_emb = Lfm2RotaryEmbedding(config=config)
605
+ self.gradient_checkpointing = False
606
+ self.pos_emb = Lfm2RotaryEmbedding(config)
607
+ self.embedding_norm = Lfm2RMSNorm(config.hidden_size, eps=config.norm_eps)
608
+
609
+ # Initialize weights and apply final processing
610
+ self.post_init()
611
+
612
+ @check_model_inputs
613
+ @auto_docstring
614
+ def forward(
615
+ self,
616
+ input_ids: Optional[torch.LongTensor] = None,
617
+ attention_mask: Optional[torch.Tensor] = None,
618
+ position_ids: Optional[torch.LongTensor] = None,
619
+ past_key_values: Optional[Lfm2HybridConvCache] = None,
620
+ inputs_embeds: Optional[torch.FloatTensor] = None,
621
+ use_cache: Optional[bool] = None,
622
+ cache_position: Optional[torch.LongTensor] = None,
623
+ **kwargs: Unpack[TransformersKwargs],
624
+ ) -> BaseModelOutputWithPast:
625
+ if (input_ids is None) ^ (inputs_embeds is not None):
626
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
627
+
628
+ if inputs_embeds is None:
629
+ inputs_embeds = self.embed_tokens(input_ids)
630
+
631
+ if use_cache and past_key_values is None:
632
+ batch_size = inputs_embeds.shape[0]
633
+ past_key_values = Lfm2HybridConvCache(
634
+ config=self.config, max_batch_size=batch_size, dtype=self.dtype, device=self.device
635
+ )
636
+
637
+ if cache_position is None:
638
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
639
+ cache_position = torch.arange(
640
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
641
+ )
642
+
643
+ if position_ids is None:
644
+ position_ids = cache_position.unsqueeze(0)
645
+
646
+ causal_mask = create_causal_mask(
647
+ config=self.config,
648
+ input_embeds=inputs_embeds,
649
+ attention_mask=attention_mask,
650
+ cache_position=cache_position,
651
+ past_key_values=past_key_values,
652
+ position_ids=position_ids,
653
+ )
654
+
655
+ hidden_states = inputs_embeds
656
+ position_embeddings = self.pos_emb(hidden_states, position_ids)
657
+
658
+ # decoder layers
659
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
660
+ hidden_states = decoder_layer(
661
+ hidden_states,
662
+ attention_mask=causal_mask,
663
+ position_ids=position_ids,
664
+ past_key_values=past_key_values,
665
+ cache_position=cache_position,
666
+ position_embeddings=position_embeddings,
667
+ **kwargs,
668
+ )
669
+
670
+ hidden_states = self.embedding_norm(hidden_states)
671
+
672
+ return BaseModelOutputWithPast(
673
+ last_hidden_state=hidden_states,
674
+ past_key_values=past_key_values,
675
+ )
676
+
677
+
678
+ @auto_docstring
679
+ class Lfm2ForCausalLM(Lfm2PreTrainedModel, GenerationMixin):
680
+ _tied_weights_keys = ["lm_head.weight"]
681
+ _tp_plan = {"lm_head": "colwise_rep"}
682
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
683
+
684
+ def __init__(self, config):
685
+ super().__init__(config)
686
+ self.model = Lfm2Model(config)
687
+ self.vocab_size = config.vocab_size
688
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
689
+
690
+ # Initialize weights and apply final processing
691
+ self.post_init()
692
+
693
+ def set_decoder(self, decoder):
694
+ self.model = decoder
695
+
696
+ def get_decoder(self):
697
+ return self.model
698
+
699
+ @can_return_tuple
700
+ @auto_docstring
701
+ def forward(
702
+ self,
703
+ input_ids: Optional[torch.LongTensor] = None,
704
+ attention_mask: Optional[torch.Tensor] = None,
705
+ position_ids: Optional[torch.LongTensor] = None,
706
+ past_key_values: Optional[Cache] = None,
707
+ inputs_embeds: Optional[torch.FloatTensor] = None,
708
+ labels: Optional[torch.LongTensor] = None,
709
+ use_cache: Optional[bool] = None,
710
+ cache_position: Optional[torch.LongTensor] = None,
711
+ logits_to_keep: Union[int, torch.Tensor] = 0,
712
+ **kwargs: Unpack[TransformersKwargs],
713
+ ) -> CausalLMOutputWithPast:
714
+ r"""
715
+ Example:
716
+
717
+ ```python
718
+ >>> from transformers import AutoTokenizer, Lfm2ForCausalLM
719
+
720
+ >>> model = Lfm2ForCausalLM.from_pretrained("meta-lfm2/Lfm2-2-7b-hf")
721
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-lfm2/Lfm2-2-7b-hf")
722
+
723
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
724
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
725
+
726
+ >>> # Generate
727
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
728
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
729
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
730
+ ```"""
731
+ outputs: BaseModelOutputWithPast = self.model(
732
+ input_ids=input_ids,
733
+ attention_mask=attention_mask,
734
+ position_ids=position_ids,
735
+ past_key_values=past_key_values,
736
+ inputs_embeds=inputs_embeds,
737
+ use_cache=use_cache,
738
+ cache_position=cache_position,
739
+ **kwargs,
740
+ )
741
+
742
+ hidden_states = outputs.last_hidden_state
743
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
744
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
745
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
746
+
747
+ loss = None
748
+ if labels is not None:
749
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
750
+
751
+ return CausalLMOutputWithPast(
752
+ loss=loss,
753
+ logits=logits,
754
+ past_key_values=outputs.past_key_values,
755
+ hidden_states=outputs.hidden_states,
756
+ attentions=outputs.attentions,
757
+ )
758
+
759
+
760
+ __all__ = ["Lfm2ForCausalLM", "Lfm2Model", "Lfm2PreTrainedModel"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lfm2/modular_lfm2.py ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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 Any, Callable, Optional, Union
15
+
16
+ import torch
17
+ import torch.nn.functional as F
18
+ from torch import nn
19
+
20
+ from ...masking_utils import create_causal_mask
21
+ from ...modeling_layers import GradientCheckpointingLayer
22
+ from ...modeling_outputs import BaseModelOutputWithPast
23
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
24
+ from ...processing_utils import Unpack
25
+ from ...utils import TransformersKwargs, logging
26
+ from ...utils.deprecation import deprecate_kwarg
27
+ from ...utils.import_utils import is_causal_conv1d_available
28
+ from ..bamba.modeling_bamba import apply_mask_to_padding_states
29
+ from ..llama.modeling_llama import (
30
+ LlamaAttention,
31
+ LlamaForCausalLM,
32
+ LlamaModel,
33
+ LlamaPreTrainedModel,
34
+ LlamaRMSNorm,
35
+ LlamaRotaryEmbedding,
36
+ apply_rotary_pos_emb,
37
+ eager_attention_forward,
38
+ )
39
+ from .configuration_lfm2 import Lfm2Config
40
+
41
+
42
+ if is_causal_conv1d_available():
43
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
44
+ else:
45
+ causal_conv1d_fn, causal_conv1d_update = None, None
46
+
47
+
48
+ kernel_modules = (causal_conv1d_fn, causal_conv1d_update)
49
+ is_fast_path_available = all(kernel_modules)
50
+
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+
55
+ class Lfm2RMSNorm(LlamaRMSNorm):
56
+ pass
57
+
58
+
59
+ class Lfm2RotaryEmbedding(LlamaRotaryEmbedding):
60
+ pass
61
+
62
+
63
+ class Lfm2MLP(nn.Module):
64
+ def __init__(self, config: Lfm2Config):
65
+ super().__init__()
66
+ intermediate_size = config.intermediate_size
67
+ if config.block_auto_adjust_ff_dim:
68
+ intermediate_size = int(2 * intermediate_size / 3)
69
+ # custom dim factor multiplier
70
+ if config.block_ffn_dim_multiplier is not None:
71
+ intermediate_size = int(config.block_ffn_dim_multiplier * intermediate_size)
72
+ intermediate_size = config.block_multiple_of * (
73
+ (intermediate_size + config.block_multiple_of - 1) // config.block_multiple_of
74
+ )
75
+ self.w1 = nn.Linear(config.hidden_size, intermediate_size, bias=False)
76
+ self.w3 = nn.Linear(config.hidden_size, intermediate_size, bias=False)
77
+ self.w2 = nn.Linear(intermediate_size, config.hidden_size, bias=False)
78
+
79
+ def forward(self, x):
80
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
81
+
82
+
83
+ class Lfm2HybridConvCache:
84
+ """
85
+ Attention and conv cache for Lfm2.
86
+
87
+ It stores the Key and Value states as a list of tensors, one for each layer.
88
+ Attention layer cache shape: `[batch_size, num_heads, seq_len, head_dim]`.
89
+ Conv layer cache shape: `[batch_size, hidden_size, L_cache-1]`.
90
+ """
91
+
92
+ # Override @property existing in Cache
93
+ max_batch_size = None
94
+ is_compileable = False
95
+ key_cache = None
96
+ value_cache = None
97
+
98
+ def __init__(
99
+ self,
100
+ config: Lfm2Config,
101
+ max_batch_size: int,
102
+ dtype: torch.dtype = torch.float32,
103
+ device: Union[torch.device, str, None] = None,
104
+ ):
105
+ self.key_cache = []
106
+ self.value_cache = []
107
+ self.max_batch_size = max_batch_size
108
+ self.layer_types = config.layer_types
109
+ self.first_attention_layer = self.layer_types.index("full_attention")
110
+ self.conv_L_cache = config.conv_L_cache
111
+ self._dtype = dtype
112
+
113
+ self.conv_cache: list[torch.Tensor] = []
114
+ device = torch.device(device) if device is not None else None
115
+
116
+ for _ in range(config.num_hidden_layers):
117
+ conv_state = torch.zeros(
118
+ self.max_batch_size,
119
+ config.hidden_size,
120
+ self.conv_L_cache,
121
+ dtype=self._dtype,
122
+ device=device,
123
+ )
124
+ torch._dynamo.mark_static_address(conv_state)
125
+ self.conv_cache.append(conv_state)
126
+
127
+ def update(
128
+ self,
129
+ key_states: torch.Tensor,
130
+ value_states: torch.Tensor,
131
+ layer_idx: int,
132
+ cache_kwargs: Optional[dict[str, Any]] = None,
133
+ ) -> tuple[torch.Tensor, torch.Tensor]:
134
+ """
135
+ Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
136
+
137
+ Parameters:
138
+ key_states (`torch.Tensor`):
139
+ The new key states to cache.
140
+ value_states (`torch.Tensor`):
141
+ The new value states to cache.
142
+ layer_idx (`int`):
143
+ The index of the layer to cache the states for.
144
+ cache_kwargs (`Dict[str, Any]`, `optional`):
145
+ Additional arguments for the cache subclass. No additional arguments are used in `DynamicCache`.
146
+
147
+ Return:
148
+ A tuple containing the updated key and value states.
149
+ """
150
+ # Update the cache
151
+ if key_states is not None:
152
+ if len(self.key_cache) <= layer_idx:
153
+ # There may be skipped layers, fill them with empty lists
154
+ for _ in range(len(self.key_cache), layer_idx):
155
+ self.key_cache.append(torch.tensor([]))
156
+ self.value_cache.append(torch.tensor([]))
157
+ self.key_cache.append(key_states)
158
+ self.value_cache.append(value_states)
159
+ elif (
160
+ not self.key_cache[layer_idx].numel() # prefers not t.numel() to len(t) == 0 to export the model
161
+ ): # fills previously skipped layers; checking for tensor causes errors
162
+ self.key_cache[layer_idx] = key_states
163
+ self.value_cache[layer_idx] = value_states
164
+ else:
165
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=-2)
166
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=-2)
167
+
168
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
169
+
170
+ def reorder_cache(self, beam_idx: torch.LongTensor):
171
+ """Reorders the cache for beam search, given the selected beam indices."""
172
+ for layer_idx in range(len(self.key_cache)):
173
+ device = self.key_cache[layer_idx].device
174
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
175
+ device = self.value_cache[layer_idx].device
176
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
177
+
178
+ device = self.conv_cache[layer_idx].device
179
+ self.conv_cache[layer_idx] = self.conv_cache[layer_idx].index_select(0, beam_idx.to(device))
180
+
181
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
182
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
183
+ # take any layer that contains cache and not empty tensor
184
+ layer_idx = self.first_attention_layer if self.layer_types[layer_idx] != "full_attention" else layer_idx
185
+ if len(self.key_cache) <= layer_idx or self.key_cache[layer_idx].numel() == 0:
186
+ return 0
187
+ return self.key_cache[layer_idx].shape[-2]
188
+
189
+ def get_mask_sizes(self, cache_position: torch.Tensor, layer_idx: int) -> tuple[int, int]:
190
+ """
191
+ Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for
192
+ the given layer at `layer_idx`.
193
+ The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns (i.e. sliding_window, chunk_size),
194
+ for each layer.
195
+ """
196
+ full_mask_kv_offset = 0
197
+ query_length = cache_position.shape[0]
198
+ past_seen_tokens = self.get_seq_length()
199
+ kv_length = query_length + past_seen_tokens
200
+ return kv_length, full_mask_kv_offset
201
+
202
+ def crop(self, max_length: int):
203
+ """Crop the cache to the given length"""
204
+ if max_length < 0:
205
+ max_length = self.get_seq_length() - abs(max_length)
206
+
207
+ if self.get_seq_length() <= max_length:
208
+ return
209
+
210
+ for idx in range(len(self.key_cache)):
211
+ if self.key_cache[idx].numel():
212
+ self.key_cache[idx] = self.key_cache[idx][..., :max_length, :]
213
+ self.value_cache[idx] = self.value_cache[idx][..., :max_length, :]
214
+
215
+ def __len__(self) -> int:
216
+ return len(self.key_cache)
217
+
218
+ def __getitem__(self, layer_idx: int) -> tuple[torch.Tensor, torch.Tensor]:
219
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
220
+
221
+ def reset(self):
222
+ for layer_idx in range(len(self.conv_cache)):
223
+ # In-place ops prevent breaking the static address
224
+ self.conv_cache[layer_idx].zero_()
225
+
226
+
227
+ class Lfm2Attention(LlamaAttention):
228
+ def __init__(self, config: Lfm2Config, layer_idx: int):
229
+ super().__init__(config, layer_idx)
230
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
231
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
232
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
233
+ self.out_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
234
+ self.q_layernorm = Lfm2RMSNorm(self.head_dim, eps=config.norm_eps)
235
+ self.k_layernorm = Lfm2RMSNorm(self.head_dim, eps=config.norm_eps)
236
+ del self.o_proj
237
+ del self.attention_dropout
238
+
239
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
240
+ def forward(
241
+ self,
242
+ hidden_states: torch.Tensor,
243
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
244
+ attention_mask: Optional[torch.Tensor],
245
+ past_key_values: Optional[Lfm2HybridConvCache] = None,
246
+ cache_position: Optional[torch.LongTensor] = None,
247
+ **kwargs,
248
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
249
+ input_shape = hidden_states.shape[:-1]
250
+ hidden_shape = (*input_shape, -1, self.head_dim)
251
+
252
+ query_states = self.q_layernorm(self.q_proj(hidden_states).view(*hidden_shape)).transpose(1, 2)
253
+ key_states = self.k_layernorm(self.k_proj(hidden_states).view(*hidden_shape)).transpose(1, 2)
254
+ value_states = self.v_proj(hidden_states).view(*hidden_shape).transpose(1, 2)
255
+
256
+ cos, sin = position_embeddings
257
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
258
+
259
+ if past_key_values is not None:
260
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
261
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
262
+
263
+ attention_interface: Callable = eager_attention_forward
264
+ if self.config._attn_implementation != "eager":
265
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
266
+
267
+ attn_output, attn_weights = attention_interface(
268
+ self,
269
+ query_states,
270
+ key_states,
271
+ value_states,
272
+ attention_mask,
273
+ dropout=0.0,
274
+ scaling=self.scaling,
275
+ **kwargs,
276
+ )
277
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
278
+ output = self.out_proj(attn_output)
279
+ return output, attn_weights
280
+
281
+
282
+ class Lfm2ShortConv(nn.Module):
283
+ def __init__(
284
+ self,
285
+ config: Lfm2Config,
286
+ layer_idx: int,
287
+ ):
288
+ super().__init__()
289
+ self.config = config
290
+ self.layer_idx = layer_idx
291
+ self.L_cache = config.conv_L_cache
292
+ self.bias = config.conv_bias
293
+
294
+ self.conv = nn.Conv1d(
295
+ in_channels=config.hidden_size,
296
+ out_channels=config.hidden_size,
297
+ kernel_size=self.L_cache,
298
+ groups=config.hidden_size,
299
+ bias=self.bias,
300
+ padding=self.L_cache - 1,
301
+ )
302
+ self.in_proj = nn.Linear(config.hidden_size, 3 * config.hidden_size, bias=self.bias)
303
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=self.bias)
304
+
305
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
306
+ def cuda_kernels_forward(
307
+ self,
308
+ x: torch.Tensor,
309
+ past_key_values: Optional[Lfm2HybridConvCache] = None,
310
+ cache_position: Optional[torch.LongTensor] = None,
311
+ attention_mask: Optional[torch.Tensor] = None,
312
+ ):
313
+ x = apply_mask_to_padding_states(x, attention_mask)
314
+ BCx = self.in_proj(x).transpose(-1, -2)
315
+ B, C, x = BCx.chunk(3, dim=-2)
316
+
317
+ Bx = B * x
318
+
319
+ conv_weights = self.conv.weight.view(self.conv.weight.size(0), self.conv.weight.size(2))
320
+ if past_key_values is not None and cache_position[0] > 0:
321
+ conv_out = causal_conv1d_update(
322
+ Bx.squeeze(-1),
323
+ past_key_values.conv_cache[self.layer_idx],
324
+ conv_weights,
325
+ self.conv.bias,
326
+ None,
327
+ )
328
+ conv_out = conv_out.unsqueeze(-1)
329
+ else:
330
+ if past_key_values is not None:
331
+ conv_state = nn.functional.pad(Bx, (self.L_cache - Bx.shape[-1], 0))
332
+ past_key_values.conv_cache[self.layer_idx].copy_(conv_state)
333
+
334
+ conv_out = causal_conv1d_fn(Bx, conv_weights, self.conv.bias, activation=None)
335
+
336
+ y = C * conv_out
337
+ y = self.out_proj(y.transpose(-1, -2).contiguous())
338
+ return y
339
+
340
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
341
+ def slow_forward(
342
+ self,
343
+ x: torch.Tensor,
344
+ past_key_values: Optional[Lfm2HybridConvCache] = None,
345
+ cache_position: Optional[torch.LongTensor] = None,
346
+ attention_mask: Optional[torch.Tensor] = None,
347
+ ):
348
+ seqlen = x.shape[1]
349
+
350
+ x = apply_mask_to_padding_states(x, attention_mask)
351
+ BCx = self.in_proj(x).transpose(-1, -2)
352
+ B, C, x = BCx.chunk(3, dim=-2)
353
+
354
+ Bx = B * x
355
+
356
+ if past_key_values is not None and cache_position[0] > 0:
357
+ conv_state = past_key_values.conv_cache[self.layer_idx]
358
+ cache_position = cache_position.clamp(0, self.L_cache - 1)
359
+ conv_state = conv_state.roll(shifts=-1, dims=-1)
360
+ conv_state[:, :, cache_position] = Bx.to(device=conv_state.device, dtype=conv_state.dtype)
361
+ past_key_values.conv_cache[self.layer_idx].copy_(conv_state)
362
+ conv_out = torch.sum(conv_state.to(Bx.device) * self.conv.weight[:, 0, :], dim=-1)
363
+ if self.bias:
364
+ conv_out += self.conv.bias
365
+
366
+ conv_out = conv_out.unsqueeze(-1)
367
+ else:
368
+ if past_key_values is not None:
369
+ conv_state = nn.functional.pad(Bx, (self.L_cache - Bx.shape[-1], 0))
370
+ past_key_values.conv_cache[self.layer_idx].copy_(conv_state)
371
+
372
+ conv_out = self.conv(Bx)[..., :seqlen]
373
+
374
+ y = C * conv_out
375
+ y = y.transpose(-1, -2).contiguous()
376
+ y = self.out_proj(y)
377
+ return y
378
+
379
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
380
+ def forward(
381
+ self,
382
+ hidden_states: torch.Tensor,
383
+ past_key_values: Optional[Lfm2HybridConvCache] = None,
384
+ cache_position: Optional[torch.LongTensor] = None,
385
+ attention_mask: Optional[torch.Tensor] = None,
386
+ ):
387
+ if is_fast_path_available and "cuda" in hidden_states.device.type and not torch._dynamo.is_compiling():
388
+ return self.cuda_kernels_forward(hidden_states, past_key_values, cache_position, attention_mask)
389
+ return self.slow_forward(hidden_states, past_key_values, cache_position, attention_mask)
390
+
391
+
392
+ class Lfm2DecoderLayer(GradientCheckpointingLayer):
393
+ def __init__(self, config: Lfm2Config, layer_idx: int):
394
+ super().__init__()
395
+ self.is_attention_layer = config.layer_types[layer_idx] == "full_attention"
396
+
397
+ if self.is_attention_layer:
398
+ self.self_attn = Lfm2Attention(config, layer_idx)
399
+ else:
400
+ self.conv = Lfm2ShortConv(config, layer_idx)
401
+ self.feed_forward = Lfm2MLP(config)
402
+ self.operator_norm = Lfm2RMSNorm(config.hidden_size, eps=config.norm_eps)
403
+ self.ffn_norm = Lfm2RMSNorm(config.hidden_size, eps=config.norm_eps)
404
+
405
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
406
+ def forward(
407
+ self,
408
+ hidden_states: torch.Tensor,
409
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
410
+ attention_mask: Optional[torch.Tensor] = None,
411
+ position_ids: Optional[torch.LongTensor] = None,
412
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
413
+ cache_position: Optional[torch.LongTensor] = None,
414
+ **kwargs,
415
+ ) -> torch.Tensor:
416
+ residual = hidden_states
417
+ if self.is_attention_layer:
418
+ hidden_states, _ = self.self_attn(
419
+ hidden_states=self.operator_norm(hidden_states),
420
+ position_embeddings=position_embeddings,
421
+ attention_mask=attention_mask,
422
+ position_ids=position_ids,
423
+ past_key_values=past_key_values,
424
+ cache_position=cache_position,
425
+ **kwargs,
426
+ )
427
+ else:
428
+ hidden_states = self.conv(
429
+ hidden_states=self.operator_norm(hidden_states),
430
+ past_key_values=past_key_values,
431
+ cache_position=cache_position,
432
+ attention_mask=attention_mask,
433
+ )
434
+ hidden_states = hidden_states + residual
435
+ hidden_states = hidden_states + self.feed_forward(self.ffn_norm(hidden_states))
436
+
437
+ return hidden_states
438
+
439
+
440
+ class Lfm2PreTrainedModel(LlamaPreTrainedModel):
441
+ _can_compile_fullgraph = False
442
+
443
+
444
+ class Lfm2Model(LlamaModel):
445
+ def __init__(self, config: Lfm2Config):
446
+ super().__init__(config)
447
+ self.pos_emb = Lfm2RotaryEmbedding(config)
448
+ self.embedding_norm = Lfm2RMSNorm(config.hidden_size, eps=config.norm_eps)
449
+ del self.norm
450
+ del self.rotary_emv
451
+
452
+ def forward(
453
+ self,
454
+ input_ids: Optional[torch.LongTensor] = None,
455
+ attention_mask: Optional[torch.Tensor] = None,
456
+ position_ids: Optional[torch.LongTensor] = None,
457
+ past_key_values: Optional[Lfm2HybridConvCache] = None,
458
+ inputs_embeds: Optional[torch.FloatTensor] = None,
459
+ use_cache: Optional[bool] = None,
460
+ cache_position: Optional[torch.LongTensor] = None,
461
+ **kwargs: Unpack[TransformersKwargs],
462
+ ) -> BaseModelOutputWithPast:
463
+ if (input_ids is None) ^ (inputs_embeds is not None):
464
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
465
+
466
+ if inputs_embeds is None:
467
+ inputs_embeds = self.embed_tokens(input_ids)
468
+
469
+ if use_cache and past_key_values is None:
470
+ batch_size = inputs_embeds.shape[0]
471
+ past_key_values = Lfm2HybridConvCache(
472
+ config=self.config, max_batch_size=batch_size, dtype=self.dtype, device=self.device
473
+ )
474
+
475
+ if cache_position is None:
476
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
477
+ cache_position = torch.arange(
478
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
479
+ )
480
+
481
+ if position_ids is None:
482
+ position_ids = cache_position.unsqueeze(0)
483
+
484
+ causal_mask = create_causal_mask(
485
+ config=self.config,
486
+ input_embeds=inputs_embeds,
487
+ attention_mask=attention_mask,
488
+ cache_position=cache_position,
489
+ past_key_values=past_key_values,
490
+ position_ids=position_ids,
491
+ )
492
+
493
+ hidden_states = inputs_embeds
494
+ position_embeddings = self.pos_emb(hidden_states, position_ids)
495
+
496
+ # decoder layers
497
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
498
+ hidden_states = decoder_layer(
499
+ hidden_states,
500
+ attention_mask=causal_mask,
501
+ position_ids=position_ids,
502
+ past_key_values=past_key_values,
503
+ cache_position=cache_position,
504
+ position_embeddings=position_embeddings,
505
+ **kwargs,
506
+ )
507
+
508
+ hidden_states = self.embedding_norm(hidden_states)
509
+
510
+ return BaseModelOutputWithPast(
511
+ last_hidden_state=hidden_states,
512
+ past_key_values=past_key_values,
513
+ )
514
+
515
+
516
+ class Lfm2ForCausalLM(LlamaForCausalLM):
517
+ pass
518
+
519
+
520
+ __all__ = ["Lfm2ForCausalLM", "Lfm2Model", "Lfm2PreTrainedModel"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lightglue/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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_lightglue import *
22
+ from .image_processing_lightglue import *
23
+ from .modeling_lightglue 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-5cbfd9f64dbc/environment/source/src/transformers/models/lightglue/configuration_lightglue.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/lightglue/modular_lightglue.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_lightglue.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+
22
+ from ...configuration_utils import PretrainedConfig
23
+ from ..auto import CONFIG_MAPPING, AutoConfig
24
+ from ..superpoint import SuperPointConfig
25
+
26
+
27
+ class LightGlueConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`LightGlueForKeypointMatching`]. It is used to
30
+ instantiate a LightGlue model according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the LightGlue
32
+ [ETH-CVG/lightglue_superpoint](https://huggingface.co/ETH-CVG/lightglue_superpoint) 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
+ Args:
38
+ keypoint_detector_config (`Union[AutoConfig, dict]`, *optional*, defaults to `SuperPointConfig`):
39
+ The config object or dictionary of the keypoint detector.
40
+ descriptor_dim (`int`, *optional*, defaults to 256):
41
+ The dimension of the descriptors.
42
+ num_hidden_layers (`int`, *optional*, defaults to 9):
43
+ The number of self and cross attention layers.
44
+ num_attention_heads (`int`, *optional*, defaults to 4):
45
+ The number of heads in the multi-head attention.
46
+ num_key_value_heads (`int`, *optional*):
47
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
48
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
49
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
50
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
51
+ by meanpooling all the original heads within that group. For more details checkout [this
52
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
53
+ `num_attention_heads`.
54
+ depth_confidence (`float`, *optional*, defaults to 0.95):
55
+ The confidence threshold used to perform early stopping
56
+ width_confidence (`float`, *optional*, defaults to 0.99):
57
+ The confidence threshold used to prune points
58
+ filter_threshold (`float`, *optional*, defaults to 0.1):
59
+ The confidence threshold used to filter matches
60
+ initializer_range (`float`, *optional*, defaults to 0.02):
61
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
62
+ hidden_act (`str`, *optional*, defaults to `"gelu"`):
63
+ The activation function to be used in the hidden layers.
64
+ attention_dropout (`float`, *optional*, defaults to 0.0):
65
+ The dropout ratio for the attention probabilities.
66
+ attention_bias (`bool`, *optional*, defaults to `True`):
67
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
68
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
69
+ Whether to trust remote code when using other models than SuperPoint as keypoint detector.
70
+
71
+ Examples:
72
+ ```python
73
+ >>> from transformers import LightGlueConfig, LightGlueForKeypointMatching
74
+
75
+ >>> # Initializing a LightGlue style configuration
76
+ >>> configuration = LightGlueConfig()
77
+
78
+ >>> # Initializing a model from the LightGlue style configuration
79
+ >>> model = LightGlueForKeypointMatching(configuration)
80
+
81
+ >>> # Accessing the model configuration
82
+ >>> configuration = model.config
83
+ ```
84
+ """
85
+
86
+ model_type = "lightglue"
87
+ sub_configs = {"keypoint_detector_config": AutoConfig}
88
+
89
+ def __init__(
90
+ self,
91
+ keypoint_detector_config: SuperPointConfig = None,
92
+ descriptor_dim: int = 256,
93
+ num_hidden_layers: int = 9,
94
+ num_attention_heads: int = 4,
95
+ num_key_value_heads=None,
96
+ depth_confidence: float = 0.95,
97
+ width_confidence: float = 0.99,
98
+ filter_threshold: float = 0.1,
99
+ initializer_range: float = 0.02,
100
+ hidden_act: str = "gelu",
101
+ attention_dropout=0.0,
102
+ attention_bias=True,
103
+ trust_remote_code: bool = False,
104
+ **kwargs,
105
+ ):
106
+ # LightGlue can be used with other models than SuperPoint as keypoint detector
107
+ # We provide the trust_remote_code argument to allow the use of other models
108
+ # that are not registered in the CONFIG_MAPPING dictionary (for example DISK)
109
+ self.trust_remote_code = trust_remote_code
110
+
111
+ if descriptor_dim % num_attention_heads != 0:
112
+ raise ValueError("descriptor_dim % num_heads is different from zero")
113
+
114
+ self.descriptor_dim = descriptor_dim
115
+ self.num_hidden_layers = num_hidden_layers
116
+ self.num_attention_heads = num_attention_heads
117
+
118
+ # for backward compatibility
119
+ if num_key_value_heads is None:
120
+ num_key_value_heads = num_attention_heads
121
+
122
+ self.num_key_value_heads = num_key_value_heads
123
+
124
+ self.depth_confidence = depth_confidence
125
+ self.width_confidence = width_confidence
126
+ self.filter_threshold = filter_threshold
127
+ self.initializer_range = initializer_range
128
+
129
+ # Keypoint Detector is forced into eager attention mode because SuperPoint does not have Attention
130
+ # See https://github.com/huggingface/transformers/pull/31718#discussion_r2109733153
131
+ if isinstance(keypoint_detector_config, dict):
132
+ keypoint_detector_config["model_type"] = keypoint_detector_config.get("model_type", "superpoint")
133
+ if keypoint_detector_config["model_type"] not in CONFIG_MAPPING:
134
+ keypoint_detector_config = AutoConfig.from_pretrained(
135
+ keypoint_detector_config["_name_or_path"], trust_remote_code=self.trust_remote_code
136
+ )
137
+ else:
138
+ keypoint_detector_config = CONFIG_MAPPING[keypoint_detector_config["model_type"]](
139
+ **keypoint_detector_config, attn_implementation="eager"
140
+ )
141
+
142
+ if keypoint_detector_config is None:
143
+ keypoint_detector_config = CONFIG_MAPPING["superpoint"](attn_implementation="eager")
144
+
145
+ self.keypoint_detector_config = keypoint_detector_config
146
+
147
+ self.hidden_size = descriptor_dim
148
+ self.intermediate_size = descriptor_dim * 2
149
+ self.hidden_act = hidden_act
150
+ self.attention_dropout = attention_dropout
151
+ self.attention_bias = attention_bias
152
+ super().__init__(**kwargs)
153
+
154
+
155
+ __all__ = ["LightGlueConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lightglue/convert_lightglue_to_hf.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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 argparse
15
+ import gc
16
+ import os
17
+ import re
18
+
19
+ import torch
20
+ from datasets import load_dataset
21
+
22
+ from transformers import (
23
+ AutoModelForKeypointDetection,
24
+ LightGlueForKeypointMatching,
25
+ LightGlueImageProcessor,
26
+ )
27
+ from transformers.models.lightglue.configuration_lightglue import LightGlueConfig
28
+
29
+
30
+ DEFAULT_CHECKPOINT_URL = "https://github.com/cvg/LightGlue/releases/download/v0.1_arxiv/superpoint_lightglue.pth"
31
+
32
+
33
+ def prepare_imgs():
34
+ dataset = load_dataset("hf-internal-testing/image-matching-test-dataset", split="train")
35
+ image0 = dataset[0]["image"]
36
+ image1 = dataset[1]["image"]
37
+ image2 = dataset[2]["image"]
38
+ # [image1, image1] on purpose to test the model early stopping
39
+ return [[image2, image0], [image1, image1]]
40
+
41
+
42
+ def verify_model_outputs(model, device):
43
+ images = prepare_imgs()
44
+ preprocessor = LightGlueImageProcessor()
45
+ inputs = preprocessor(images=images, return_tensors="pt").to(device)
46
+ model.to(device)
47
+ with torch.no_grad():
48
+ outputs = model(**inputs, output_hidden_states=True, output_attentions=True)
49
+
50
+ predicted_matches_values = outputs.matches[0, 0, 20:30]
51
+ predicted_matching_scores_values = outputs.matching_scores[0, 0, 20:30]
52
+
53
+ predicted_number_of_matches = torch.sum(outputs.matches[0][0] != -1).item()
54
+
55
+ expected_max_number_keypoints = 866
56
+ expected_matches_shape = torch.Size((len(images), 2, expected_max_number_keypoints))
57
+ expected_matching_scores_shape = torch.Size((len(images), 2, expected_max_number_keypoints))
58
+
59
+ expected_matches_values = torch.tensor([-1, -1, 5, -1, -1, 19, -1, 10, -1, 11], dtype=torch.int64).to(device)
60
+ expected_matching_scores_values = torch.tensor([0, 0, 0.2997, 0, 0, 0.6762, 0, 0.8826, 0, 0.5583]).to(device)
61
+
62
+ expected_number_of_matches = 140
63
+
64
+ assert outputs.matches.shape == expected_matches_shape
65
+ assert outputs.matching_scores.shape == expected_matching_scores_shape
66
+
67
+ assert torch.allclose(predicted_matches_values, expected_matches_values, atol=1e-2)
68
+ assert torch.allclose(predicted_matching_scores_values, expected_matching_scores_values, atol=1e-2)
69
+
70
+ assert predicted_number_of_matches == expected_number_of_matches
71
+
72
+
73
+ ORIGINAL_TO_CONVERTED_KEY_MAPPING = {
74
+ r"posenc.Wr": r"positional_encoder.projector",
75
+ r"self_attn.(\d+).Wqkv": r"transformer_layers.\1.self_attention.Wqkv",
76
+ r"self_attn.(\d+).out_proj": r"transformer_layers.\1.self_attention.o_proj",
77
+ r"self_attn.(\d+).ffn.0": r"transformer_layers.\1.self_mlp.fc1",
78
+ r"self_attn.(\d+).ffn.1": r"transformer_layers.\1.self_mlp.layer_norm",
79
+ r"self_attn.(\d+).ffn.3": r"transformer_layers.\1.self_mlp.fc2",
80
+ r"cross_attn.(\d+).to_qk": r"transformer_layers.\1.cross_attention.to_qk",
81
+ r"cross_attn.(\d+).to_v": r"transformer_layers.\1.cross_attention.v_proj",
82
+ r"cross_attn.(\d+).to_out": r"transformer_layers.\1.cross_attention.o_proj",
83
+ r"cross_attn.(\d+).ffn.0": r"transformer_layers.\1.cross_mlp.fc1",
84
+ r"cross_attn.(\d+).ffn.1": r"transformer_layers.\1.cross_mlp.layer_norm",
85
+ r"cross_attn.(\d+).ffn.3": r"transformer_layers.\1.cross_mlp.fc2",
86
+ r"log_assignment.(\d+).matchability": r"match_assignment_layers.\1.matchability",
87
+ r"log_assignment.(\d+).final_proj": r"match_assignment_layers.\1.final_projection",
88
+ r"token_confidence.(\d+).token.0": r"token_confidence.\1.token",
89
+ }
90
+
91
+
92
+ def convert_old_keys_to_new_keys(state_dict_keys: list[str]):
93
+ """
94
+ This function should be applied only once, on the concatenated keys to efficiently rename using
95
+ the key mappings.
96
+ """
97
+ output_dict = {}
98
+ if state_dict_keys is not None:
99
+ old_text = "\n".join(state_dict_keys)
100
+ new_text = old_text
101
+ for pattern, replacement in ORIGINAL_TO_CONVERTED_KEY_MAPPING.items():
102
+ if replacement is None:
103
+ new_text = re.sub(pattern, "", new_text) # an empty line
104
+ continue
105
+ new_text = re.sub(pattern, replacement, new_text)
106
+ output_dict = dict(zip(old_text.split("\n"), new_text.split("\n")))
107
+ return output_dict
108
+
109
+
110
+ def add_keypoint_detector_state_dict(lightglue_state_dict):
111
+ keypoint_detector = AutoModelForKeypointDetection.from_pretrained("magic-leap-community/superpoint")
112
+ keypoint_detector_state_dict = keypoint_detector.state_dict()
113
+ for k, v in keypoint_detector_state_dict.items():
114
+ lightglue_state_dict[f"keypoint_detector.{k}"] = v
115
+ return lightglue_state_dict
116
+
117
+
118
+ def split_weights(state_dict):
119
+ for i in range(9):
120
+ # Remove unused r values
121
+ log_assignment_r_key = f"log_assignment.{i}.r"
122
+ if state_dict.get(log_assignment_r_key, None) is not None:
123
+ state_dict.pop(log_assignment_r_key)
124
+
125
+ Wqkv_weight = state_dict.pop(f"transformer_layers.{i}.self_attention.Wqkv.weight")
126
+ Wqkv_bias = state_dict.pop(f"transformer_layers.{i}.self_attention.Wqkv.bias")
127
+ Wqkv_weight = Wqkv_weight.reshape(256, 3, 256)
128
+ Wqkv_bias = Wqkv_bias.reshape(256, 3)
129
+ query_weight, key_weight, value_weight = Wqkv_weight[:, 0], Wqkv_weight[:, 1], Wqkv_weight[:, 2]
130
+ query_bias, key_bias, value_bias = Wqkv_bias[:, 0], Wqkv_bias[:, 1], Wqkv_bias[:, 2]
131
+ state_dict[f"transformer_layers.{i}.self_attention.q_proj.weight"] = query_weight
132
+ state_dict[f"transformer_layers.{i}.self_attention.k_proj.weight"] = key_weight
133
+ state_dict[f"transformer_layers.{i}.self_attention.v_proj.weight"] = value_weight
134
+ state_dict[f"transformer_layers.{i}.self_attention.q_proj.bias"] = query_bias
135
+ state_dict[f"transformer_layers.{i}.self_attention.k_proj.bias"] = key_bias
136
+ state_dict[f"transformer_layers.{i}.self_attention.v_proj.bias"] = value_bias
137
+
138
+ to_qk_weight = state_dict.pop(f"transformer_layers.{i}.cross_attention.to_qk.weight")
139
+ to_qk_bias = state_dict.pop(f"transformer_layers.{i}.cross_attention.to_qk.bias")
140
+ state_dict[f"transformer_layers.{i}.cross_attention.q_proj.weight"] = to_qk_weight
141
+ state_dict[f"transformer_layers.{i}.cross_attention.q_proj.bias"] = to_qk_bias
142
+ state_dict[f"transformer_layers.{i}.cross_attention.k_proj.weight"] = to_qk_weight
143
+ state_dict[f"transformer_layers.{i}.cross_attention.k_proj.bias"] = to_qk_bias
144
+
145
+ return state_dict
146
+
147
+
148
+ @torch.no_grad()
149
+ def write_model(
150
+ model_path,
151
+ checkpoint_url,
152
+ organization,
153
+ safe_serialization=True,
154
+ push_to_hub=False,
155
+ ):
156
+ os.makedirs(model_path, exist_ok=True)
157
+
158
+ # ------------------------------------------------------------
159
+ # LightGlue config
160
+ # ------------------------------------------------------------
161
+
162
+ config = LightGlueConfig(
163
+ descriptor_dim=256,
164
+ num_hidden_layers=9,
165
+ num_attention_heads=4,
166
+ )
167
+ config.architectures = ["LightGlueForKeypointMatching"]
168
+ config.save_pretrained(model_path)
169
+ print("Model config saved successfully...")
170
+
171
+ # ------------------------------------------------------------
172
+ # Convert weights
173
+ # ------------------------------------------------------------
174
+
175
+ print(f"Fetching all parameters from the checkpoint at {checkpoint_url}...")
176
+ original_state_dict = torch.hub.load_state_dict_from_url(checkpoint_url)
177
+
178
+ print("Converting model...")
179
+ all_keys = list(original_state_dict.keys())
180
+ new_keys = convert_old_keys_to_new_keys(all_keys)
181
+
182
+ state_dict = {}
183
+ for key in all_keys:
184
+ new_key = new_keys[key]
185
+ state_dict[new_key] = original_state_dict.pop(key).contiguous().clone()
186
+
187
+ del original_state_dict
188
+ gc.collect()
189
+ state_dict = split_weights(state_dict)
190
+ state_dict = add_keypoint_detector_state_dict(state_dict)
191
+
192
+ print("Loading the checkpoint in a LightGlue model...")
193
+ device = "cuda"
194
+ with torch.device(device):
195
+ model = LightGlueForKeypointMatching(config)
196
+ model.load_state_dict(state_dict)
197
+ print("Checkpoint loaded successfully...")
198
+ del model.config._name_or_path
199
+
200
+ print("Saving the model...")
201
+ model.save_pretrained(model_path, safe_serialization=safe_serialization)
202
+ del state_dict, model
203
+
204
+ # Safety check: reload the converted model
205
+ gc.collect()
206
+ print("Reloading the model to check if it's saved correctly.")
207
+ model = LightGlueForKeypointMatching.from_pretrained(model_path)
208
+ print("Model reloaded successfully.")
209
+
210
+ model_name = "lightglue"
211
+ if "superpoint" in checkpoint_url:
212
+ model_name += "_superpoint"
213
+ if checkpoint_url == DEFAULT_CHECKPOINT_URL:
214
+ print("Checking the model outputs...")
215
+ verify_model_outputs(model, device)
216
+ print("Model outputs verified successfully.")
217
+
218
+ if push_to_hub:
219
+ print("Pushing model to the hub...")
220
+ model.push_to_hub(
221
+ repo_id=f"{organization}/{model_name}",
222
+ commit_message="Add model",
223
+ )
224
+ config.push_to_hub(repo_id=f"{organization}/{model_name}", commit_message="Add config")
225
+
226
+ write_image_processor(model_path, model_name, organization, push_to_hub=push_to_hub)
227
+
228
+
229
+ def write_image_processor(save_dir, model_name, organization, push_to_hub=False):
230
+ if "superpoint" in model_name:
231
+ image_processor = LightGlueImageProcessor(do_grayscale=True)
232
+ else:
233
+ image_processor = LightGlueImageProcessor()
234
+ image_processor.save_pretrained(save_dir)
235
+
236
+ if push_to_hub:
237
+ print("Pushing image processor to the hub...")
238
+ image_processor.push_to_hub(
239
+ repo_id=f"{organization}/{model_name}",
240
+ commit_message="Add image processor",
241
+ )
242
+
243
+
244
+ if __name__ == "__main__":
245
+ parser = argparse.ArgumentParser()
246
+ # Required parameters
247
+ parser.add_argument(
248
+ "--checkpoint_url",
249
+ default=DEFAULT_CHECKPOINT_URL,
250
+ type=str,
251
+ help="URL of the original LightGlue checkpoint you'd like to convert.",
252
+ )
253
+ parser.add_argument(
254
+ "--pytorch_dump_folder_path",
255
+ default=None,
256
+ type=str,
257
+ required=True,
258
+ help="Path to the output PyTorch model directory.",
259
+ )
260
+ parser.add_argument("--save_model", action="store_true", help="Save model to local")
261
+ parser.add_argument(
262
+ "--push_to_hub",
263
+ action="store_true",
264
+ help="Push model and image preprocessor to the hub",
265
+ )
266
+ parser.add_argument(
267
+ "--organization",
268
+ default="ETH-CVG",
269
+ type=str,
270
+ help="Hub organization in which you want the model to be uploaded.",
271
+ )
272
+
273
+ args = parser.parse_args()
274
+ write_model(
275
+ args.pytorch_dump_folder_path,
276
+ args.checkpoint_url,
277
+ args.organization,
278
+ safe_serialization=True,
279
+ push_to_hub=args.push_to_hub,
280
+ )
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lightglue/image_processing_lightglue.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/lightglue/modular_lightglue.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_lightglue.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ import warnings
21
+ from typing import Optional, Union
22
+
23
+ import numpy as np
24
+ import torch
25
+
26
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
27
+ from ...image_transforms import resize, to_channel_dimension_format
28
+ from ...image_utils import (
29
+ ChannelDimension,
30
+ ImageInput,
31
+ ImageType,
32
+ PILImageResampling,
33
+ get_image_type,
34
+ infer_channel_dimension_format,
35
+ is_pil_image,
36
+ is_scaled_image,
37
+ is_valid_image,
38
+ is_vision_available,
39
+ to_numpy_array,
40
+ valid_images,
41
+ validate_preprocess_arguments,
42
+ )
43
+ from ...utils import TensorType, is_matplotlib_available, logging, requires_backends
44
+ from ...utils.import_utils import requires
45
+ from .modeling_lightglue import LightGlueKeypointMatchingOutput
46
+
47
+
48
+ if is_vision_available():
49
+ from PIL import Image, ImageDraw
50
+
51
+ if is_vision_available():
52
+ import PIL
53
+
54
+ logger = logging.get_logger(__name__)
55
+
56
+
57
+ def is_grayscale(
58
+ image: np.ndarray,
59
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
60
+ ):
61
+ if input_data_format == ChannelDimension.FIRST:
62
+ if image.shape[0] == 1:
63
+ return True
64
+ return np.all(image[0, ...] == image[1, ...]) and np.all(image[1, ...] == image[2, ...])
65
+ elif input_data_format == ChannelDimension.LAST:
66
+ if image.shape[-1] == 1:
67
+ return True
68
+ return np.all(image[..., 0] == image[..., 1]) and np.all(image[..., 1] == image[..., 2])
69
+
70
+
71
+ def convert_to_grayscale(
72
+ image: ImageInput,
73
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
74
+ ) -> ImageInput:
75
+ """
76
+ Converts an image to grayscale format using the NTSC formula. Only support numpy and PIL Image. TODO support torch
77
+ and tensorflow grayscale conversion
78
+
79
+ This function is supposed to return a 1-channel image, but it returns a 3-channel image with the same value in each
80
+ channel, because of an issue that is discussed in :
81
+ https://github.com/huggingface/transformers/pull/25786#issuecomment-1730176446
82
+
83
+ Args:
84
+ image (Image):
85
+ The image to convert.
86
+ input_data_format (`ChannelDimension` or `str`, *optional*):
87
+ The channel dimension format for the input image.
88
+ """
89
+ requires_backends(convert_to_grayscale, ["vision"])
90
+
91
+ if isinstance(image, np.ndarray):
92
+ if is_grayscale(image, input_data_format=input_data_format):
93
+ return image
94
+ if input_data_format == ChannelDimension.FIRST:
95
+ gray_image = image[0, ...] * 0.2989 + image[1, ...] * 0.5870 + image[2, ...] * 0.1140
96
+ gray_image = np.stack([gray_image] * 3, axis=0)
97
+ elif input_data_format == ChannelDimension.LAST:
98
+ gray_image = image[..., 0] * 0.2989 + image[..., 1] * 0.5870 + image[..., 2] * 0.1140
99
+ gray_image = np.stack([gray_image] * 3, axis=-1)
100
+ return gray_image
101
+
102
+ if not isinstance(image, PIL.Image.Image):
103
+ return image
104
+
105
+ image = image.convert("L")
106
+ return image
107
+
108
+
109
+ def validate_and_format_image_pairs(images: ImageInput):
110
+ error_message = (
111
+ "Input images must be a one of the following :",
112
+ " - A pair of PIL images.",
113
+ " - A pair of 3D arrays.",
114
+ " - A list of pairs of PIL images.",
115
+ " - A list of pairs of 3D arrays.",
116
+ )
117
+
118
+ def _is_valid_image(image):
119
+ """images is a PIL Image or a 3D array."""
120
+ return is_pil_image(image) or (
121
+ is_valid_image(image) and get_image_type(image) != ImageType.PIL and len(image.shape) == 3
122
+ )
123
+
124
+ if isinstance(images, list):
125
+ if len(images) == 2 and all((_is_valid_image(image)) for image in images):
126
+ return images
127
+ if all(
128
+ isinstance(image_pair, list)
129
+ and len(image_pair) == 2
130
+ and all(_is_valid_image(image) for image in image_pair)
131
+ for image_pair in images
132
+ ):
133
+ return [image for image_pair in images for image in image_pair]
134
+ raise ValueError(error_message)
135
+
136
+
137
+ @requires(backends=("torch",))
138
+ class LightGlueImageProcessor(BaseImageProcessor):
139
+ r"""
140
+ Constructs a LightGlue image processor.
141
+
142
+ Args:
143
+ do_resize (`bool`, *optional*, defaults to `True`):
144
+ Controls whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden
145
+ by `do_resize` in the `preprocess` method.
146
+ size (`dict[str, int]` *optional*, defaults to `{"height": 480, "width": 640}`):
147
+ Resolution of the output image after `resize` is applied. Only has an effect if `do_resize` is set to
148
+ `True`. Can be overridden by `size` in the `preprocess` method.
149
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
150
+ Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
151
+ do_rescale (`bool`, *optional*, defaults to `True`):
152
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
153
+ the `preprocess` method.
154
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
155
+ Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
156
+ method.
157
+ do_grayscale (`bool`, *optional*, defaults to `True`):
158
+ Whether to convert the image to grayscale. Can be overridden by `do_grayscale` in the `preprocess` method.
159
+ """
160
+
161
+ model_input_names = ["pixel_values"]
162
+
163
+ def __init__(
164
+ self,
165
+ do_resize: bool = True,
166
+ size: Optional[dict[str, int]] = None,
167
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
168
+ do_rescale: bool = True,
169
+ rescale_factor: float = 1 / 255,
170
+ do_grayscale: bool = True,
171
+ **kwargs,
172
+ ) -> None:
173
+ super().__init__(**kwargs)
174
+ size = size if size is not None else {"height": 480, "width": 640}
175
+ size = get_size_dict(size, default_to_square=False)
176
+
177
+ self.do_resize = do_resize
178
+ self.size = size
179
+ self.resample = resample
180
+ self.do_rescale = do_rescale
181
+ self.rescale_factor = rescale_factor
182
+ self.do_grayscale = do_grayscale
183
+
184
+ def resize(
185
+ self,
186
+ image: np.ndarray,
187
+ size: dict[str, int],
188
+ data_format: Optional[Union[str, ChannelDimension]] = None,
189
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
190
+ **kwargs,
191
+ ):
192
+ """
193
+ Resize an image.
194
+
195
+ Args:
196
+ image (`np.ndarray`):
197
+ Image to resize.
198
+ size (`dict[str, int]`):
199
+ Dictionary of the form `{"height": int, "width": int}`, specifying the size of the output image.
200
+ data_format (`ChannelDimension` or `str`, *optional*):
201
+ The channel dimension format of the output image. If not provided, it will be inferred from the input
202
+ image. Can be one of:
203
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
204
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
205
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
206
+ input_data_format (`ChannelDimension` or `str`, *optional*):
207
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
208
+ from the input image. Can be one of:
209
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
210
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
211
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
212
+ """
213
+ size = get_size_dict(size, default_to_square=False)
214
+
215
+ return resize(
216
+ image,
217
+ size=(size["height"], size["width"]),
218
+ data_format=data_format,
219
+ input_data_format=input_data_format,
220
+ **kwargs,
221
+ )
222
+
223
+ def preprocess(
224
+ self,
225
+ images,
226
+ do_resize: Optional[bool] = None,
227
+ size: Optional[dict[str, int]] = None,
228
+ resample: PILImageResampling = None,
229
+ do_rescale: Optional[bool] = None,
230
+ rescale_factor: Optional[float] = None,
231
+ do_grayscale: Optional[bool] = None,
232
+ return_tensors: Optional[Union[str, TensorType]] = None,
233
+ data_format: ChannelDimension = ChannelDimension.FIRST,
234
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
235
+ **kwargs,
236
+ ) -> BatchFeature:
237
+ """
238
+ Preprocess an image or batch of images.
239
+
240
+ Args:
241
+ images (`ImageInput`):
242
+ Image pairs to preprocess. Expects either a list of 2 images or a list of list of 2 images list with
243
+ pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set
244
+ `do_rescale=False`.
245
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
246
+ Whether to resize the image.
247
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
248
+ Size of the output image after `resize` has been applied. If `size["shortest_edge"]` >= 384, the image
249
+ is resized to `(size["shortest_edge"], size["shortest_edge"])`. Otherwise, the smaller edge of the
250
+ image will be matched to `int(size["shortest_edge"]/ crop_pct)`, after which the image is cropped to
251
+ `(size["shortest_edge"], size["shortest_edge"])`. Only has an effect if `do_resize` is set to `True`.
252
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
253
+ Resampling filter to use if resizing the image. This can be one of `PILImageResampling`, filters. Only
254
+ has an effect if `do_resize` is set to `True`.
255
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
256
+ Whether to rescale the image values between [0 - 1].
257
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
258
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
259
+ do_grayscale (`bool`, *optional*, defaults to `self.do_grayscale`):
260
+ Whether to convert the image to grayscale.
261
+ return_tensors (`str` or `TensorType`, *optional*):
262
+ The type of tensors to return. Can be one of:
263
+ - Unset: Return a list of `np.ndarray`.
264
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
265
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
266
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
267
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
268
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
269
+ The channel dimension format for the output image. Can be one of:
270
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
271
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
272
+ - Unset: Use the channel dimension format of the input image.
273
+ input_data_format (`ChannelDimension` or `str`, *optional*):
274
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
275
+ from the input image. Can be one of:
276
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
277
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
278
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
279
+ """
280
+
281
+ do_resize = do_resize if do_resize is not None else self.do_resize
282
+ resample = resample if resample is not None else self.resample
283
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
284
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
285
+ do_grayscale = do_grayscale if do_grayscale is not None else self.do_grayscale
286
+
287
+ size = size if size is not None else self.size
288
+ size = get_size_dict(size, default_to_square=False)
289
+
290
+ # Validate and convert the input images into a flattened list of images for all subsequent processing steps.
291
+ images = validate_and_format_image_pairs(images)
292
+
293
+ if not valid_images(images):
294
+ raise ValueError(
295
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
296
+ "torch.Tensor, tf.Tensor or jax.ndarray."
297
+ )
298
+
299
+ validate_preprocess_arguments(
300
+ do_resize=do_resize,
301
+ size=size,
302
+ resample=resample,
303
+ do_rescale=do_rescale,
304
+ rescale_factor=rescale_factor,
305
+ )
306
+
307
+ # All transformations expect numpy arrays.
308
+ images = [to_numpy_array(image) for image in images]
309
+
310
+ if is_scaled_image(images[0]) and do_rescale:
311
+ logger.warning_once(
312
+ "It looks like you are trying to rescale already rescaled images. If the input"
313
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
314
+ )
315
+
316
+ if input_data_format is None:
317
+ # We assume that all images have the same channel dimension format.
318
+ input_data_format = infer_channel_dimension_format(images[0])
319
+
320
+ all_images = []
321
+ for image in images:
322
+ if do_resize:
323
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
324
+
325
+ if do_rescale:
326
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
327
+
328
+ if do_grayscale:
329
+ image = convert_to_grayscale(image, input_data_format=input_data_format)
330
+
331
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
332
+ all_images.append(image)
333
+
334
+ # Convert back the flattened list of images into a list of pairs of images.
335
+ image_pairs = [all_images[i : i + 2] for i in range(0, len(all_images), 2)]
336
+
337
+ data = {"pixel_values": image_pairs}
338
+
339
+ return BatchFeature(data=data, tensor_type=return_tensors)
340
+
341
+ def post_process_keypoint_matching(
342
+ self,
343
+ outputs: LightGlueKeypointMatchingOutput,
344
+ target_sizes: Union[TensorType, list[tuple]],
345
+ threshold: float = 0.0,
346
+ ) -> list[dict[str, torch.Tensor]]:
347
+ """
348
+ Converts the raw output of [`KeypointMatchingOutput`] into lists of keypoints, scores and descriptors
349
+ with coordinates absolute to the original image sizes.
350
+ Args:
351
+ outputs ([`KeypointMatchingOutput`]):
352
+ Raw outputs of the model.
353
+ target_sizes (`torch.Tensor` or `list[tuple[tuple[int, int]]]`, *optional*):
354
+ Tensor of shape `(batch_size, 2, 2)` or list of tuples of tuples (`tuple[int, int]`) containing the
355
+ target size `(height, width)` of each image in the batch. This must be the original image size (before
356
+ any processing).
357
+ threshold (`float`, *optional*, defaults to 0.0):
358
+ Threshold to filter out the matches with low scores.
359
+ Returns:
360
+ `list[Dict]`: A list of dictionaries, each dictionary containing the keypoints in the first and second image
361
+ of the pair, the matching scores and the matching indices.
362
+ """
363
+ if outputs.mask.shape[0] != len(target_sizes):
364
+ raise ValueError("Make sure that you pass in as many target sizes as the batch dimension of the mask")
365
+ if not all(len(target_size) == 2 for target_size in target_sizes):
366
+ raise ValueError("Each element of target_sizes must contain the size (h, w) of each image of the batch")
367
+
368
+ if isinstance(target_sizes, list):
369
+ image_pair_sizes = torch.tensor(target_sizes, device=outputs.mask.device)
370
+ else:
371
+ if target_sizes.shape[1] != 2 or target_sizes.shape[2] != 2:
372
+ raise ValueError(
373
+ "Each element of target_sizes must contain the size (h, w) of each image of the batch"
374
+ )
375
+ image_pair_sizes = target_sizes
376
+
377
+ keypoints = outputs.keypoints.clone()
378
+ keypoints = keypoints * image_pair_sizes.flip(-1).reshape(-1, 2, 1, 2)
379
+ keypoints = keypoints.to(torch.int32)
380
+
381
+ results = []
382
+ for mask_pair, keypoints_pair, matches, scores in zip(
383
+ outputs.mask, keypoints, outputs.matches[:, 0], outputs.matching_scores[:, 0]
384
+ ):
385
+ mask0 = mask_pair[0] > 0
386
+ mask1 = mask_pair[1] > 0
387
+ keypoints0 = keypoints_pair[0][mask0]
388
+ keypoints1 = keypoints_pair[1][mask1]
389
+ matches0 = matches[mask0]
390
+ scores0 = scores[mask0]
391
+
392
+ # Filter out matches with low scores
393
+ valid_matches = torch.logical_and(scores0 > threshold, matches0 > -1)
394
+
395
+ matched_keypoints0 = keypoints0[valid_matches]
396
+ matched_keypoints1 = keypoints1[matches0[valid_matches]]
397
+ matching_scores = scores0[valid_matches]
398
+
399
+ results.append(
400
+ {
401
+ "keypoints0": matched_keypoints0,
402
+ "keypoints1": matched_keypoints1,
403
+ "matching_scores": matching_scores,
404
+ }
405
+ )
406
+
407
+ return results
408
+
409
+ def visualize_keypoint_matching(
410
+ self,
411
+ images: ImageInput,
412
+ keypoint_matching_output: list[dict[str, torch.Tensor]],
413
+ ) -> list["Image.Image"]:
414
+ """
415
+ Plots the image pairs side by side with the detected keypoints as well as the matching between them.
416
+
417
+ Args:
418
+ images (`ImageInput`):
419
+ Image pairs to plot. Same as `LightGlueImageProcessor.preprocess`. Expects either a list of 2
420
+ images or a list of list of 2 images list with pixel values ranging from 0 to 255.
421
+ keypoint_matching_output (List[Dict[str, torch.Tensor]]]):
422
+ A post processed keypoint matching output
423
+
424
+ Returns:
425
+ `List[PIL.Image.Image]`: A list of PIL images, each containing the image pairs side by side with the detected
426
+ keypoints as well as the matching between them.
427
+ """
428
+ images = validate_and_format_image_pairs(images)
429
+ images = [to_numpy_array(image) for image in images]
430
+ image_pairs = [images[i : i + 2] for i in range(0, len(images), 2)]
431
+
432
+ results = []
433
+ for image_pair, pair_output in zip(image_pairs, keypoint_matching_output):
434
+ height0, width0 = image_pair[0].shape[:2]
435
+ height1, width1 = image_pair[1].shape[:2]
436
+ plot_image = np.zeros((max(height0, height1), width0 + width1, 3), dtype=np.uint8)
437
+ plot_image[:height0, :width0] = image_pair[0]
438
+ plot_image[:height1, width0:] = image_pair[1]
439
+
440
+ plot_image_pil = Image.fromarray(plot_image)
441
+ draw = ImageDraw.Draw(plot_image_pil)
442
+
443
+ keypoints0_x, keypoints0_y = pair_output["keypoints0"].unbind(1)
444
+ keypoints1_x, keypoints1_y = pair_output["keypoints1"].unbind(1)
445
+ for keypoint0_x, keypoint0_y, keypoint1_x, keypoint1_y, matching_score in zip(
446
+ keypoints0_x, keypoints0_y, keypoints1_x, keypoints1_y, pair_output["matching_scores"]
447
+ ):
448
+ color = self._get_color(matching_score)
449
+ draw.line(
450
+ (keypoint0_x, keypoint0_y, keypoint1_x + width0, keypoint1_y),
451
+ fill=color,
452
+ width=3,
453
+ )
454
+ draw.ellipse((keypoint0_x - 2, keypoint0_y - 2, keypoint0_x + 2, keypoint0_y + 2), fill="black")
455
+ draw.ellipse(
456
+ (keypoint1_x + width0 - 2, keypoint1_y - 2, keypoint1_x + width0 + 2, keypoint1_y + 2),
457
+ fill="black",
458
+ )
459
+
460
+ results.append(plot_image_pil)
461
+ return results
462
+
463
+ def _get_color(self, score):
464
+ """Maps a score to a color."""
465
+ r = int(255 * (1 - score))
466
+ g = int(255 * score)
467
+ b = 0
468
+ return (r, g, b)
469
+
470
+ def plot_keypoint_matching(self, images: ImageInput, keypoint_matching_output: LightGlueKeypointMatchingOutput):
471
+ """
472
+ Plots the image pairs side by side with the detected keypoints as well as the matching between them. Requires
473
+ matplotlib to be installed.
474
+
475
+ .. deprecated::
476
+ `plot_keypoint_matching` is deprecated and will be removed in a future version. Use `visualize_keypoint_matching` instead.
477
+
478
+ Args:
479
+ images (`ImageInput`):
480
+ Image pairs to plot. Same as `LightGlueImageProcessor.preprocess`. Expects either a list of 2 images or
481
+ a list of list of 2 images list with pixel values ranging from 0 to 255.
482
+ keypoint_matching_output ([`LightGlueKeypointMatchingOutput`]):
483
+ Raw outputs of the model.
484
+ """
485
+ warnings.warn(
486
+ "`plot_keypoint_matching` is deprecated and will be removed in transformers v. "
487
+ "Use `visualize_keypoint_matching` instead.",
488
+ FutureWarning,
489
+ )
490
+
491
+ if is_matplotlib_available():
492
+ import matplotlib.pyplot as plt
493
+ else:
494
+ raise ImportError("Please install matplotlib to use `plot_keypoint_matching` method")
495
+
496
+ images = validate_and_format_image_pairs(images)
497
+ images = [to_numpy_array(image) for image in images]
498
+ image_pairs = [images[i : i + 2] for i in range(0, len(images), 2)]
499
+
500
+ for image_pair, pair_output in zip(image_pairs, keypoint_matching_output):
501
+ height0, width0 = image_pair[0].shape[:2]
502
+ height1, width1 = image_pair[1].shape[:2]
503
+ plot_image = np.zeros((max(height0, height1), width0 + width1, 3))
504
+ plot_image[:height0, :width0] = image_pair[0] / 255.0
505
+ plot_image[:height1, width0:] = image_pair[1] / 255.0
506
+ plt.imshow(plot_image)
507
+ plt.axis("off")
508
+
509
+ keypoints0_x, keypoints0_y = pair_output["keypoints0"].unbind(1)
510
+ keypoints1_x, keypoints1_y = pair_output["keypoints1"].unbind(1)
511
+ for keypoint0_x, keypoint0_y, keypoint1_x, keypoint1_y, matching_score in zip(
512
+ keypoints0_x, keypoints0_y, keypoints1_x, keypoints1_y, pair_output["matching_scores"]
513
+ ):
514
+ plt.plot(
515
+ [keypoint0_x, keypoint1_x + width0],
516
+ [keypoint0_y, keypoint1_y],
517
+ color=plt.get_cmap("RdYlGn")(matching_score.item()),
518
+ alpha=0.9,
519
+ linewidth=0.5,
520
+ )
521
+ plt.scatter(keypoint0_x, keypoint0_y, c="black", s=2)
522
+ plt.scatter(keypoint1_x + width0, keypoint1_y, c="black", s=2)
523
+ plt.show()
524
+
525
+
526
+ __all__ = ["LightGlueImageProcessor"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lightglue/modeling_lightglue.py ADDED
@@ -0,0 +1,916 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/lightglue/modular_lightglue.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_lightglue.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ from dataclasses import dataclass
21
+ from typing import Callable, Optional, Union
22
+
23
+ import numpy as np
24
+ import torch
25
+ from torch import nn
26
+ from torch.nn.utils.rnn import pad_sequence
27
+
28
+ from ...activations import ACT2FN
29
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
30
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
31
+ from ...processing_utils import Unpack
32
+ from ...utils import ModelOutput, TransformersKwargs, auto_docstring
33
+ from ...utils.deprecation import deprecate_kwarg
34
+ from ...utils.generic import can_return_tuple
35
+ from ..auto.modeling_auto import AutoModelForKeypointDetection
36
+ from .configuration_lightglue import LightGlueConfig
37
+
38
+
39
+ @dataclass
40
+ @auto_docstring(
41
+ custom_intro="""
42
+ Base class for outputs of LightGlue keypoint matching models. Due to the nature of keypoint detection and matching,
43
+ the number of keypoints is not fixed and can vary from image to image, which makes batching non-trivial. In the
44
+ batch of images, the maximum number of matches is set as the dimension of the matches and matching scores. The mask
45
+ tensor is used to indicate which values in the keypoints, matches, matching_scores and prune tensors are keypoint
46
+ matching information.
47
+ """
48
+ )
49
+ class LightGlueKeypointMatchingOutput(ModelOutput):
50
+ r"""
51
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*):
52
+ Loss computed during training.
53
+ matches (`torch.FloatTensor` of shape `(batch_size, 2, num_matches)`):
54
+ Index of keypoint matched in the other image.
55
+ matching_scores (`torch.FloatTensor` of shape `(batch_size, 2, num_matches)`):
56
+ Scores of predicted matches.
57
+ keypoints (`torch.FloatTensor` of shape `(batch_size, num_keypoints, 2)`):
58
+ Absolute (x, y) coordinates of predicted keypoints in a given image.
59
+ prune (`torch.IntTensor` of shape `(batch_size, num_keypoints)`):
60
+ Pruning mask indicating which keypoints are removed and at which layer.
61
+ mask (`torch.BoolTensor` of shape `(batch_size, num_keypoints)`):
62
+ Mask indicating which values in matches, matching_scores, keypoints and prune are keypoint matching
63
+ information.
64
+ hidden_states (`Tuple[torch.FloatTensor, ...]`, *optional*):
65
+ Tuple of `torch.FloatTensor` (one for the output of each stage) of shape `(batch_size, 2, num_channels,
66
+ num_keypoints)` returned when `output_hidden_states=True` is passed or when
67
+ `config.output_hidden_states=True`
68
+ attentions (`Tuple[torch.FloatTensor, ...]`, *optional*):
69
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, 2, num_heads, num_keypoints,
70
+ num_keypoints)` returned when `output_attentions=True` is passed or when
71
+ `config.output_attentions=True`
72
+ """
73
+
74
+ loss: Optional[torch.FloatTensor] = None
75
+ matches: Optional[torch.FloatTensor] = None
76
+ matching_scores: Optional[torch.FloatTensor] = None
77
+ keypoints: Optional[torch.FloatTensor] = None
78
+ prune: Optional[torch.IntTensor] = None
79
+ mask: Optional[torch.FloatTensor] = None
80
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
81
+ attentions: Optional[tuple[torch.FloatTensor]] = None
82
+
83
+
84
+ class LightGluePositionalEncoder(nn.Module):
85
+ def __init__(self, config: LightGlueConfig):
86
+ super().__init__()
87
+ self.projector = nn.Linear(2, config.descriptor_dim // config.num_attention_heads // 2, bias=False)
88
+
89
+ def forward(
90
+ self, keypoints: torch.Tensor, output_hidden_states: Optional[bool] = False
91
+ ) -> Union[tuple[torch.Tensor], tuple[torch.Tensor, torch.Tensor]]:
92
+ projected_keypoints = self.projector(keypoints)
93
+ embeddings = projected_keypoints.repeat_interleave(2, dim=-1)
94
+ cosines = torch.cos(embeddings)
95
+ sines = torch.sin(embeddings)
96
+ embeddings = (cosines, sines)
97
+ output = (embeddings, projected_keypoints) if output_hidden_states else (embeddings,)
98
+ return output
99
+
100
+
101
+ def rotate_half(x):
102
+ # Split and rotate. Note that this function is different from e.g. Llama.
103
+ x1 = x[..., ::2]
104
+ x2 = x[..., 1::2]
105
+ rot_x = torch.stack([-x2, x1], dim=-1).flatten(-2)
106
+ return rot_x
107
+
108
+
109
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
110
+ """Applies Rotary Position Embedding to the query and key tensors.
111
+
112
+ Args:
113
+ q (`torch.Tensor`): The query tensor.
114
+ k (`torch.Tensor`): The key tensor.
115
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
116
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
117
+ position_ids (`torch.Tensor`, *optional*):
118
+ Deprecated and unused.
119
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
120
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
121
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
122
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
123
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
124
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
125
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
126
+ Returns:
127
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
128
+ """
129
+ dtype = q.dtype
130
+ q = q.float()
131
+ k = k.float()
132
+ cos = cos.unsqueeze(unsqueeze_dim)
133
+ sin = sin.unsqueeze(unsqueeze_dim)
134
+ q_embed = (q * cos) + (rotate_half(q) * sin)
135
+ k_embed = (k * cos) + (rotate_half(k) * sin)
136
+ return q_embed.to(dtype=dtype), k_embed.to(dtype=dtype)
137
+
138
+
139
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
140
+ """
141
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
142
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
143
+ """
144
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
145
+ if n_rep == 1:
146
+ return hidden_states
147
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
148
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
149
+
150
+
151
+ def eager_attention_forward(
152
+ module: nn.Module,
153
+ query: torch.Tensor,
154
+ key: torch.Tensor,
155
+ value: torch.Tensor,
156
+ attention_mask: Optional[torch.Tensor],
157
+ scaling: float,
158
+ dropout: float = 0.0,
159
+ **kwargs: Unpack[TransformersKwargs],
160
+ ):
161
+ key_states = repeat_kv(key, module.num_key_value_groups)
162
+ value_states = repeat_kv(value, module.num_key_value_groups)
163
+
164
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
165
+ if attention_mask is not None:
166
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
167
+ attn_weights = attn_weights + causal_mask
168
+
169
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
170
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
171
+ attn_output = torch.matmul(attn_weights, value_states)
172
+ attn_output = attn_output.transpose(1, 2).contiguous()
173
+
174
+ return attn_output, attn_weights
175
+
176
+
177
+ class LightGlueAttention(nn.Module):
178
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
179
+
180
+ def __init__(self, config: LightGlueConfig, layer_idx: int):
181
+ super().__init__()
182
+ self.config = config
183
+ self.layer_idx = layer_idx
184
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
185
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
186
+ self.scaling = self.head_dim**-0.5
187
+ self.attention_dropout = config.attention_dropout
188
+ self.is_causal = True
189
+
190
+ self.q_proj = nn.Linear(
191
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
192
+ )
193
+ self.k_proj = nn.Linear(
194
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
195
+ )
196
+ self.v_proj = nn.Linear(
197
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
198
+ )
199
+ self.o_proj = nn.Linear(
200
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
201
+ )
202
+
203
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
204
+ def forward(
205
+ self,
206
+ hidden_states: torch.Tensor,
207
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
208
+ attention_mask: Optional[torch.Tensor] = None,
209
+ encoder_hidden_states: Optional[torch.Tensor] = None,
210
+ encoder_attention_mask: Optional[torch.Tensor] = None,
211
+ **kwargs: Unpack[FlashAttentionKwargs],
212
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
213
+ input_shape = hidden_states.shape[:-1]
214
+ hidden_shape = (*input_shape, -1, self.head_dim)
215
+
216
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
217
+
218
+ is_cross_attention = encoder_hidden_states is not None
219
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
220
+ current_attention_mask = encoder_attention_mask if is_cross_attention else attention_mask
221
+
222
+ key_states = self.k_proj(current_states).view(hidden_shape).transpose(1, 2)
223
+ value_states = self.v_proj(current_states).view(hidden_shape).transpose(1, 2)
224
+
225
+ if position_embeddings is not None:
226
+ cos, sin = position_embeddings
227
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
228
+
229
+ attention_interface: Callable = eager_attention_forward
230
+ if self.config._attn_implementation != "eager":
231
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
232
+
233
+ attn_output, attn_weights = attention_interface(
234
+ self,
235
+ query_states,
236
+ key_states,
237
+ value_states,
238
+ current_attention_mask,
239
+ dropout=0.0 if not self.training else self.attention_dropout,
240
+ scaling=self.scaling,
241
+ **kwargs,
242
+ )
243
+
244
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
245
+ attn_output = self.o_proj(attn_output)
246
+ return attn_output, attn_weights
247
+
248
+
249
+ class LightGlueMLP(nn.Module):
250
+ def __init__(self, config: LightGlueConfig):
251
+ super().__init__()
252
+ self.config = config
253
+ self.activation_fn = ACT2FN[config.hidden_act]
254
+ self.fc1 = nn.Linear(config.intermediate_size, config.intermediate_size)
255
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
256
+ self.layer_norm = nn.LayerNorm(config.intermediate_size, elementwise_affine=True)
257
+
258
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
259
+ hidden_states = self.fc1(hidden_states)
260
+ hidden_states = self.layer_norm(hidden_states)
261
+ hidden_states = self.activation_fn(hidden_states)
262
+ hidden_states = self.fc2(hidden_states)
263
+ return hidden_states
264
+
265
+
266
+ class LightGlueTransformerLayer(nn.Module):
267
+ def __init__(self, config: LightGlueConfig, layer_idx: int):
268
+ super().__init__()
269
+ self.self_attention = LightGlueAttention(config, layer_idx)
270
+ self.self_mlp = LightGlueMLP(config)
271
+ self.cross_attention = LightGlueAttention(config, layer_idx)
272
+ self.cross_mlp = LightGlueMLP(config)
273
+
274
+ def forward(
275
+ self,
276
+ descriptors: torch.Tensor,
277
+ keypoints: torch.Tensor,
278
+ attention_mask: torch.Tensor,
279
+ output_hidden_states: Optional[bool] = False,
280
+ output_attentions: Optional[bool] = False,
281
+ ) -> tuple[torch.Tensor, Optional[tuple[torch.Tensor]], Optional[tuple[torch.Tensor]]]:
282
+ all_hidden_states = () if output_hidden_states else None
283
+ all_attentions = () if output_attentions else None
284
+
285
+ if output_hidden_states:
286
+ all_hidden_states = all_hidden_states + (descriptors,)
287
+
288
+ batch_size, num_keypoints, descriptor_dim = descriptors.shape
289
+
290
+ # Self attention block
291
+ attention_output, self_attentions = self.self_attention(
292
+ descriptors,
293
+ position_embeddings=keypoints,
294
+ attention_mask=attention_mask,
295
+ output_attentions=output_attentions,
296
+ )
297
+ intermediate_states = torch.cat([descriptors, attention_output], dim=-1)
298
+ output_states = self.self_mlp(intermediate_states)
299
+ self_attention_descriptors = descriptors + output_states
300
+
301
+ if output_hidden_states:
302
+ self_attention_hidden_states = (intermediate_states, output_states)
303
+
304
+ # Reshape hidden_states to group by image_pairs :
305
+ # (batch_size, num_keypoints, descriptor_dim) -> (batch_size, 2, num_keypoints, descriptor_dim)
306
+ # Flip dimension 1 to perform cross attention :
307
+ # (image0, image1) -> (image1, image0)
308
+ # Reshape back to original shape :
309
+ # (batch_size, 2, num_keypoints, descriptor_dim) -> (batch_size, num_keypoints, descriptor_dim)
310
+ encoder_hidden_states = (
311
+ self_attention_descriptors.reshape(-1, 2, num_keypoints, descriptor_dim)
312
+ .flip(1)
313
+ .reshape(batch_size, num_keypoints, descriptor_dim)
314
+ )
315
+ # Same for mask
316
+ encoder_attention_mask = (
317
+ attention_mask.reshape(-1, 2, 1, 1, num_keypoints).flip(1).reshape(batch_size, 1, 1, num_keypoints)
318
+ if attention_mask is not None
319
+ else None
320
+ )
321
+
322
+ # Cross attention block
323
+ cross_attention_output, cross_attentions = self.cross_attention(
324
+ self_attention_descriptors,
325
+ encoder_hidden_states=encoder_hidden_states,
326
+ encoder_attention_mask=encoder_attention_mask,
327
+ output_attentions=output_attentions,
328
+ )
329
+ cross_intermediate_states = torch.cat([self_attention_descriptors, cross_attention_output], dim=-1)
330
+ cross_output_states = self.cross_mlp(cross_intermediate_states)
331
+ descriptors = self_attention_descriptors + cross_output_states
332
+
333
+ if output_hidden_states:
334
+ cross_attention_hidden_states = (cross_intermediate_states, cross_output_states)
335
+ all_hidden_states = (
336
+ all_hidden_states
337
+ + (self_attention_descriptors.reshape(batch_size, num_keypoints, descriptor_dim),)
338
+ + self_attention_hidden_states
339
+ + (descriptors.reshape(batch_size, num_keypoints, descriptor_dim),)
340
+ + cross_attention_hidden_states
341
+ )
342
+
343
+ if output_attentions:
344
+ all_attentions = all_attentions + (self_attentions,) + (cross_attentions,)
345
+
346
+ return descriptors, all_hidden_states, all_attentions
347
+
348
+
349
+ def sigmoid_log_double_softmax(
350
+ similarity: torch.Tensor, matchability0: torch.Tensor, matchability1: torch.Tensor
351
+ ) -> torch.Tensor:
352
+ """create the log assignment matrix from logits and similarity"""
353
+ batch_size, num_keypoints_0, num_keypoints_1 = similarity.shape
354
+ certainties = nn.functional.logsigmoid(matchability0) + nn.functional.logsigmoid(matchability1).transpose(1, 2)
355
+ scores0 = nn.functional.log_softmax(similarity, 2)
356
+ scores1 = nn.functional.log_softmax(similarity.transpose(-1, -2).contiguous(), 2).transpose(-1, -2)
357
+ scores = similarity.new_full((batch_size, num_keypoints_0 + 1, num_keypoints_1 + 1), 0)
358
+ scores[:, :num_keypoints_0, :num_keypoints_1] = scores0 + scores1 + certainties
359
+ scores[:, :-1, -1] = nn.functional.logsigmoid(-matchability0.squeeze(-1))
360
+ scores[:, -1, :-1] = nn.functional.logsigmoid(-matchability1.squeeze(-1))
361
+ return scores
362
+
363
+
364
+ class LightGlueMatchAssignmentLayer(nn.Module):
365
+ def __init__(self, config: LightGlueConfig):
366
+ super().__init__()
367
+
368
+ self.descriptor_dim = config.descriptor_dim
369
+ self.final_projection = nn.Linear(self.descriptor_dim, self.descriptor_dim, bias=True)
370
+ self.matchability = nn.Linear(self.descriptor_dim, 1, bias=True)
371
+
372
+ def forward(self, descriptors: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
373
+ batch_size, num_keypoints, descriptor_dim = descriptors.shape
374
+ # Final projection and similarity computation
375
+ m_descriptors = self.final_projection(descriptors)
376
+ m_descriptors = m_descriptors / torch.tensor(self.descriptor_dim, device=m_descriptors.device) ** 0.25
377
+ m_descriptors = m_descriptors.reshape(batch_size // 2, 2, num_keypoints, descriptor_dim)
378
+ m_descriptors0 = m_descriptors[:, 0]
379
+ m_descriptors1 = m_descriptors[:, 1]
380
+ similarity = m_descriptors0 @ m_descriptors1.transpose(-1, -2)
381
+ if mask is not None:
382
+ mask = mask.reshape(batch_size // 2, 2, num_keypoints)
383
+ mask0 = mask[:, 0].unsqueeze(-1)
384
+ mask1 = mask[:, 1].unsqueeze(-1).transpose(-1, -2)
385
+ mask = mask0 * mask1
386
+ similarity = similarity.masked_fill(mask == 0, torch.finfo(similarity.dtype).min)
387
+
388
+ # Compute matchability of descriptors
389
+ matchability = self.matchability(descriptors)
390
+ matchability = matchability.reshape(batch_size // 2, 2, num_keypoints, 1)
391
+ matchability_0 = matchability[:, 0]
392
+ matchability_1 = matchability[:, 1]
393
+
394
+ # Compute scores from similarity and matchability
395
+ scores = sigmoid_log_double_softmax(similarity, matchability_0, matchability_1)
396
+ return scores
397
+
398
+ def get_matchability(self, descriptors: torch.Tensor) -> torch.Tensor:
399
+ """Get matchability of descriptors as a probability"""
400
+ matchability = self.matchability(descriptors)
401
+ matchability = nn.functional.sigmoid(matchability).squeeze(-1)
402
+ return matchability
403
+
404
+
405
+ class LightGlueTokenConfidenceLayer(nn.Module):
406
+ def __init__(self, config: LightGlueConfig):
407
+ super().__init__()
408
+
409
+ self.token = nn.Linear(config.descriptor_dim, 1)
410
+
411
+ def forward(self, descriptors: torch.Tensor) -> torch.Tensor:
412
+ token = self.token(descriptors.detach())
413
+ token = nn.functional.sigmoid(token).squeeze(-1)
414
+ return token
415
+
416
+
417
+ @auto_docstring
418
+ class LightGluePreTrainedModel(PreTrainedModel):
419
+ """
420
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
421
+ models.
422
+ """
423
+
424
+ config: LightGlueConfig
425
+ base_model_prefix = "lightglue"
426
+ main_input_name = "pixel_values"
427
+ supports_gradient_checkpointing = False
428
+ _supports_flash_attn = True
429
+ _supports_sdpa = True
430
+
431
+
432
+ def get_matches_from_scores(scores: torch.Tensor, threshold: float) -> tuple[torch.Tensor, torch.Tensor]:
433
+ """obtain matches from a score matrix [Bx M+1 x N+1]"""
434
+ batch_size, _, _ = scores.shape
435
+ # For each keypoint, get the best match
436
+ max0 = scores[:, :-1, :-1].max(2)
437
+ max1 = scores[:, :-1, :-1].max(1)
438
+ matches0 = max0.indices
439
+ matches1 = max1.indices
440
+
441
+ # Mutual check for matches
442
+ indices0 = torch.arange(matches0.shape[1], device=matches0.device)[None]
443
+ indices1 = torch.arange(matches1.shape[1], device=matches1.device)[None]
444
+ mutual0 = indices0 == matches1.gather(1, matches0)
445
+ mutual1 = indices1 == matches0.gather(1, matches1)
446
+
447
+ # Get matching scores and filter based on mutual check and thresholding
448
+ max0 = max0.values.exp()
449
+ zero = max0.new_tensor(0)
450
+ matching_scores0 = torch.where(mutual0, max0, zero)
451
+ matching_scores1 = torch.where(mutual1, matching_scores0.gather(1, matches1), zero)
452
+ valid0 = mutual0 & (matching_scores0 > threshold)
453
+ valid1 = mutual1 & valid0.gather(1, matches1)
454
+
455
+ # Filter matches based on mutual check and thresholding of scores
456
+ matches0 = torch.where(valid0, matches0, -1)
457
+ matches1 = torch.where(valid1, matches1, -1)
458
+ matches = torch.stack([matches0, matches1]).transpose(0, 1).reshape(batch_size * 2, -1)
459
+ matching_scores = torch.stack([matching_scores0, matching_scores1]).transpose(0, 1).reshape(batch_size * 2, -1)
460
+
461
+ return matches, matching_scores
462
+
463
+
464
+ def normalize_keypoints(keypoints: torch.Tensor, height: int, width: int) -> torch.Tensor:
465
+ """
466
+ Normalize keypoints locations based on image image_shape
467
+
468
+ Args:
469
+ keypoints (`torch.Tensor` of shape `(batch_size, num_keypoints, 2)`):
470
+ Keypoints locations in (x, y) format.
471
+ height (`int`):
472
+ Image height.
473
+ width (`int`):
474
+ Image width.
475
+
476
+ Returns:
477
+ Normalized keypoints locations of shape (`torch.Tensor` of shape `(batch_size, num_keypoints, 2)`).
478
+ """
479
+ size = torch.tensor([width, height], device=keypoints.device, dtype=keypoints.dtype)[None]
480
+ shift = size / 2
481
+ scale = size.max(-1).values / 2
482
+ keypoints = (keypoints - shift[..., None, :]) / scale[..., None, None]
483
+ return keypoints
484
+
485
+
486
+ @auto_docstring(
487
+ custom_intro="""
488
+ LightGlue model taking images as inputs and outputting the matching of them.
489
+ """
490
+ )
491
+ class LightGlueForKeypointMatching(LightGluePreTrainedModel):
492
+ """
493
+ LightGlue is a model matching keypoints in images by leveraging detections from a keypoint detector such as
494
+ SuperPoint. It is based on the SuperGlue architecture and is designed to be lightweight and efficient.
495
+ It consists of :
496
+ 1. Keypoint Encoder
497
+ 2. A Graph Neural Network with self and cross attention layers
498
+ 3. Matching Assignment layers
499
+
500
+ The correspondence ids use -1 to indicate non-matching points.
501
+
502
+ Philipp Lindenberger, Paul-Edouard Sarlin and Marc Pollefeys. LightGlue: Local Feature Matching at Light Speed.
503
+ In ICCV 2023. https://arxiv.org/pdf/2306.13643.pdf
504
+ """
505
+
506
+ def __init__(self, config: LightGlueConfig):
507
+ super().__init__(config)
508
+ self.keypoint_detector = AutoModelForKeypointDetection.from_config(
509
+ config.keypoint_detector_config, trust_remote_code=config.trust_remote_code
510
+ )
511
+
512
+ self.keypoint_detector_descriptor_dim = config.keypoint_detector_config.descriptor_decoder_dim
513
+ self.descriptor_dim = config.descriptor_dim
514
+ self.num_layers = config.num_hidden_layers
515
+ self.filter_threshold = config.filter_threshold
516
+ self.depth_confidence = config.depth_confidence
517
+ self.width_confidence = config.width_confidence
518
+
519
+ if self.descriptor_dim != self.keypoint_detector_descriptor_dim:
520
+ self.input_projection = nn.Linear(self.keypoint_detector_descriptor_dim, self.descriptor_dim, bias=True)
521
+ else:
522
+ self.input_projection = nn.Identity()
523
+
524
+ self.positional_encoder = LightGluePositionalEncoder(config)
525
+
526
+ self.transformer_layers = nn.ModuleList(
527
+ [LightGlueTransformerLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)]
528
+ )
529
+ self.match_assignment_layers = nn.ModuleList(
530
+ [LightGlueMatchAssignmentLayer(config) for _ in range(config.num_hidden_layers)]
531
+ )
532
+ self.token_confidence = nn.ModuleList(
533
+ [LightGlueTokenConfidenceLayer(config) for _ in range(config.num_hidden_layers - 1)]
534
+ )
535
+
536
+ self.post_init()
537
+
538
+ def _get_confidence_threshold(self, layer_index: int) -> float:
539
+ """scaled confidence threshold for a given layer"""
540
+ threshold = 0.8 + 0.1 * np.exp(-4.0 * layer_index / self.num_layers)
541
+ return np.clip(threshold, 0, 1)
542
+
543
+ def _keypoint_processing(
544
+ self, descriptors: torch.Tensor, keypoints: torch.Tensor, output_hidden_states: Optional[bool] = False
545
+ ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
546
+ descriptors = descriptors.detach().contiguous()
547
+ projected_descriptors = self.input_projection(descriptors)
548
+ keypoint_encoding_output = self.positional_encoder(keypoints, output_hidden_states=output_hidden_states)
549
+ return projected_descriptors, keypoint_encoding_output
550
+
551
+ def _get_early_stopped_image_pairs(
552
+ self, keypoint_confidences: torch.Tensor, layer_index: int, mask: torch.Tensor, num_points: torch.Tensor
553
+ ) -> torch.Tensor:
554
+ """evaluate whether we should stop inference based on the confidence of the keypoints"""
555
+ batch_size, _ = mask.shape
556
+ if layer_index < self.num_layers - 1:
557
+ # If the current layer is not the last layer, we compute the confidence of the keypoints and check
558
+ # if we should stop the forward pass through the transformer layers for each pair of images.
559
+ keypoint_confidences = keypoint_confidences.masked_fill(mask == 0, 1)
560
+ keypoint_confidences = keypoint_confidences.reshape(batch_size // 2, -1)
561
+ threshold = self._get_confidence_threshold(layer_index)
562
+ ratio_confident = 1.0 - (keypoint_confidences < threshold).float().sum(dim=1) / num_points
563
+ early_stopped_pairs = ratio_confident > self.depth_confidence
564
+ else:
565
+ # If the current layer is the last layer, we stop the forward pass through the transformer layers for
566
+ # all pairs of images.
567
+ early_stopped_pairs = torch.ones(batch_size, dtype=torch.bool)
568
+ return early_stopped_pairs
569
+
570
+ def _get_keypoint_matching(self, descriptors, mask, layer_index, early_stops=None):
571
+ if early_stops is not None:
572
+ descriptors = descriptors[early_stops]
573
+ mask = mask[early_stops]
574
+ scores = self.match_assignment_layers[layer_index](descriptors, mask)
575
+ matches, matching_scores = get_matches_from_scores(scores, self.filter_threshold)
576
+ return matches, matching_scores
577
+
578
+ def _get_pruning_mask(self, confidences: torch.Tensor, scores: torch.Tensor, layer_index: int) -> torch.Tensor:
579
+ """mask points which should be removed"""
580
+ keep = scores > (1 - self.width_confidence)
581
+ if confidences is not None: # Low-confidence points are never pruned.
582
+ keep |= confidences <= self._get_confidence_threshold(layer_index)
583
+ return keep
584
+
585
+ def _do_layer_keypoint_pruning(
586
+ self,
587
+ descriptors: torch.Tensor,
588
+ keypoints: torch.Tensor,
589
+ mask: torch.Tensor,
590
+ indices: torch.Tensor,
591
+ prune_output: torch.Tensor,
592
+ keypoint_confidences: torch.Tensor,
593
+ layer_index: int,
594
+ ):
595
+ """
596
+ For a given layer, prune keypoints based on the confidence of the keypoints and the matchability of the
597
+ descriptors.
598
+ """
599
+ batch_size, _, _ = descriptors.shape
600
+ descriptors_matchability = self.match_assignment_layers[layer_index].get_matchability(descriptors)
601
+ pruned_keypoints_mask = self._get_pruning_mask(keypoint_confidences, descriptors_matchability, layer_index)
602
+ pruned_keypoints_mask = pruned_keypoints_mask.masked_fill(mask == 0, torch.tensor(False))
603
+
604
+ # For each image, we extract the pruned indices and the corresponding descriptors and keypoints.
605
+ pruned_descriptors, pruned_keypoints_0, pruned_keypoints_1, pruned_mask, pruned_indices = (
606
+ [t[mask] for t, mask in zip(tensor, pruned_keypoints_mask)]
607
+ for tensor in [descriptors, keypoints[0], keypoints[1], pruned_keypoints_mask, indices]
608
+ )
609
+ for i in range(batch_size):
610
+ prune_output[i, pruned_indices[i]] += 1
611
+
612
+ # Pad the pruned descriptors, keypoints, indices and mask to have the same shape across the batch.
613
+ pruned_descriptors, pruned_keypoints_0, pruned_keypoints_1, pruned_mask = (
614
+ pad_sequence(pruned_tensor, batch_first=True)
615
+ for pruned_tensor in [pruned_descriptors, pruned_keypoints_0, pruned_keypoints_1, pruned_mask]
616
+ )
617
+ pruned_keypoints = (pruned_keypoints_0, pruned_keypoints_1)
618
+ pruned_indices = pad_sequence(pruned_indices, batch_first=True, padding_value=-1)
619
+
620
+ return pruned_descriptors, pruned_keypoints, pruned_indices, pruned_mask, prune_output
621
+
622
+ def _concat_early_stopped_outputs(
623
+ self,
624
+ early_stops_indices,
625
+ final_pruned_keypoints_indices,
626
+ final_pruned_keypoints_iterations,
627
+ matches,
628
+ matching_scores,
629
+ ):
630
+ early_stops_indices = torch.stack(early_stops_indices)
631
+ matches, final_pruned_keypoints_indices = (
632
+ pad_sequence(tensor, batch_first=True, padding_value=-1)
633
+ for tensor in [matches, final_pruned_keypoints_indices]
634
+ )
635
+ matching_scores, final_pruned_keypoints_iterations = (
636
+ pad_sequence(tensor, batch_first=True, padding_value=0)
637
+ for tensor in [matching_scores, final_pruned_keypoints_iterations]
638
+ )
639
+ matches, matching_scores, final_pruned_keypoints_indices, final_pruned_keypoints_iterations = (
640
+ tensor[early_stops_indices]
641
+ for tensor in [
642
+ matches,
643
+ matching_scores,
644
+ final_pruned_keypoints_indices,
645
+ final_pruned_keypoints_iterations,
646
+ ]
647
+ )
648
+ return final_pruned_keypoints_indices, final_pruned_keypoints_iterations, matches, matching_scores
649
+
650
+ def _do_final_keypoint_pruning(
651
+ self,
652
+ indices: torch.Tensor,
653
+ matches: torch.Tensor,
654
+ matching_scores: torch.Tensor,
655
+ num_keypoints: torch.Tensor,
656
+ ) -> tuple[torch.Tensor, torch.Tensor]:
657
+ # (batch_size, num_keypoints) -> (batch_size // 2, 2, num_keypoints) -> 2 * (batch_size // 2, num_keypoints) to
658
+ # have tensors from
659
+ batch_size, _ = indices.shape
660
+ indices, matches, matching_scores = (
661
+ tensor.reshape(batch_size // 2, 2, -1) for tensor in [indices, matches, matching_scores]
662
+ )
663
+ indices0 = indices[:, 0]
664
+ indices1 = indices[:, 1]
665
+ matches0 = matches[:, 0]
666
+ matches1 = matches[:, 1]
667
+ matching_scores0 = matching_scores[:, 0]
668
+ matching_scores1 = matching_scores[:, 1]
669
+
670
+ # Prepare final matches and matching scores
671
+ _matches = torch.full((batch_size // 2, 2, num_keypoints), -1, device=indices.device, dtype=matches.dtype)
672
+ _matching_scores = torch.zeros(
673
+ (batch_size // 2, 2, num_keypoints), device=indices.device, dtype=matching_scores.dtype
674
+ )
675
+ # Fill the matches and matching scores for each image pair
676
+ for i in range(batch_size // 2):
677
+ _matches[i, 0, indices0[i]] = torch.where(
678
+ matches0[i] == -1, -1, indices1[i].gather(0, matches0[i].clamp(min=0))
679
+ )
680
+ _matches[i, 1, indices1[i]] = torch.where(
681
+ matches1[i] == -1, -1, indices0[i].gather(0, matches1[i].clamp(min=0))
682
+ )
683
+ _matching_scores[i, 0, indices0[i]] = matching_scores0[i]
684
+ _matching_scores[i, 1, indices1[i]] = matching_scores1[i]
685
+ return _matches, _matching_scores
686
+
687
+ def _match_image_pair(
688
+ self,
689
+ keypoints: torch.Tensor,
690
+ descriptors: torch.Tensor,
691
+ height: int,
692
+ width: int,
693
+ mask: torch.Tensor = None,
694
+ output_attentions: Optional[bool] = None,
695
+ output_hidden_states: Optional[bool] = None,
696
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple, tuple]:
697
+ all_hidden_states = () if output_hidden_states else None
698
+ all_attentions = () if output_attentions else None
699
+
700
+ if keypoints.shape[2] == 0: # no keypoints
701
+ shape = keypoints.shape[:-1]
702
+ return (
703
+ keypoints.new_full(shape, -1, dtype=torch.int),
704
+ keypoints.new_zeros(shape),
705
+ keypoints.new_zeros(shape),
706
+ all_hidden_states,
707
+ all_attentions,
708
+ )
709
+
710
+ device = keypoints.device
711
+ batch_size, _, initial_num_keypoints, _ = keypoints.shape
712
+ num_points_per_pair = torch.sum(mask.reshape(batch_size, -1), dim=1)
713
+ # (batch_size, 2, num_keypoints, 2) -> (batch_size * 2, num_keypoints, 2)
714
+ keypoints = keypoints.reshape(batch_size * 2, initial_num_keypoints, 2)
715
+ mask = mask.reshape(batch_size * 2, initial_num_keypoints) if mask is not None else None
716
+ descriptors = descriptors.reshape(batch_size * 2, initial_num_keypoints, self.keypoint_detector_descriptor_dim)
717
+ image_indices = torch.arange(batch_size * 2, device=device)
718
+ # Keypoint normalization
719
+ keypoints = normalize_keypoints(keypoints, height, width)
720
+
721
+ descriptors, keypoint_encoding_output = self._keypoint_processing(
722
+ descriptors, keypoints, output_hidden_states=output_hidden_states
723
+ )
724
+
725
+ keypoints = keypoint_encoding_output[0]
726
+
727
+ # Early stop consists of stopping the forward pass through the transformer layers when the confidence of the
728
+ # keypoints is above a certain threshold.
729
+ do_early_stop = self.depth_confidence > 0
730
+ # Keypoint pruning consists of removing keypoints from the input of the transformer layers when the confidence of
731
+ # the keypoints is below a certain threshold.
732
+ do_keypoint_pruning = self.width_confidence > 0
733
+
734
+ early_stops_indices = []
735
+ matches = []
736
+ matching_scores = []
737
+ final_pruned_keypoints_indices = []
738
+ final_pruned_keypoints_iterations = []
739
+
740
+ pruned_keypoints_indices = torch.arange(0, initial_num_keypoints, device=device).expand(batch_size * 2, -1)
741
+ pruned_keypoints_iterations = torch.ones_like(pruned_keypoints_indices)
742
+
743
+ for layer_index in range(self.num_layers):
744
+ input_shape = descriptors.size()
745
+ if mask is not None:
746
+ extended_attention_mask = self.get_extended_attention_mask(mask, input_shape)
747
+ else:
748
+ extended_attention_mask = torch.ones((batch_size, input_shape[-2]), device=keypoints.device)
749
+ layer_output = self.transformer_layers[layer_index](
750
+ descriptors,
751
+ keypoints,
752
+ attention_mask=extended_attention_mask,
753
+ output_hidden_states=output_hidden_states,
754
+ output_attentions=output_attentions,
755
+ )
756
+ descriptors, hidden_states, attention = layer_output
757
+ if output_hidden_states:
758
+ all_hidden_states = all_hidden_states + hidden_states
759
+ if output_attentions:
760
+ all_attentions = all_attentions + attention
761
+
762
+ if do_early_stop:
763
+ if layer_index < self.num_layers - 1:
764
+ # Get the confidence of the keypoints for the current layer
765
+ keypoint_confidences = self.token_confidence[layer_index](descriptors)
766
+
767
+ # Determine which pairs of images should be early stopped based on the confidence of the keypoints for
768
+ # the current layer.
769
+ early_stopped_pairs = self._get_early_stopped_image_pairs(
770
+ keypoint_confidences, layer_index, mask, num_points=num_points_per_pair
771
+ )
772
+ else:
773
+ # Early stopping always occurs at the last layer
774
+ early_stopped_pairs = torch.ones(batch_size, dtype=torch.bool)
775
+
776
+ if torch.any(early_stopped_pairs):
777
+ # If a pair of images is considered early stopped, we compute the matches for the remaining
778
+ # keypoints and stop the forward pass through the transformer layers for this pair of images.
779
+ early_stops = early_stopped_pairs.repeat_interleave(2)
780
+ early_stopped_image_indices = image_indices[early_stops]
781
+ early_stopped_matches, early_stopped_matching_scores = self._get_keypoint_matching(
782
+ descriptors, mask, layer_index, early_stops=early_stops
783
+ )
784
+ early_stops_indices.extend(list(early_stopped_image_indices))
785
+ matches.extend(list(early_stopped_matches))
786
+ matching_scores.extend(list(early_stopped_matching_scores))
787
+ if do_keypoint_pruning:
788
+ final_pruned_keypoints_indices.extend(list(pruned_keypoints_indices[early_stops]))
789
+ final_pruned_keypoints_iterations.extend(list(pruned_keypoints_iterations[early_stops]))
790
+
791
+ # Remove image pairs that have been early stopped from the forward pass
792
+ num_points_per_pair = num_points_per_pair[~early_stopped_pairs]
793
+ descriptors, keypoints_0, keypoint_1, mask, image_indices = tuple(
794
+ tensor[~early_stops]
795
+ for tensor in [descriptors, keypoints[0], keypoints[1], mask, image_indices]
796
+ )
797
+ keypoints = (keypoints_0, keypoint_1)
798
+ if do_keypoint_pruning:
799
+ pruned_keypoints_indices, pruned_keypoints_iterations, keypoint_confidences = tuple(
800
+ tensor[~early_stops]
801
+ for tensor in [
802
+ pruned_keypoints_indices,
803
+ pruned_keypoints_iterations,
804
+ keypoint_confidences,
805
+ ]
806
+ )
807
+ # If all pairs of images are early stopped, we stop the forward pass through the transformer
808
+ # layers for all pairs of images.
809
+ if torch.all(early_stopped_pairs):
810
+ break
811
+
812
+ if do_keypoint_pruning:
813
+ # Prune keypoints from the input of the transformer layers for the next iterations if the confidence of
814
+ # the keypoints is below a certain threshold.
815
+ descriptors, keypoints, pruned_keypoints_indices, mask, pruned_keypoints_iterations = (
816
+ self._do_layer_keypoint_pruning(
817
+ descriptors,
818
+ keypoints,
819
+ mask,
820
+ pruned_keypoints_indices,
821
+ pruned_keypoints_iterations,
822
+ keypoint_confidences,
823
+ layer_index,
824
+ )
825
+ )
826
+
827
+ if do_early_stop and do_keypoint_pruning:
828
+ # Concatenate early stopped outputs together and perform final keypoint pruning
829
+ final_pruned_keypoints_indices, final_pruned_keypoints_iterations, matches, matching_scores = (
830
+ self._concat_early_stopped_outputs(
831
+ early_stops_indices,
832
+ final_pruned_keypoints_indices,
833
+ final_pruned_keypoints_iterations,
834
+ matches,
835
+ matching_scores,
836
+ )
837
+ )
838
+ matches, matching_scores = self._do_final_keypoint_pruning(
839
+ final_pruned_keypoints_indices,
840
+ matches,
841
+ matching_scores,
842
+ initial_num_keypoints,
843
+ )
844
+ else:
845
+ matches, matching_scores = self._get_keypoint_matching(descriptors, mask, self.num_layers - 1)
846
+ final_pruned_keypoints_iterations = torch.ones_like(matching_scores) * self.num_layers
847
+
848
+ final_pruned_keypoints_iterations = final_pruned_keypoints_iterations.reshape(
849
+ batch_size, 2, initial_num_keypoints
850
+ )
851
+
852
+ return (
853
+ matches,
854
+ matching_scores,
855
+ final_pruned_keypoints_iterations,
856
+ all_hidden_states,
857
+ all_attentions,
858
+ )
859
+
860
+ @can_return_tuple
861
+ @auto_docstring
862
+ def forward(
863
+ self,
864
+ pixel_values: torch.FloatTensor,
865
+ labels: Optional[torch.LongTensor] = None,
866
+ output_attentions: Optional[bool] = None,
867
+ output_hidden_states: Optional[bool] = None,
868
+ ) -> Union[tuple, LightGlueKeypointMatchingOutput]:
869
+ loss = None
870
+ if labels is not None:
871
+ raise ValueError("LightGlue is not trainable, no labels should be provided.")
872
+
873
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
874
+ output_hidden_states = (
875
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
876
+ )
877
+
878
+ if pixel_values.ndim != 5 or pixel_values.size(1) != 2:
879
+ raise ValueError("Input must be a 5D tensor of shape (batch_size, 2, num_channels, height, width)")
880
+
881
+ batch_size, _, channels, height, width = pixel_values.shape
882
+ pixel_values = pixel_values.reshape(batch_size * 2, channels, height, width)
883
+ keypoint_detections = self.keypoint_detector(pixel_values)
884
+
885
+ keypoints, _, descriptors, mask = keypoint_detections[:4]
886
+ keypoints = keypoints.reshape(batch_size, 2, -1, 2).to(pixel_values)
887
+ descriptors = descriptors.reshape(batch_size, 2, -1, self.keypoint_detector_descriptor_dim).to(pixel_values)
888
+ mask = mask.reshape(batch_size, 2, -1)
889
+
890
+ absolute_keypoints = keypoints.clone()
891
+ absolute_keypoints[:, :, :, 0] = absolute_keypoints[:, :, :, 0] * width
892
+ absolute_keypoints[:, :, :, 1] = absolute_keypoints[:, :, :, 1] * height
893
+
894
+ matches, matching_scores, prune, hidden_states, attentions = self._match_image_pair(
895
+ absolute_keypoints,
896
+ descriptors,
897
+ height,
898
+ width,
899
+ mask=mask,
900
+ output_attentions=output_attentions,
901
+ output_hidden_states=output_hidden_states,
902
+ )
903
+
904
+ return LightGlueKeypointMatchingOutput(
905
+ loss=loss,
906
+ matches=matches,
907
+ matching_scores=matching_scores,
908
+ keypoints=keypoints,
909
+ prune=prune,
910
+ mask=mask,
911
+ hidden_states=hidden_states,
912
+ attentions=attentions,
913
+ )
914
+
915
+
916
+ __all__ = ["LightGluePreTrainedModel", "LightGlueForKeypointMatching"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lightglue/modular_lightglue.py ADDED
@@ -0,0 +1,1074 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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 warnings
15
+ from dataclasses import dataclass
16
+ from typing import Callable, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ from torch import nn
21
+ from torch.nn.utils.rnn import pad_sequence
22
+
23
+ from ...configuration_utils import PretrainedConfig
24
+ from ...image_utils import ImageInput, is_vision_available, to_numpy_array
25
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
26
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
27
+ from ...processing_utils import Unpack
28
+ from ...utils import ModelOutput, TensorType, auto_docstring, is_matplotlib_available, logging
29
+ from ...utils.generic import can_return_tuple
30
+ from ..auto import CONFIG_MAPPING, AutoConfig
31
+ from ..auto.modeling_auto import AutoModelForKeypointDetection
32
+ from ..clip.modeling_clip import CLIPMLP
33
+ from ..cohere.modeling_cohere import apply_rotary_pos_emb
34
+ from ..llama.modeling_llama import LlamaAttention, eager_attention_forward
35
+ from ..superglue.image_processing_superglue import SuperGlueImageProcessor, validate_and_format_image_pairs
36
+ from ..superpoint import SuperPointConfig
37
+
38
+
39
+ if is_vision_available():
40
+ from PIL import Image, ImageDraw
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ class LightGlueConfig(PretrainedConfig):
47
+ r"""
48
+ This is the configuration class to store the configuration of a [`LightGlueForKeypointMatching`]. It is used to
49
+ instantiate a LightGlue model according to the specified arguments, defining the model architecture. Instantiating a
50
+ configuration with the defaults will yield a similar configuration to that of the LightGlue
51
+ [ETH-CVG/lightglue_superpoint](https://huggingface.co/ETH-CVG/lightglue_superpoint) architecture.
52
+
53
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
54
+ documentation from [`PretrainedConfig`] for more information.
55
+
56
+ Args:
57
+ keypoint_detector_config (`Union[AutoConfig, dict]`, *optional*, defaults to `SuperPointConfig`):
58
+ The config object or dictionary of the keypoint detector.
59
+ descriptor_dim (`int`, *optional*, defaults to 256):
60
+ The dimension of the descriptors.
61
+ num_hidden_layers (`int`, *optional*, defaults to 9):
62
+ The number of self and cross attention layers.
63
+ num_attention_heads (`int`, *optional*, defaults to 4):
64
+ The number of heads in the multi-head attention.
65
+ num_key_value_heads (`int`, *optional*):
66
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
67
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
68
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
69
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
70
+ by meanpooling all the original heads within that group. For more details checkout [this
71
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
72
+ `num_attention_heads`.
73
+ depth_confidence (`float`, *optional*, defaults to 0.95):
74
+ The confidence threshold used to perform early stopping
75
+ width_confidence (`float`, *optional*, defaults to 0.99):
76
+ The confidence threshold used to prune points
77
+ filter_threshold (`float`, *optional*, defaults to 0.1):
78
+ The confidence threshold used to filter matches
79
+ initializer_range (`float`, *optional*, defaults to 0.02):
80
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
81
+ hidden_act (`str`, *optional*, defaults to `"gelu"`):
82
+ The activation function to be used in the hidden layers.
83
+ attention_dropout (`float`, *optional*, defaults to 0.0):
84
+ The dropout ratio for the attention probabilities.
85
+ attention_bias (`bool`, *optional*, defaults to `True`):
86
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
87
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
88
+ Whether to trust remote code when using other models than SuperPoint as keypoint detector.
89
+
90
+ Examples:
91
+ ```python
92
+ >>> from transformers import LightGlueConfig, LightGlueForKeypointMatching
93
+
94
+ >>> # Initializing a LightGlue style configuration
95
+ >>> configuration = LightGlueConfig()
96
+
97
+ >>> # Initializing a model from the LightGlue style configuration
98
+ >>> model = LightGlueForKeypointMatching(configuration)
99
+
100
+ >>> # Accessing the model configuration
101
+ >>> configuration = model.config
102
+ ```
103
+ """
104
+
105
+ model_type = "lightglue"
106
+ sub_configs = {"keypoint_detector_config": AutoConfig}
107
+
108
+ def __init__(
109
+ self,
110
+ keypoint_detector_config: SuperPointConfig = None,
111
+ descriptor_dim: int = 256,
112
+ num_hidden_layers: int = 9,
113
+ num_attention_heads: int = 4,
114
+ num_key_value_heads=None,
115
+ depth_confidence: float = 0.95,
116
+ width_confidence: float = 0.99,
117
+ filter_threshold: float = 0.1,
118
+ initializer_range: float = 0.02,
119
+ hidden_act: str = "gelu",
120
+ attention_dropout=0.0,
121
+ attention_bias=True,
122
+ trust_remote_code: bool = False,
123
+ **kwargs,
124
+ ):
125
+ # LightGlue can be used with other models than SuperPoint as keypoint detector
126
+ # We provide the trust_remote_code argument to allow the use of other models
127
+ # that are not registered in the CONFIG_MAPPING dictionary (for example DISK)
128
+ self.trust_remote_code = trust_remote_code
129
+
130
+ if descriptor_dim % num_attention_heads != 0:
131
+ raise ValueError("descriptor_dim % num_heads is different from zero")
132
+
133
+ self.descriptor_dim = descriptor_dim
134
+ self.num_hidden_layers = num_hidden_layers
135
+ self.num_attention_heads = num_attention_heads
136
+
137
+ # for backward compatibility
138
+ if num_key_value_heads is None:
139
+ num_key_value_heads = num_attention_heads
140
+
141
+ self.num_key_value_heads = num_key_value_heads
142
+
143
+ self.depth_confidence = depth_confidence
144
+ self.width_confidence = width_confidence
145
+ self.filter_threshold = filter_threshold
146
+ self.initializer_range = initializer_range
147
+
148
+ # Keypoint Detector is forced into eager attention mode because SuperPoint does not have Attention
149
+ # See https://github.com/huggingface/transformers/pull/31718#discussion_r2109733153
150
+ if isinstance(keypoint_detector_config, dict):
151
+ keypoint_detector_config["model_type"] = keypoint_detector_config.get("model_type", "superpoint")
152
+ if keypoint_detector_config["model_type"] not in CONFIG_MAPPING:
153
+ keypoint_detector_config = AutoConfig.from_pretrained(
154
+ keypoint_detector_config["_name_or_path"], trust_remote_code=self.trust_remote_code
155
+ )
156
+ else:
157
+ keypoint_detector_config = CONFIG_MAPPING[keypoint_detector_config["model_type"]](
158
+ **keypoint_detector_config, attn_implementation="eager"
159
+ )
160
+
161
+ if keypoint_detector_config is None:
162
+ keypoint_detector_config = CONFIG_MAPPING["superpoint"](attn_implementation="eager")
163
+
164
+ self.keypoint_detector_config = keypoint_detector_config
165
+
166
+ self.hidden_size = descriptor_dim
167
+ self.intermediate_size = descriptor_dim * 2
168
+ self.hidden_act = hidden_act
169
+ self.attention_dropout = attention_dropout
170
+ self.attention_bias = attention_bias
171
+ super().__init__(**kwargs)
172
+
173
+
174
+ @dataclass
175
+ @auto_docstring(
176
+ custom_intro="""
177
+ Base class for outputs of LightGlue keypoint matching models. Due to the nature of keypoint detection and matching,
178
+ the number of keypoints is not fixed and can vary from image to image, which makes batching non-trivial. In the
179
+ batch of images, the maximum number of matches is set as the dimension of the matches and matching scores. The mask
180
+ tensor is used to indicate which values in the keypoints, matches, matching_scores and prune tensors are keypoint
181
+ matching information.
182
+ """
183
+ )
184
+ class LightGlueKeypointMatchingOutput(ModelOutput):
185
+ r"""
186
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*):
187
+ Loss computed during training.
188
+ matches (`torch.FloatTensor` of shape `(batch_size, 2, num_matches)`):
189
+ Index of keypoint matched in the other image.
190
+ matching_scores (`torch.FloatTensor` of shape `(batch_size, 2, num_matches)`):
191
+ Scores of predicted matches.
192
+ keypoints (`torch.FloatTensor` of shape `(batch_size, num_keypoints, 2)`):
193
+ Absolute (x, y) coordinates of predicted keypoints in a given image.
194
+ prune (`torch.IntTensor` of shape `(batch_size, num_keypoints)`):
195
+ Pruning mask indicating which keypoints are removed and at which layer.
196
+ mask (`torch.BoolTensor` of shape `(batch_size, num_keypoints)`):
197
+ Mask indicating which values in matches, matching_scores, keypoints and prune are keypoint matching
198
+ information.
199
+ hidden_states (`Tuple[torch.FloatTensor, ...]`, *optional*):
200
+ Tuple of `torch.FloatTensor` (one for the output of each stage) of shape `(batch_size, 2, num_channels,
201
+ num_keypoints)` returned when `output_hidden_states=True` is passed or when
202
+ `config.output_hidden_states=True`
203
+ attentions (`Tuple[torch.FloatTensor, ...]`, *optional*):
204
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, 2, num_heads, num_keypoints,
205
+ num_keypoints)` returned when `output_attentions=True` is passed or when
206
+ `config.output_attentions=True`
207
+ """
208
+
209
+ loss: Optional[torch.FloatTensor] = None
210
+ matches: Optional[torch.FloatTensor] = None
211
+ matching_scores: Optional[torch.FloatTensor] = None
212
+ keypoints: Optional[torch.FloatTensor] = None
213
+ prune: Optional[torch.IntTensor] = None
214
+ mask: Optional[torch.FloatTensor] = None
215
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
216
+ attentions: Optional[tuple[torch.FloatTensor]] = None
217
+
218
+
219
+ class LightGlueImageProcessor(SuperGlueImageProcessor):
220
+ def post_process_keypoint_matching(
221
+ self,
222
+ outputs: LightGlueKeypointMatchingOutput,
223
+ target_sizes: Union[TensorType, list[tuple]],
224
+ threshold: float = 0.0,
225
+ ) -> list[dict[str, torch.Tensor]]:
226
+ return super().post_process_keypoint_matching(outputs, target_sizes, threshold)
227
+
228
+ # Copied from transformers.models.efficientloftr.image_processing_efficientloftr.EfficientLoFTRImageProcessor.visualize_keypoint_matching with EfficientLoFTR->LightGlue
229
+ def visualize_keypoint_matching(
230
+ self,
231
+ images: ImageInput,
232
+ keypoint_matching_output: list[dict[str, torch.Tensor]],
233
+ ) -> list["Image.Image"]:
234
+ """
235
+ Plots the image pairs side by side with the detected keypoints as well as the matching between them.
236
+
237
+ Args:
238
+ images (`ImageInput`):
239
+ Image pairs to plot. Same as `LightGlueImageProcessor.preprocess`. Expects either a list of 2
240
+ images or a list of list of 2 images list with pixel values ranging from 0 to 255.
241
+ keypoint_matching_output (List[Dict[str, torch.Tensor]]]):
242
+ A post processed keypoint matching output
243
+
244
+ Returns:
245
+ `List[PIL.Image.Image]`: A list of PIL images, each containing the image pairs side by side with the detected
246
+ keypoints as well as the matching between them.
247
+ """
248
+ images = validate_and_format_image_pairs(images)
249
+ images = [to_numpy_array(image) for image in images]
250
+ image_pairs = [images[i : i + 2] for i in range(0, len(images), 2)]
251
+
252
+ results = []
253
+ for image_pair, pair_output in zip(image_pairs, keypoint_matching_output):
254
+ height0, width0 = image_pair[0].shape[:2]
255
+ height1, width1 = image_pair[1].shape[:2]
256
+ plot_image = np.zeros((max(height0, height1), width0 + width1, 3), dtype=np.uint8)
257
+ plot_image[:height0, :width0] = image_pair[0]
258
+ plot_image[:height1, width0:] = image_pair[1]
259
+
260
+ plot_image_pil = Image.fromarray(plot_image)
261
+ draw = ImageDraw.Draw(plot_image_pil)
262
+
263
+ keypoints0_x, keypoints0_y = pair_output["keypoints0"].unbind(1)
264
+ keypoints1_x, keypoints1_y = pair_output["keypoints1"].unbind(1)
265
+ for keypoint0_x, keypoint0_y, keypoint1_x, keypoint1_y, matching_score in zip(
266
+ keypoints0_x, keypoints0_y, keypoints1_x, keypoints1_y, pair_output["matching_scores"]
267
+ ):
268
+ color = self._get_color(matching_score)
269
+ draw.line(
270
+ (keypoint0_x, keypoint0_y, keypoint1_x + width0, keypoint1_y),
271
+ fill=color,
272
+ width=3,
273
+ )
274
+ draw.ellipse((keypoint0_x - 2, keypoint0_y - 2, keypoint0_x + 2, keypoint0_y + 2), fill="black")
275
+ draw.ellipse(
276
+ (keypoint1_x + width0 - 2, keypoint1_y - 2, keypoint1_x + width0 + 2, keypoint1_y + 2),
277
+ fill="black",
278
+ )
279
+
280
+ results.append(plot_image_pil)
281
+ return results
282
+
283
+ # Copied from transformers.models.efficientloftr.image_processing_efficientloftr.EfficientLoFTRImageProcessor._get_color
284
+ def _get_color(self, score):
285
+ """Maps a score to a color."""
286
+ r = int(255 * (1 - score))
287
+ g = int(255 * score)
288
+ b = 0
289
+ return (r, g, b)
290
+
291
+ def plot_keypoint_matching(self, images: ImageInput, keypoint_matching_output: LightGlueKeypointMatchingOutput):
292
+ """
293
+ Plots the image pairs side by side with the detected keypoints as well as the matching between them. Requires
294
+ matplotlib to be installed.
295
+
296
+ .. deprecated::
297
+ `plot_keypoint_matching` is deprecated and will be removed in a future version. Use `visualize_keypoint_matching` instead.
298
+
299
+ Args:
300
+ images (`ImageInput`):
301
+ Image pairs to plot. Same as `LightGlueImageProcessor.preprocess`. Expects either a list of 2 images or
302
+ a list of list of 2 images list with pixel values ranging from 0 to 255.
303
+ keypoint_matching_output ([`LightGlueKeypointMatchingOutput`]):
304
+ Raw outputs of the model.
305
+ """
306
+ warnings.warn(
307
+ "`plot_keypoint_matching` is deprecated and will be removed in transformers v. "
308
+ "Use `visualize_keypoint_matching` instead.",
309
+ FutureWarning,
310
+ )
311
+
312
+ if is_matplotlib_available():
313
+ import matplotlib.pyplot as plt
314
+ else:
315
+ raise ImportError("Please install matplotlib to use `plot_keypoint_matching` method")
316
+
317
+ images = validate_and_format_image_pairs(images)
318
+ images = [to_numpy_array(image) for image in images]
319
+ image_pairs = [images[i : i + 2] for i in range(0, len(images), 2)]
320
+
321
+ for image_pair, pair_output in zip(image_pairs, keypoint_matching_output):
322
+ height0, width0 = image_pair[0].shape[:2]
323
+ height1, width1 = image_pair[1].shape[:2]
324
+ plot_image = np.zeros((max(height0, height1), width0 + width1, 3))
325
+ plot_image[:height0, :width0] = image_pair[0] / 255.0
326
+ plot_image[:height1, width0:] = image_pair[1] / 255.0
327
+ plt.imshow(plot_image)
328
+ plt.axis("off")
329
+
330
+ keypoints0_x, keypoints0_y = pair_output["keypoints0"].unbind(1)
331
+ keypoints1_x, keypoints1_y = pair_output["keypoints1"].unbind(1)
332
+ for keypoint0_x, keypoint0_y, keypoint1_x, keypoint1_y, matching_score in zip(
333
+ keypoints0_x, keypoints0_y, keypoints1_x, keypoints1_y, pair_output["matching_scores"]
334
+ ):
335
+ plt.plot(
336
+ [keypoint0_x, keypoint1_x + width0],
337
+ [keypoint0_y, keypoint1_y],
338
+ color=plt.get_cmap("RdYlGn")(matching_score.item()),
339
+ alpha=0.9,
340
+ linewidth=0.5,
341
+ )
342
+ plt.scatter(keypoint0_x, keypoint0_y, c="black", s=2)
343
+ plt.scatter(keypoint1_x + width0, keypoint1_y, c="black", s=2)
344
+ plt.show()
345
+
346
+
347
+ class LightGluePositionalEncoder(nn.Module):
348
+ def __init__(self, config: LightGlueConfig):
349
+ super().__init__()
350
+ self.projector = nn.Linear(2, config.descriptor_dim // config.num_attention_heads // 2, bias=False)
351
+
352
+ def forward(
353
+ self, keypoints: torch.Tensor, output_hidden_states: Optional[bool] = False
354
+ ) -> Union[tuple[torch.Tensor], tuple[torch.Tensor, torch.Tensor]]:
355
+ projected_keypoints = self.projector(keypoints)
356
+ embeddings = projected_keypoints.repeat_interleave(2, dim=-1)
357
+ cosines = torch.cos(embeddings)
358
+ sines = torch.sin(embeddings)
359
+ embeddings = (cosines, sines)
360
+ output = (embeddings, projected_keypoints) if output_hidden_states else (embeddings,)
361
+ return output
362
+
363
+
364
+ class LightGlueAttention(LlamaAttention):
365
+ def forward(
366
+ self,
367
+ hidden_states: torch.Tensor,
368
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
369
+ attention_mask: Optional[torch.Tensor] = None,
370
+ encoder_hidden_states: Optional[torch.Tensor] = None,
371
+ encoder_attention_mask: Optional[torch.Tensor] = None,
372
+ **kwargs: Unpack[FlashAttentionKwargs],
373
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
374
+ input_shape = hidden_states.shape[:-1]
375
+ hidden_shape = (*input_shape, -1, self.head_dim)
376
+
377
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
378
+
379
+ is_cross_attention = encoder_hidden_states is not None
380
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
381
+ current_attention_mask = encoder_attention_mask if is_cross_attention else attention_mask
382
+
383
+ key_states = self.k_proj(current_states).view(hidden_shape).transpose(1, 2)
384
+ value_states = self.v_proj(current_states).view(hidden_shape).transpose(1, 2)
385
+
386
+ if position_embeddings is not None:
387
+ cos, sin = position_embeddings
388
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
389
+
390
+ attention_interface: Callable = eager_attention_forward
391
+ if self.config._attn_implementation != "eager":
392
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
393
+
394
+ attn_output, attn_weights = attention_interface(
395
+ self,
396
+ query_states,
397
+ key_states,
398
+ value_states,
399
+ current_attention_mask,
400
+ dropout=0.0 if not self.training else self.attention_dropout,
401
+ scaling=self.scaling,
402
+ **kwargs,
403
+ )
404
+
405
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
406
+ attn_output = self.o_proj(attn_output)
407
+ return attn_output, attn_weights
408
+
409
+
410
+ class LightGlueMLP(CLIPMLP):
411
+ def __init__(self, config: LightGlueConfig):
412
+ super().__init__(config)
413
+ self.fc1 = nn.Linear(config.intermediate_size, config.intermediate_size)
414
+ self.layer_norm = nn.LayerNorm(config.intermediate_size, elementwise_affine=True)
415
+
416
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
417
+ hidden_states = self.fc1(hidden_states)
418
+ hidden_states = self.layer_norm(hidden_states)
419
+ hidden_states = self.activation_fn(hidden_states)
420
+ hidden_states = self.fc2(hidden_states)
421
+ return hidden_states
422
+
423
+
424
+ class LightGlueTransformerLayer(nn.Module):
425
+ def __init__(self, config: LightGlueConfig, layer_idx: int):
426
+ super().__init__()
427
+ self.self_attention = LightGlueAttention(config, layer_idx)
428
+ self.self_mlp = LightGlueMLP(config)
429
+ self.cross_attention = LightGlueAttention(config, layer_idx)
430
+ self.cross_mlp = LightGlueMLP(config)
431
+
432
+ def forward(
433
+ self,
434
+ descriptors: torch.Tensor,
435
+ keypoints: torch.Tensor,
436
+ attention_mask: torch.Tensor,
437
+ output_hidden_states: Optional[bool] = False,
438
+ output_attentions: Optional[bool] = False,
439
+ ) -> tuple[torch.Tensor, Optional[tuple[torch.Tensor]], Optional[tuple[torch.Tensor]]]:
440
+ all_hidden_states = () if output_hidden_states else None
441
+ all_attentions = () if output_attentions else None
442
+
443
+ if output_hidden_states:
444
+ all_hidden_states = all_hidden_states + (descriptors,)
445
+
446
+ batch_size, num_keypoints, descriptor_dim = descriptors.shape
447
+
448
+ # Self attention block
449
+ attention_output, self_attentions = self.self_attention(
450
+ descriptors,
451
+ position_embeddings=keypoints,
452
+ attention_mask=attention_mask,
453
+ output_attentions=output_attentions,
454
+ )
455
+ intermediate_states = torch.cat([descriptors, attention_output], dim=-1)
456
+ output_states = self.self_mlp(intermediate_states)
457
+ self_attention_descriptors = descriptors + output_states
458
+
459
+ if output_hidden_states:
460
+ self_attention_hidden_states = (intermediate_states, output_states)
461
+
462
+ # Reshape hidden_states to group by image_pairs :
463
+ # (batch_size, num_keypoints, descriptor_dim) -> (batch_size, 2, num_keypoints, descriptor_dim)
464
+ # Flip dimension 1 to perform cross attention :
465
+ # (image0, image1) -> (image1, image0)
466
+ # Reshape back to original shape :
467
+ # (batch_size, 2, num_keypoints, descriptor_dim) -> (batch_size, num_keypoints, descriptor_dim)
468
+ encoder_hidden_states = (
469
+ self_attention_descriptors.reshape(-1, 2, num_keypoints, descriptor_dim)
470
+ .flip(1)
471
+ .reshape(batch_size, num_keypoints, descriptor_dim)
472
+ )
473
+ # Same for mask
474
+ encoder_attention_mask = (
475
+ attention_mask.reshape(-1, 2, 1, 1, num_keypoints).flip(1).reshape(batch_size, 1, 1, num_keypoints)
476
+ if attention_mask is not None
477
+ else None
478
+ )
479
+
480
+ # Cross attention block
481
+ cross_attention_output, cross_attentions = self.cross_attention(
482
+ self_attention_descriptors,
483
+ encoder_hidden_states=encoder_hidden_states,
484
+ encoder_attention_mask=encoder_attention_mask,
485
+ output_attentions=output_attentions,
486
+ )
487
+ cross_intermediate_states = torch.cat([self_attention_descriptors, cross_attention_output], dim=-1)
488
+ cross_output_states = self.cross_mlp(cross_intermediate_states)
489
+ descriptors = self_attention_descriptors + cross_output_states
490
+
491
+ if output_hidden_states:
492
+ cross_attention_hidden_states = (cross_intermediate_states, cross_output_states)
493
+ all_hidden_states = (
494
+ all_hidden_states
495
+ + (self_attention_descriptors.reshape(batch_size, num_keypoints, descriptor_dim),)
496
+ + self_attention_hidden_states
497
+ + (descriptors.reshape(batch_size, num_keypoints, descriptor_dim),)
498
+ + cross_attention_hidden_states
499
+ )
500
+
501
+ if output_attentions:
502
+ all_attentions = all_attentions + (self_attentions,) + (cross_attentions,)
503
+
504
+ return descriptors, all_hidden_states, all_attentions
505
+
506
+
507
+ def sigmoid_log_double_softmax(
508
+ similarity: torch.Tensor, matchability0: torch.Tensor, matchability1: torch.Tensor
509
+ ) -> torch.Tensor:
510
+ """create the log assignment matrix from logits and similarity"""
511
+ batch_size, num_keypoints_0, num_keypoints_1 = similarity.shape
512
+ certainties = nn.functional.logsigmoid(matchability0) + nn.functional.logsigmoid(matchability1).transpose(1, 2)
513
+ scores0 = nn.functional.log_softmax(similarity, 2)
514
+ scores1 = nn.functional.log_softmax(similarity.transpose(-1, -2).contiguous(), 2).transpose(-1, -2)
515
+ scores = similarity.new_full((batch_size, num_keypoints_0 + 1, num_keypoints_1 + 1), 0)
516
+ scores[:, :num_keypoints_0, :num_keypoints_1] = scores0 + scores1 + certainties
517
+ scores[:, :-1, -1] = nn.functional.logsigmoid(-matchability0.squeeze(-1))
518
+ scores[:, -1, :-1] = nn.functional.logsigmoid(-matchability1.squeeze(-1))
519
+ return scores
520
+
521
+
522
+ class LightGlueMatchAssignmentLayer(nn.Module):
523
+ def __init__(self, config: LightGlueConfig):
524
+ super().__init__()
525
+
526
+ self.descriptor_dim = config.descriptor_dim
527
+ self.final_projection = nn.Linear(self.descriptor_dim, self.descriptor_dim, bias=True)
528
+ self.matchability = nn.Linear(self.descriptor_dim, 1, bias=True)
529
+
530
+ def forward(self, descriptors: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
531
+ batch_size, num_keypoints, descriptor_dim = descriptors.shape
532
+ # Final projection and similarity computation
533
+ m_descriptors = self.final_projection(descriptors)
534
+ m_descriptors = m_descriptors / torch.tensor(self.descriptor_dim, device=m_descriptors.device) ** 0.25
535
+ m_descriptors = m_descriptors.reshape(batch_size // 2, 2, num_keypoints, descriptor_dim)
536
+ m_descriptors0 = m_descriptors[:, 0]
537
+ m_descriptors1 = m_descriptors[:, 1]
538
+ similarity = m_descriptors0 @ m_descriptors1.transpose(-1, -2)
539
+ if mask is not None:
540
+ mask = mask.reshape(batch_size // 2, 2, num_keypoints)
541
+ mask0 = mask[:, 0].unsqueeze(-1)
542
+ mask1 = mask[:, 1].unsqueeze(-1).transpose(-1, -2)
543
+ mask = mask0 * mask1
544
+ similarity = similarity.masked_fill(mask == 0, torch.finfo(similarity.dtype).min)
545
+
546
+ # Compute matchability of descriptors
547
+ matchability = self.matchability(descriptors)
548
+ matchability = matchability.reshape(batch_size // 2, 2, num_keypoints, 1)
549
+ matchability_0 = matchability[:, 0]
550
+ matchability_1 = matchability[:, 1]
551
+
552
+ # Compute scores from similarity and matchability
553
+ scores = sigmoid_log_double_softmax(similarity, matchability_0, matchability_1)
554
+ return scores
555
+
556
+ def get_matchability(self, descriptors: torch.Tensor) -> torch.Tensor:
557
+ """Get matchability of descriptors as a probability"""
558
+ matchability = self.matchability(descriptors)
559
+ matchability = nn.functional.sigmoid(matchability).squeeze(-1)
560
+ return matchability
561
+
562
+
563
+ class LightGlueTokenConfidenceLayer(nn.Module):
564
+ def __init__(self, config: LightGlueConfig):
565
+ super().__init__()
566
+
567
+ self.token = nn.Linear(config.descriptor_dim, 1)
568
+
569
+ def forward(self, descriptors: torch.Tensor) -> torch.Tensor:
570
+ token = self.token(descriptors.detach())
571
+ token = nn.functional.sigmoid(token).squeeze(-1)
572
+ return token
573
+
574
+
575
+ @auto_docstring
576
+ class LightGluePreTrainedModel(PreTrainedModel):
577
+ """
578
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
579
+ models.
580
+ """
581
+
582
+ config: LightGlueConfig
583
+ base_model_prefix = "lightglue"
584
+ main_input_name = "pixel_values"
585
+ supports_gradient_checkpointing = False
586
+ _supports_flash_attn = True
587
+ _supports_sdpa = True
588
+
589
+
590
+ def get_matches_from_scores(scores: torch.Tensor, threshold: float) -> tuple[torch.Tensor, torch.Tensor]:
591
+ """obtain matches from a score matrix [Bx M+1 x N+1]"""
592
+ batch_size, _, _ = scores.shape
593
+ # For each keypoint, get the best match
594
+ max0 = scores[:, :-1, :-1].max(2)
595
+ max1 = scores[:, :-1, :-1].max(1)
596
+ matches0 = max0.indices
597
+ matches1 = max1.indices
598
+
599
+ # Mutual check for matches
600
+ indices0 = torch.arange(matches0.shape[1], device=matches0.device)[None]
601
+ indices1 = torch.arange(matches1.shape[1], device=matches1.device)[None]
602
+ mutual0 = indices0 == matches1.gather(1, matches0)
603
+ mutual1 = indices1 == matches0.gather(1, matches1)
604
+
605
+ # Get matching scores and filter based on mutual check and thresholding
606
+ max0 = max0.values.exp()
607
+ zero = max0.new_tensor(0)
608
+ matching_scores0 = torch.where(mutual0, max0, zero)
609
+ matching_scores1 = torch.where(mutual1, matching_scores0.gather(1, matches1), zero)
610
+ valid0 = mutual0 & (matching_scores0 > threshold)
611
+ valid1 = mutual1 & valid0.gather(1, matches1)
612
+
613
+ # Filter matches based on mutual check and thresholding of scores
614
+ matches0 = torch.where(valid0, matches0, -1)
615
+ matches1 = torch.where(valid1, matches1, -1)
616
+ matches = torch.stack([matches0, matches1]).transpose(0, 1).reshape(batch_size * 2, -1)
617
+ matching_scores = torch.stack([matching_scores0, matching_scores1]).transpose(0, 1).reshape(batch_size * 2, -1)
618
+
619
+ return matches, matching_scores
620
+
621
+
622
+ def normalize_keypoints(keypoints: torch.Tensor, height: int, width: int) -> torch.Tensor:
623
+ """
624
+ Normalize keypoints locations based on image image_shape
625
+
626
+ Args:
627
+ keypoints (`torch.Tensor` of shape `(batch_size, num_keypoints, 2)`):
628
+ Keypoints locations in (x, y) format.
629
+ height (`int`):
630
+ Image height.
631
+ width (`int`):
632
+ Image width.
633
+
634
+ Returns:
635
+ Normalized keypoints locations of shape (`torch.Tensor` of shape `(batch_size, num_keypoints, 2)`).
636
+ """
637
+ size = torch.tensor([width, height], device=keypoints.device, dtype=keypoints.dtype)[None]
638
+ shift = size / 2
639
+ scale = size.max(-1).values / 2
640
+ keypoints = (keypoints - shift[..., None, :]) / scale[..., None, None]
641
+ return keypoints
642
+
643
+
644
+ @auto_docstring(
645
+ custom_intro="""
646
+ LightGlue model taking images as inputs and outputting the matching of them.
647
+ """
648
+ )
649
+ class LightGlueForKeypointMatching(LightGluePreTrainedModel):
650
+ """
651
+ LightGlue is a model matching keypoints in images by leveraging detections from a keypoint detector such as
652
+ SuperPoint. It is based on the SuperGlue architecture and is designed to be lightweight and efficient.
653
+ It consists of :
654
+ 1. Keypoint Encoder
655
+ 2. A Graph Neural Network with self and cross attention layers
656
+ 3. Matching Assignment layers
657
+
658
+ The correspondence ids use -1 to indicate non-matching points.
659
+
660
+ Philipp Lindenberger, Paul-Edouard Sarlin and Marc Pollefeys. LightGlue: Local Feature Matching at Light Speed.
661
+ In ICCV 2023. https://arxiv.org/pdf/2306.13643.pdf
662
+ """
663
+
664
+ def __init__(self, config: LightGlueConfig):
665
+ super().__init__(config)
666
+ self.keypoint_detector = AutoModelForKeypointDetection.from_config(
667
+ config.keypoint_detector_config, trust_remote_code=config.trust_remote_code
668
+ )
669
+
670
+ self.keypoint_detector_descriptor_dim = config.keypoint_detector_config.descriptor_decoder_dim
671
+ self.descriptor_dim = config.descriptor_dim
672
+ self.num_layers = config.num_hidden_layers
673
+ self.filter_threshold = config.filter_threshold
674
+ self.depth_confidence = config.depth_confidence
675
+ self.width_confidence = config.width_confidence
676
+
677
+ if self.descriptor_dim != self.keypoint_detector_descriptor_dim:
678
+ self.input_projection = nn.Linear(self.keypoint_detector_descriptor_dim, self.descriptor_dim, bias=True)
679
+ else:
680
+ self.input_projection = nn.Identity()
681
+
682
+ self.positional_encoder = LightGluePositionalEncoder(config)
683
+
684
+ self.transformer_layers = nn.ModuleList(
685
+ [LightGlueTransformerLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)]
686
+ )
687
+ self.match_assignment_layers = nn.ModuleList(
688
+ [LightGlueMatchAssignmentLayer(config) for _ in range(config.num_hidden_layers)]
689
+ )
690
+ self.token_confidence = nn.ModuleList(
691
+ [LightGlueTokenConfidenceLayer(config) for _ in range(config.num_hidden_layers - 1)]
692
+ )
693
+
694
+ self.post_init()
695
+
696
+ def _get_confidence_threshold(self, layer_index: int) -> float:
697
+ """scaled confidence threshold for a given layer"""
698
+ threshold = 0.8 + 0.1 * np.exp(-4.0 * layer_index / self.num_layers)
699
+ return np.clip(threshold, 0, 1)
700
+
701
+ def _keypoint_processing(
702
+ self, descriptors: torch.Tensor, keypoints: torch.Tensor, output_hidden_states: Optional[bool] = False
703
+ ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
704
+ descriptors = descriptors.detach().contiguous()
705
+ projected_descriptors = self.input_projection(descriptors)
706
+ keypoint_encoding_output = self.positional_encoder(keypoints, output_hidden_states=output_hidden_states)
707
+ return projected_descriptors, keypoint_encoding_output
708
+
709
+ def _get_early_stopped_image_pairs(
710
+ self, keypoint_confidences: torch.Tensor, layer_index: int, mask: torch.Tensor, num_points: torch.Tensor
711
+ ) -> torch.Tensor:
712
+ """evaluate whether we should stop inference based on the confidence of the keypoints"""
713
+ batch_size, _ = mask.shape
714
+ if layer_index < self.num_layers - 1:
715
+ # If the current layer is not the last layer, we compute the confidence of the keypoints and check
716
+ # if we should stop the forward pass through the transformer layers for each pair of images.
717
+ keypoint_confidences = keypoint_confidences.masked_fill(mask == 0, 1)
718
+ keypoint_confidences = keypoint_confidences.reshape(batch_size // 2, -1)
719
+ threshold = self._get_confidence_threshold(layer_index)
720
+ ratio_confident = 1.0 - (keypoint_confidences < threshold).float().sum(dim=1) / num_points
721
+ early_stopped_pairs = ratio_confident > self.depth_confidence
722
+ else:
723
+ # If the current layer is the last layer, we stop the forward pass through the transformer layers for
724
+ # all pairs of images.
725
+ early_stopped_pairs = torch.ones(batch_size, dtype=torch.bool)
726
+ return early_stopped_pairs
727
+
728
+ def _get_keypoint_matching(self, descriptors, mask, layer_index, early_stops=None):
729
+ if early_stops is not None:
730
+ descriptors = descriptors[early_stops]
731
+ mask = mask[early_stops]
732
+ scores = self.match_assignment_layers[layer_index](descriptors, mask)
733
+ matches, matching_scores = get_matches_from_scores(scores, self.filter_threshold)
734
+ return matches, matching_scores
735
+
736
+ def _get_pruning_mask(self, confidences: torch.Tensor, scores: torch.Tensor, layer_index: int) -> torch.Tensor:
737
+ """mask points which should be removed"""
738
+ keep = scores > (1 - self.width_confidence)
739
+ if confidences is not None: # Low-confidence points are never pruned.
740
+ keep |= confidences <= self._get_confidence_threshold(layer_index)
741
+ return keep
742
+
743
+ def _do_layer_keypoint_pruning(
744
+ self,
745
+ descriptors: torch.Tensor,
746
+ keypoints: torch.Tensor,
747
+ mask: torch.Tensor,
748
+ indices: torch.Tensor,
749
+ prune_output: torch.Tensor,
750
+ keypoint_confidences: torch.Tensor,
751
+ layer_index: int,
752
+ ):
753
+ """
754
+ For a given layer, prune keypoints based on the confidence of the keypoints and the matchability of the
755
+ descriptors.
756
+ """
757
+ batch_size, _, _ = descriptors.shape
758
+ descriptors_matchability = self.match_assignment_layers[layer_index].get_matchability(descriptors)
759
+ pruned_keypoints_mask = self._get_pruning_mask(keypoint_confidences, descriptors_matchability, layer_index)
760
+ pruned_keypoints_mask = pruned_keypoints_mask.masked_fill(mask == 0, torch.tensor(False))
761
+
762
+ # For each image, we extract the pruned indices and the corresponding descriptors and keypoints.
763
+ pruned_descriptors, pruned_keypoints_0, pruned_keypoints_1, pruned_mask, pruned_indices = (
764
+ [t[mask] for t, mask in zip(tensor, pruned_keypoints_mask)]
765
+ for tensor in [descriptors, keypoints[0], keypoints[1], pruned_keypoints_mask, indices]
766
+ )
767
+ for i in range(batch_size):
768
+ prune_output[i, pruned_indices[i]] += 1
769
+
770
+ # Pad the pruned descriptors, keypoints, indices and mask to have the same shape across the batch.
771
+ pruned_descriptors, pruned_keypoints_0, pruned_keypoints_1, pruned_mask = (
772
+ pad_sequence(pruned_tensor, batch_first=True)
773
+ for pruned_tensor in [pruned_descriptors, pruned_keypoints_0, pruned_keypoints_1, pruned_mask]
774
+ )
775
+ pruned_keypoints = (pruned_keypoints_0, pruned_keypoints_1)
776
+ pruned_indices = pad_sequence(pruned_indices, batch_first=True, padding_value=-1)
777
+
778
+ return pruned_descriptors, pruned_keypoints, pruned_indices, pruned_mask, prune_output
779
+
780
+ def _concat_early_stopped_outputs(
781
+ self,
782
+ early_stops_indices,
783
+ final_pruned_keypoints_indices,
784
+ final_pruned_keypoints_iterations,
785
+ matches,
786
+ matching_scores,
787
+ ):
788
+ early_stops_indices = torch.stack(early_stops_indices)
789
+ matches, final_pruned_keypoints_indices = (
790
+ pad_sequence(tensor, batch_first=True, padding_value=-1)
791
+ for tensor in [matches, final_pruned_keypoints_indices]
792
+ )
793
+ matching_scores, final_pruned_keypoints_iterations = (
794
+ pad_sequence(tensor, batch_first=True, padding_value=0)
795
+ for tensor in [matching_scores, final_pruned_keypoints_iterations]
796
+ )
797
+ matches, matching_scores, final_pruned_keypoints_indices, final_pruned_keypoints_iterations = (
798
+ tensor[early_stops_indices]
799
+ for tensor in [
800
+ matches,
801
+ matching_scores,
802
+ final_pruned_keypoints_indices,
803
+ final_pruned_keypoints_iterations,
804
+ ]
805
+ )
806
+ return final_pruned_keypoints_indices, final_pruned_keypoints_iterations, matches, matching_scores
807
+
808
+ def _do_final_keypoint_pruning(
809
+ self,
810
+ indices: torch.Tensor,
811
+ matches: torch.Tensor,
812
+ matching_scores: torch.Tensor,
813
+ num_keypoints: torch.Tensor,
814
+ ) -> tuple[torch.Tensor, torch.Tensor]:
815
+ # (batch_size, num_keypoints) -> (batch_size // 2, 2, num_keypoints) -> 2 * (batch_size // 2, num_keypoints) to
816
+ # have tensors from
817
+ batch_size, _ = indices.shape
818
+ indices, matches, matching_scores = (
819
+ tensor.reshape(batch_size // 2, 2, -1) for tensor in [indices, matches, matching_scores]
820
+ )
821
+ indices0 = indices[:, 0]
822
+ indices1 = indices[:, 1]
823
+ matches0 = matches[:, 0]
824
+ matches1 = matches[:, 1]
825
+ matching_scores0 = matching_scores[:, 0]
826
+ matching_scores1 = matching_scores[:, 1]
827
+
828
+ # Prepare final matches and matching scores
829
+ _matches = torch.full((batch_size // 2, 2, num_keypoints), -1, device=indices.device, dtype=matches.dtype)
830
+ _matching_scores = torch.zeros(
831
+ (batch_size // 2, 2, num_keypoints), device=indices.device, dtype=matching_scores.dtype
832
+ )
833
+ # Fill the matches and matching scores for each image pair
834
+ for i in range(batch_size // 2):
835
+ _matches[i, 0, indices0[i]] = torch.where(
836
+ matches0[i] == -1, -1, indices1[i].gather(0, matches0[i].clamp(min=0))
837
+ )
838
+ _matches[i, 1, indices1[i]] = torch.where(
839
+ matches1[i] == -1, -1, indices0[i].gather(0, matches1[i].clamp(min=0))
840
+ )
841
+ _matching_scores[i, 0, indices0[i]] = matching_scores0[i]
842
+ _matching_scores[i, 1, indices1[i]] = matching_scores1[i]
843
+ return _matches, _matching_scores
844
+
845
+ def _match_image_pair(
846
+ self,
847
+ keypoints: torch.Tensor,
848
+ descriptors: torch.Tensor,
849
+ height: int,
850
+ width: int,
851
+ mask: torch.Tensor = None,
852
+ output_attentions: Optional[bool] = None,
853
+ output_hidden_states: Optional[bool] = None,
854
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple, tuple]:
855
+ all_hidden_states = () if output_hidden_states else None
856
+ all_attentions = () if output_attentions else None
857
+
858
+ if keypoints.shape[2] == 0: # no keypoints
859
+ shape = keypoints.shape[:-1]
860
+ return (
861
+ keypoints.new_full(shape, -1, dtype=torch.int),
862
+ keypoints.new_zeros(shape),
863
+ keypoints.new_zeros(shape),
864
+ all_hidden_states,
865
+ all_attentions,
866
+ )
867
+
868
+ device = keypoints.device
869
+ batch_size, _, initial_num_keypoints, _ = keypoints.shape
870
+ num_points_per_pair = torch.sum(mask.reshape(batch_size, -1), dim=1)
871
+ # (batch_size, 2, num_keypoints, 2) -> (batch_size * 2, num_keypoints, 2)
872
+ keypoints = keypoints.reshape(batch_size * 2, initial_num_keypoints, 2)
873
+ mask = mask.reshape(batch_size * 2, initial_num_keypoints) if mask is not None else None
874
+ descriptors = descriptors.reshape(batch_size * 2, initial_num_keypoints, self.keypoint_detector_descriptor_dim)
875
+ image_indices = torch.arange(batch_size * 2, device=device)
876
+ # Keypoint normalization
877
+ keypoints = normalize_keypoints(keypoints, height, width)
878
+
879
+ descriptors, keypoint_encoding_output = self._keypoint_processing(
880
+ descriptors, keypoints, output_hidden_states=output_hidden_states
881
+ )
882
+
883
+ keypoints = keypoint_encoding_output[0]
884
+
885
+ # Early stop consists of stopping the forward pass through the transformer layers when the confidence of the
886
+ # keypoints is above a certain threshold.
887
+ do_early_stop = self.depth_confidence > 0
888
+ # Keypoint pruning consists of removing keypoints from the input of the transformer layers when the confidence of
889
+ # the keypoints is below a certain threshold.
890
+ do_keypoint_pruning = self.width_confidence > 0
891
+
892
+ early_stops_indices = []
893
+ matches = []
894
+ matching_scores = []
895
+ final_pruned_keypoints_indices = []
896
+ final_pruned_keypoints_iterations = []
897
+
898
+ pruned_keypoints_indices = torch.arange(0, initial_num_keypoints, device=device).expand(batch_size * 2, -1)
899
+ pruned_keypoints_iterations = torch.ones_like(pruned_keypoints_indices)
900
+
901
+ for layer_index in range(self.num_layers):
902
+ input_shape = descriptors.size()
903
+ if mask is not None:
904
+ extended_attention_mask = self.get_extended_attention_mask(mask, input_shape)
905
+ else:
906
+ extended_attention_mask = torch.ones((batch_size, input_shape[-2]), device=keypoints.device)
907
+ layer_output = self.transformer_layers[layer_index](
908
+ descriptors,
909
+ keypoints,
910
+ attention_mask=extended_attention_mask,
911
+ output_hidden_states=output_hidden_states,
912
+ output_attentions=output_attentions,
913
+ )
914
+ descriptors, hidden_states, attention = layer_output
915
+ if output_hidden_states:
916
+ all_hidden_states = all_hidden_states + hidden_states
917
+ if output_attentions:
918
+ all_attentions = all_attentions + attention
919
+
920
+ if do_early_stop:
921
+ if layer_index < self.num_layers - 1:
922
+ # Get the confidence of the keypoints for the current layer
923
+ keypoint_confidences = self.token_confidence[layer_index](descriptors)
924
+
925
+ # Determine which pairs of images should be early stopped based on the confidence of the keypoints for
926
+ # the current layer.
927
+ early_stopped_pairs = self._get_early_stopped_image_pairs(
928
+ keypoint_confidences, layer_index, mask, num_points=num_points_per_pair
929
+ )
930
+ else:
931
+ # Early stopping always occurs at the last layer
932
+ early_stopped_pairs = torch.ones(batch_size, dtype=torch.bool)
933
+
934
+ if torch.any(early_stopped_pairs):
935
+ # If a pair of images is considered early stopped, we compute the matches for the remaining
936
+ # keypoints and stop the forward pass through the transformer layers for this pair of images.
937
+ early_stops = early_stopped_pairs.repeat_interleave(2)
938
+ early_stopped_image_indices = image_indices[early_stops]
939
+ early_stopped_matches, early_stopped_matching_scores = self._get_keypoint_matching(
940
+ descriptors, mask, layer_index, early_stops=early_stops
941
+ )
942
+ early_stops_indices.extend(list(early_stopped_image_indices))
943
+ matches.extend(list(early_stopped_matches))
944
+ matching_scores.extend(list(early_stopped_matching_scores))
945
+ if do_keypoint_pruning:
946
+ final_pruned_keypoints_indices.extend(list(pruned_keypoints_indices[early_stops]))
947
+ final_pruned_keypoints_iterations.extend(list(pruned_keypoints_iterations[early_stops]))
948
+
949
+ # Remove image pairs that have been early stopped from the forward pass
950
+ num_points_per_pair = num_points_per_pair[~early_stopped_pairs]
951
+ descriptors, keypoints_0, keypoint_1, mask, image_indices = tuple(
952
+ tensor[~early_stops]
953
+ for tensor in [descriptors, keypoints[0], keypoints[1], mask, image_indices]
954
+ )
955
+ keypoints = (keypoints_0, keypoint_1)
956
+ if do_keypoint_pruning:
957
+ pruned_keypoints_indices, pruned_keypoints_iterations, keypoint_confidences = tuple(
958
+ tensor[~early_stops]
959
+ for tensor in [
960
+ pruned_keypoints_indices,
961
+ pruned_keypoints_iterations,
962
+ keypoint_confidences,
963
+ ]
964
+ )
965
+ # If all pairs of images are early stopped, we stop the forward pass through the transformer
966
+ # layers for all pairs of images.
967
+ if torch.all(early_stopped_pairs):
968
+ break
969
+
970
+ if do_keypoint_pruning:
971
+ # Prune keypoints from the input of the transformer layers for the next iterations if the confidence of
972
+ # the keypoints is below a certain threshold.
973
+ descriptors, keypoints, pruned_keypoints_indices, mask, pruned_keypoints_iterations = (
974
+ self._do_layer_keypoint_pruning(
975
+ descriptors,
976
+ keypoints,
977
+ mask,
978
+ pruned_keypoints_indices,
979
+ pruned_keypoints_iterations,
980
+ keypoint_confidences,
981
+ layer_index,
982
+ )
983
+ )
984
+
985
+ if do_early_stop and do_keypoint_pruning:
986
+ # Concatenate early stopped outputs together and perform final keypoint pruning
987
+ final_pruned_keypoints_indices, final_pruned_keypoints_iterations, matches, matching_scores = (
988
+ self._concat_early_stopped_outputs(
989
+ early_stops_indices,
990
+ final_pruned_keypoints_indices,
991
+ final_pruned_keypoints_iterations,
992
+ matches,
993
+ matching_scores,
994
+ )
995
+ )
996
+ matches, matching_scores = self._do_final_keypoint_pruning(
997
+ final_pruned_keypoints_indices,
998
+ matches,
999
+ matching_scores,
1000
+ initial_num_keypoints,
1001
+ )
1002
+ else:
1003
+ matches, matching_scores = self._get_keypoint_matching(descriptors, mask, self.num_layers - 1)
1004
+ final_pruned_keypoints_iterations = torch.ones_like(matching_scores) * self.num_layers
1005
+
1006
+ final_pruned_keypoints_iterations = final_pruned_keypoints_iterations.reshape(
1007
+ batch_size, 2, initial_num_keypoints
1008
+ )
1009
+
1010
+ return (
1011
+ matches,
1012
+ matching_scores,
1013
+ final_pruned_keypoints_iterations,
1014
+ all_hidden_states,
1015
+ all_attentions,
1016
+ )
1017
+
1018
+ @can_return_tuple
1019
+ @auto_docstring
1020
+ def forward(
1021
+ self,
1022
+ pixel_values: torch.FloatTensor,
1023
+ labels: Optional[torch.LongTensor] = None,
1024
+ output_attentions: Optional[bool] = None,
1025
+ output_hidden_states: Optional[bool] = None,
1026
+ ) -> Union[tuple, LightGlueKeypointMatchingOutput]:
1027
+ loss = None
1028
+ if labels is not None:
1029
+ raise ValueError("LightGlue is not trainable, no labels should be provided.")
1030
+
1031
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1032
+ output_hidden_states = (
1033
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1034
+ )
1035
+
1036
+ if pixel_values.ndim != 5 or pixel_values.size(1) != 2:
1037
+ raise ValueError("Input must be a 5D tensor of shape (batch_size, 2, num_channels, height, width)")
1038
+
1039
+ batch_size, _, channels, height, width = pixel_values.shape
1040
+ pixel_values = pixel_values.reshape(batch_size * 2, channels, height, width)
1041
+ keypoint_detections = self.keypoint_detector(pixel_values)
1042
+
1043
+ keypoints, _, descriptors, mask = keypoint_detections[:4]
1044
+ keypoints = keypoints.reshape(batch_size, 2, -1, 2).to(pixel_values)
1045
+ descriptors = descriptors.reshape(batch_size, 2, -1, self.keypoint_detector_descriptor_dim).to(pixel_values)
1046
+ mask = mask.reshape(batch_size, 2, -1)
1047
+
1048
+ absolute_keypoints = keypoints.clone()
1049
+ absolute_keypoints[:, :, :, 0] = absolute_keypoints[:, :, :, 0] * width
1050
+ absolute_keypoints[:, :, :, 1] = absolute_keypoints[:, :, :, 1] * height
1051
+
1052
+ matches, matching_scores, prune, hidden_states, attentions = self._match_image_pair(
1053
+ absolute_keypoints,
1054
+ descriptors,
1055
+ height,
1056
+ width,
1057
+ mask=mask,
1058
+ output_attentions=output_attentions,
1059
+ output_hidden_states=output_hidden_states,
1060
+ )
1061
+
1062
+ return LightGlueKeypointMatchingOutput(
1063
+ loss=loss,
1064
+ matches=matches,
1065
+ matching_scores=matching_scores,
1066
+ keypoints=keypoints,
1067
+ prune=prune,
1068
+ mask=mask,
1069
+ hidden_states=hidden_states,
1070
+ attentions=attentions,
1071
+ )
1072
+
1073
+
1074
+ __all__ = ["LightGluePreTrainedModel", "LightGlueForKeypointMatching", "LightGlueConfig", "LightGlueImageProcessor"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lilt/__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_lilt import *
22
+ from .modeling_lilt 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-5cbfd9f64dbc/environment/source/src/transformers/models/lilt/configuration_lilt.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """LiLT 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 LiltConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`LiltModel`]. It is used to instantiate a LiLT
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 LiLT
29
+ [SCUT-DLVCLab/lilt-roberta-en-base](https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base) architecture.
30
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
31
+ documentation from [`PretrainedConfig`] for more information.
32
+
33
+ Args:
34
+ vocab_size (`int`, *optional*, defaults to 30522):
35
+ Vocabulary size of the LiLT model. Defines the number of different tokens that can be represented by the
36
+ `inputs_ids` passed when calling [`LiltModel`].
37
+ hidden_size (`int`, *optional*, defaults to 768):
38
+ Dimensionality of the encoder layers and the pooler layer. Should be a multiple of 24.
39
+ num_hidden_layers (`int`, *optional*, defaults to 12):
40
+ Number of hidden layers in the Transformer encoder.
41
+ num_attention_heads (`int`, *optional*, defaults to 12):
42
+ Number of attention heads for each attention layer in the Transformer encoder.
43
+ intermediate_size (`int`, *optional*, defaults to 3072):
44
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
45
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
46
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
47
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
48
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
49
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
50
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
51
+ The dropout ratio for the attention probabilities.
52
+ max_position_embeddings (`int`, *optional*, defaults to 512):
53
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
54
+ just in case (e.g., 512 or 1024 or 2048).
55
+ type_vocab_size (`int`, *optional*, defaults to 2):
56
+ The vocabulary size of the `token_type_ids` passed when calling [`LiltModel`].
57
+ initializer_range (`float`, *optional*, defaults to 0.02):
58
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
59
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
60
+ The epsilon used by the layer normalization layers.
61
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
62
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
63
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
64
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
65
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
66
+ with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
67
+ classifier_dropout (`float`, *optional*):
68
+ The dropout ratio for the classification head.
69
+ channel_shrink_ratio (`int`, *optional*, defaults to 4):
70
+ The shrink ratio compared to the `hidden_size` for the channel dimension of the layout embeddings.
71
+ max_2d_position_embeddings (`int`, *optional*, defaults to 1024):
72
+ The maximum value that the 2D position embedding might ever be used with. Typically set this to something
73
+ large just in case (e.g., 1024).
74
+
75
+ Examples:
76
+
77
+ ```python
78
+ >>> from transformers import LiltConfig, LiltModel
79
+
80
+ >>> # Initializing a LiLT SCUT-DLVCLab/lilt-roberta-en-base style configuration
81
+ >>> configuration = LiltConfig()
82
+ >>> # Randomly initializing a model from the SCUT-DLVCLab/lilt-roberta-en-base style configuration
83
+ >>> model = LiltModel(configuration)
84
+ >>> # Accessing the model configuration
85
+ >>> configuration = model.config
86
+ ```"""
87
+
88
+ model_type = "lilt"
89
+
90
+ def __init__(
91
+ self,
92
+ vocab_size=30522,
93
+ hidden_size=768,
94
+ num_hidden_layers=12,
95
+ num_attention_heads=12,
96
+ intermediate_size=3072,
97
+ hidden_act="gelu",
98
+ hidden_dropout_prob=0.1,
99
+ attention_probs_dropout_prob=0.1,
100
+ max_position_embeddings=512,
101
+ type_vocab_size=2,
102
+ initializer_range=0.02,
103
+ layer_norm_eps=1e-12,
104
+ pad_token_id=0,
105
+ position_embedding_type="absolute",
106
+ classifier_dropout=None,
107
+ channel_shrink_ratio=4,
108
+ max_2d_position_embeddings=1024,
109
+ **kwargs,
110
+ ):
111
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
112
+
113
+ self.vocab_size = vocab_size
114
+ self.hidden_size = hidden_size
115
+ self.num_hidden_layers = num_hidden_layers
116
+ self.num_attention_heads = num_attention_heads
117
+ self.hidden_act = hidden_act
118
+ self.intermediate_size = intermediate_size
119
+ self.hidden_dropout_prob = hidden_dropout_prob
120
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
121
+ self.max_position_embeddings = max_position_embeddings
122
+ self.type_vocab_size = type_vocab_size
123
+ self.initializer_range = initializer_range
124
+ self.layer_norm_eps = layer_norm_eps
125
+ self.position_embedding_type = position_embedding_type
126
+ self.classifier_dropout = classifier_dropout
127
+ self.channel_shrink_ratio = channel_shrink_ratio
128
+ self.max_2d_position_embeddings = max_2d_position_embeddings
129
+
130
+
131
+ __all__ = ["LiltConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/lilt/modeling_lilt.py ADDED
@@ -0,0 +1,1093 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch LiLT model."""
16
+
17
+ import math
18
+ from typing import Optional, Union
19
+
20
+ import torch
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
24
+
25
+ from ...activations import ACT2FN
26
+ from ...modeling_layers import GradientCheckpointingLayer
27
+ from ...modeling_outputs import (
28
+ BaseModelOutput,
29
+ BaseModelOutputWithPooling,
30
+ QuestionAnsweringModelOutput,
31
+ SequenceClassifierOutput,
32
+ TokenClassifierOutput,
33
+ )
34
+ from ...modeling_utils import PreTrainedModel
35
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
36
+ from ...utils import auto_docstring, logging
37
+ from .configuration_lilt import LiltConfig
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ class LiltTextEmbeddings(nn.Module):
44
+ def __init__(self, config):
45
+ super().__init__()
46
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
47
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
48
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
49
+
50
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
51
+ # any TensorFlow checkpoint file
52
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
53
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
54
+
55
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
56
+ self.register_buffer(
57
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
58
+ )
59
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
60
+
61
+ # End copy
62
+ self.padding_idx = config.pad_token_id
63
+ self.position_embeddings = nn.Embedding(
64
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
65
+ )
66
+
67
+ def forward(
68
+ self,
69
+ input_ids=None,
70
+ token_type_ids=None,
71
+ position_ids=None,
72
+ inputs_embeds=None,
73
+ ):
74
+ if position_ids is None:
75
+ if input_ids is not None:
76
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
77
+ position_ids = self.create_position_ids_from_input_ids(input_ids, self.padding_idx).to(
78
+ input_ids.device
79
+ )
80
+ else:
81
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
82
+
83
+ if input_ids is not None:
84
+ input_shape = input_ids.size()
85
+ else:
86
+ input_shape = inputs_embeds.size()[:-1]
87
+
88
+ if token_type_ids is None:
89
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
90
+
91
+ if inputs_embeds is None:
92
+ inputs_embeds = self.word_embeddings(input_ids)
93
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
94
+
95
+ embeddings = inputs_embeds + token_type_embeddings
96
+ if self.position_embedding_type == "absolute":
97
+ position_embeddings = self.position_embeddings(position_ids)
98
+ embeddings += position_embeddings
99
+ embeddings = self.LayerNorm(embeddings)
100
+ embeddings = self.dropout(embeddings)
101
+ return embeddings, position_ids
102
+
103
+ def create_position_ids_from_input_ids(self, input_ids, padding_idx):
104
+ """
105
+ Args:
106
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
107
+ symbols are ignored. This is modified from fairseq's `utils.make_positions`.
108
+ x: torch.Tensor x:
109
+ Returns: torch.Tensor
110
+ """
111
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
112
+ mask = input_ids.ne(padding_idx).int()
113
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask)) * mask
114
+ return incremental_indices.long() + padding_idx
115
+
116
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
117
+ """
118
+ Args:
119
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.:
120
+ inputs_embeds: torch.Tensor
121
+ Returns: torch.Tensor
122
+ """
123
+ input_shape = inputs_embeds.size()[:-1]
124
+ sequence_length = input_shape[1]
125
+
126
+ position_ids = torch.arange(
127
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
128
+ )
129
+ return position_ids.unsqueeze(0).expand(input_shape)
130
+
131
+
132
+ class LiltLayoutEmbeddings(nn.Module):
133
+ def __init__(self, config):
134
+ super().__init__()
135
+ # we divide the hidden_size by 6 here as there are 6 different layout embeddings,
136
+ # namely left_position, upper_position, right_position, lower_position, height, width
137
+ self.x_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.hidden_size // 6)
138
+ self.y_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.hidden_size // 6)
139
+ self.h_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.hidden_size // 6)
140
+ self.w_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.hidden_size // 6)
141
+
142
+ self.padding_idx = config.pad_token_id
143
+ self.box_position_embeddings = nn.Embedding(
144
+ config.max_position_embeddings,
145
+ config.hidden_size // config.channel_shrink_ratio,
146
+ padding_idx=self.padding_idx,
147
+ )
148
+ self.box_linear_embeddings = nn.Linear(
149
+ in_features=config.hidden_size, out_features=config.hidden_size // config.channel_shrink_ratio
150
+ )
151
+ self.LayerNorm = nn.LayerNorm(config.hidden_size // config.channel_shrink_ratio, eps=config.layer_norm_eps)
152
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
153
+
154
+ def forward(self, bbox=None, position_ids=None):
155
+ try:
156
+ left_position_embeddings = self.x_position_embeddings(bbox[:, :, 0])
157
+ upper_position_embeddings = self.y_position_embeddings(bbox[:, :, 1])
158
+ right_position_embeddings = self.x_position_embeddings(bbox[:, :, 2])
159
+ lower_position_embeddings = self.y_position_embeddings(bbox[:, :, 3])
160
+ except IndexError as e:
161
+ raise IndexError("The `bbox` coordinate values should be within 0-1000 range.") from e
162
+
163
+ h_position_embeddings = self.h_position_embeddings(bbox[:, :, 3] - bbox[:, :, 1])
164
+ w_position_embeddings = self.w_position_embeddings(bbox[:, :, 2] - bbox[:, :, 0])
165
+
166
+ spatial_position_embeddings = torch.cat(
167
+ [
168
+ left_position_embeddings,
169
+ upper_position_embeddings,
170
+ right_position_embeddings,
171
+ lower_position_embeddings,
172
+ h_position_embeddings,
173
+ w_position_embeddings,
174
+ ],
175
+ dim=-1,
176
+ )
177
+ spatial_position_embeddings = self.box_linear_embeddings(spatial_position_embeddings)
178
+ box_position_embeddings = self.box_position_embeddings(position_ids)
179
+
180
+ spatial_position_embeddings = spatial_position_embeddings + box_position_embeddings
181
+
182
+ spatial_position_embeddings = self.LayerNorm(spatial_position_embeddings)
183
+ spatial_position_embeddings = self.dropout(spatial_position_embeddings)
184
+
185
+ return spatial_position_embeddings
186
+
187
+
188
+ class LiltSelfAttention(nn.Module):
189
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
190
+ super().__init__()
191
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
192
+ raise ValueError(
193
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
194
+ f"heads ({config.num_attention_heads})"
195
+ )
196
+
197
+ self.num_attention_heads = config.num_attention_heads
198
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
199
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
200
+
201
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
202
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
203
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
204
+
205
+ self.layout_query = nn.Linear(
206
+ config.hidden_size // config.channel_shrink_ratio, self.all_head_size // config.channel_shrink_ratio
207
+ )
208
+ self.layout_key = nn.Linear(
209
+ config.hidden_size // config.channel_shrink_ratio, self.all_head_size // config.channel_shrink_ratio
210
+ )
211
+ self.layout_value = nn.Linear(
212
+ config.hidden_size // config.channel_shrink_ratio, self.all_head_size // config.channel_shrink_ratio
213
+ )
214
+
215
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
216
+ self.position_embedding_type = position_embedding_type or getattr(
217
+ config, "position_embedding_type", "absolute"
218
+ )
219
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
220
+ self.max_position_embeddings = config.max_position_embeddings
221
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
222
+
223
+ self.channel_shrink_ratio = config.channel_shrink_ratio
224
+ self.layer_idx = layer_idx
225
+
226
+ def transpose_for_scores(self, x, r=1):
227
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size // r)
228
+ x = x.view(*new_x_shape)
229
+ return x.permute(0, 2, 1, 3)
230
+
231
+ def forward(
232
+ self,
233
+ hidden_states,
234
+ layout_inputs,
235
+ attention_mask=None,
236
+ head_mask=None,
237
+ output_attentions=False,
238
+ ):
239
+ layout_value_layer = self.transpose_for_scores(self.layout_value(layout_inputs), r=self.channel_shrink_ratio)
240
+ layout_key_layer = self.transpose_for_scores(self.layout_key(layout_inputs), r=self.channel_shrink_ratio)
241
+ layout_query_layer = self.transpose_for_scores(self.layout_query(layout_inputs), r=self.channel_shrink_ratio)
242
+
243
+ mixed_query_layer = self.query(hidden_states)
244
+
245
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
246
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
247
+ query_layer = self.transpose_for_scores(mixed_query_layer)
248
+
249
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
250
+ layout_attention_scores = torch.matmul(layout_query_layer, layout_key_layer.transpose(-1, -2))
251
+
252
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
253
+ seq_length = hidden_states.size()[1]
254
+ position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
255
+ position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
256
+ distance = position_ids_l - position_ids_r
257
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
258
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
259
+
260
+ if self.position_embedding_type == "relative_key":
261
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
262
+ attention_scores = attention_scores + relative_position_scores
263
+ elif self.position_embedding_type == "relative_key_query":
264
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
265
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
266
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
267
+
268
+ tmp_attention_scores = attention_scores / math.sqrt(self.attention_head_size)
269
+ tmp_layout_attention_scores = layout_attention_scores / math.sqrt(
270
+ self.attention_head_size // self.channel_shrink_ratio
271
+ )
272
+ attention_scores = tmp_attention_scores + tmp_layout_attention_scores
273
+ layout_attention_scores = tmp_layout_attention_scores + tmp_attention_scores
274
+
275
+ if attention_mask is not None:
276
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
277
+ layout_attention_scores = layout_attention_scores + attention_mask
278
+
279
+ # Normalize the attention scores to probabilities.
280
+ layout_attention_probs = nn.Softmax(dim=-1)(layout_attention_scores)
281
+
282
+ # This is actually dropping out entire tokens to attend to, which might
283
+ # seem a bit unusual, but is taken from the original Transformer paper.
284
+ layout_attention_probs = self.dropout(layout_attention_probs)
285
+
286
+ # Mask heads if we want to
287
+ if head_mask is not None:
288
+ layout_attention_probs = layout_attention_probs * head_mask
289
+
290
+ layout_context_layer = torch.matmul(layout_attention_probs, layout_value_layer)
291
+
292
+ layout_context_layer = layout_context_layer.permute(0, 2, 1, 3).contiguous()
293
+ new_context_layer_shape = layout_context_layer.size()[:-2] + (self.all_head_size // self.channel_shrink_ratio,)
294
+ layout_context_layer = layout_context_layer.view(*new_context_layer_shape)
295
+
296
+ if attention_mask is not None:
297
+ # Apply the attention mask is (precomputed for all layers in RobertaModel forward() function)
298
+ attention_scores = attention_scores + attention_mask
299
+
300
+ # Normalize the attention scores to probabilities.
301
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
302
+
303
+ # This is actually dropping out entire tokens to attend to, which might
304
+ # seem a bit unusual, but is taken from the original Transformer paper.
305
+ attention_probs = self.dropout(attention_probs)
306
+
307
+ # Mask heads if we want to
308
+ if head_mask is not None:
309
+ attention_probs = attention_probs * head_mask
310
+
311
+ context_layer = torch.matmul(attention_probs, value_layer)
312
+
313
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
314
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
315
+ context_layer = context_layer.view(*new_context_layer_shape)
316
+
317
+ outputs = (
318
+ ((context_layer, layout_context_layer), attention_probs)
319
+ if output_attentions
320
+ else ((context_layer, layout_context_layer),)
321
+ )
322
+
323
+ return outputs
324
+
325
+
326
+ # Copied from transformers.models.bert.modeling_bert.BertSelfOutput
327
+ class LiltSelfOutput(nn.Module):
328
+ def __init__(self, config):
329
+ super().__init__()
330
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
331
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
332
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
333
+
334
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
335
+ hidden_states = self.dense(hidden_states)
336
+ hidden_states = self.dropout(hidden_states)
337
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
338
+ return hidden_states
339
+
340
+
341
+ class LiltAttention(nn.Module):
342
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
343
+ super().__init__()
344
+ self.self = LiltSelfAttention(config, position_embedding_type=position_embedding_type, layer_idx=layer_idx)
345
+ self.output = LiltSelfOutput(config)
346
+ self.pruned_heads = set()
347
+
348
+ ori_hidden_size = config.hidden_size
349
+ config.hidden_size = config.hidden_size // config.channel_shrink_ratio
350
+ self.layout_output = LiltSelfOutput(config)
351
+ config.hidden_size = ori_hidden_size
352
+
353
+ # Copied from transformers.models.bert.modeling_bert.BertAttention.prune_heads
354
+ def prune_heads(self, heads):
355
+ if len(heads) == 0:
356
+ return
357
+ heads, index = find_pruneable_heads_and_indices(
358
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
359
+ )
360
+
361
+ # Prune linear layers
362
+ self.self.query = prune_linear_layer(self.self.query, index)
363
+ self.self.key = prune_linear_layer(self.self.key, index)
364
+ self.self.value = prune_linear_layer(self.self.value, index)
365
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
366
+
367
+ # Update hyper params and store pruned heads
368
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
369
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
370
+ self.pruned_heads = self.pruned_heads.union(heads)
371
+
372
+ def forward(
373
+ self,
374
+ hidden_states: torch.Tensor,
375
+ layout_inputs: torch.Tensor,
376
+ attention_mask: Optional[torch.FloatTensor] = None,
377
+ head_mask: Optional[torch.FloatTensor] = None,
378
+ output_attentions: Optional[bool] = False,
379
+ ) -> tuple[torch.Tensor]:
380
+ self_outputs = self.self(
381
+ hidden_states,
382
+ layout_inputs,
383
+ attention_mask,
384
+ head_mask,
385
+ output_attentions,
386
+ )
387
+ attention_output = self.output(self_outputs[0][0], hidden_states)
388
+ layout_attention_output = self.layout_output(self_outputs[0][1], layout_inputs)
389
+ outputs = ((attention_output, layout_attention_output),) + self_outputs[1:] # add attentions if we output them
390
+ return outputs
391
+
392
+
393
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate
394
+ class LiltIntermediate(nn.Module):
395
+ def __init__(self, config):
396
+ super().__init__()
397
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
398
+ if isinstance(config.hidden_act, str):
399
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
400
+ else:
401
+ self.intermediate_act_fn = config.hidden_act
402
+
403
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
404
+ hidden_states = self.dense(hidden_states)
405
+ hidden_states = self.intermediate_act_fn(hidden_states)
406
+ return hidden_states
407
+
408
+
409
+ # Copied from transformers.models.bert.modeling_bert.BertOutput
410
+ class LiltOutput(nn.Module):
411
+ def __init__(self, config):
412
+ super().__init__()
413
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
414
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
415
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
416
+
417
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
418
+ hidden_states = self.dense(hidden_states)
419
+ hidden_states = self.dropout(hidden_states)
420
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
421
+ return hidden_states
422
+
423
+
424
+ class LiltLayer(GradientCheckpointingLayer):
425
+ def __init__(self, config, layer_idx=None):
426
+ super().__init__()
427
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
428
+ self.seq_len_dim = 1
429
+ self.attention = LiltAttention(config, layer_idx=layer_idx)
430
+ self.intermediate = LiltIntermediate(config)
431
+ self.output = LiltOutput(config)
432
+
433
+ ori_hidden_size = config.hidden_size
434
+ ori_intermediate_size = config.intermediate_size
435
+ config.hidden_size = config.hidden_size // config.channel_shrink_ratio
436
+ config.intermediate_size = config.intermediate_size // config.channel_shrink_ratio
437
+ self.layout_intermediate = LiltIntermediate(config)
438
+ self.layout_output = LiltOutput(config)
439
+ config.hidden_size = ori_hidden_size
440
+ config.intermediate_size = ori_intermediate_size
441
+
442
+ def forward(
443
+ self,
444
+ hidden_states: torch.Tensor,
445
+ layout_inputs: torch.Tensor,
446
+ attention_mask: Optional[torch.FloatTensor] = None,
447
+ head_mask: Optional[torch.FloatTensor] = None,
448
+ output_attentions: Optional[bool] = False,
449
+ ) -> tuple[torch.Tensor]:
450
+ self_attention_outputs = self.attention(
451
+ hidden_states,
452
+ layout_inputs,
453
+ attention_mask,
454
+ head_mask,
455
+ output_attentions=output_attentions,
456
+ )
457
+ attention_output = self_attention_outputs[0][0]
458
+ layout_attention_output = self_attention_outputs[0][1]
459
+
460
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
461
+
462
+ layer_output = apply_chunking_to_forward(
463
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
464
+ )
465
+ layout_layer_output = apply_chunking_to_forward(
466
+ self.layout_feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, layout_attention_output
467
+ )
468
+ outputs = ((layer_output, layout_layer_output),) + outputs
469
+
470
+ return outputs
471
+
472
+ # Copied from transformers.models.bert.modeling_bert.BertLayer.feed_forward_chunk
473
+ def feed_forward_chunk(self, attention_output):
474
+ intermediate_output = self.intermediate(attention_output)
475
+ layer_output = self.output(intermediate_output, attention_output)
476
+ return layer_output
477
+
478
+ def layout_feed_forward_chunk(self, attention_output):
479
+ intermediate_output = self.layout_intermediate(attention_output)
480
+ layer_output = self.layout_output(intermediate_output, attention_output)
481
+ return layer_output
482
+
483
+
484
+ class LiltEncoder(nn.Module):
485
+ # Copied from transformers.models.bert.modeling_bert.BertEncoder.__init__ with Bert->Lilt
486
+ def __init__(self, config, layer_idx=None):
487
+ super().__init__()
488
+ self.config = config
489
+ self.layer = nn.ModuleList([LiltLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
490
+ self.gradient_checkpointing = False
491
+
492
+ def forward(
493
+ self,
494
+ hidden_states: torch.Tensor,
495
+ layout_inputs: torch.Tensor,
496
+ attention_mask: Optional[torch.FloatTensor] = None,
497
+ head_mask: Optional[torch.FloatTensor] = None,
498
+ output_attentions: Optional[bool] = False,
499
+ output_hidden_states: Optional[bool] = False,
500
+ return_dict: Optional[bool] = True,
501
+ ) -> Union[tuple[torch.Tensor], BaseModelOutput]:
502
+ all_hidden_states = () if output_hidden_states else None
503
+ all_self_attentions = () if output_attentions else None
504
+
505
+ for i, layer_module in enumerate(self.layer):
506
+ if output_hidden_states:
507
+ all_hidden_states = all_hidden_states + (hidden_states,)
508
+
509
+ layer_head_mask = head_mask[i] if head_mask is not None else None
510
+
511
+ layer_outputs = layer_module(
512
+ hidden_states,
513
+ layout_inputs,
514
+ attention_mask,
515
+ layer_head_mask,
516
+ output_attentions,
517
+ )
518
+
519
+ hidden_states = layer_outputs[0][0]
520
+ layout_inputs = layer_outputs[0][1]
521
+
522
+ if output_attentions:
523
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
524
+
525
+ if output_hidden_states:
526
+ all_hidden_states = all_hidden_states + (hidden_states,)
527
+
528
+ if not return_dict:
529
+ return tuple(
530
+ v
531
+ for v in [
532
+ hidden_states,
533
+ all_hidden_states,
534
+ all_self_attentions,
535
+ ]
536
+ if v is not None
537
+ )
538
+ return BaseModelOutput(
539
+ last_hidden_state=hidden_states,
540
+ hidden_states=all_hidden_states,
541
+ attentions=all_self_attentions,
542
+ )
543
+
544
+
545
+ # Copied from transformers.models.bert.modeling_bert.BertPooler
546
+ class LiltPooler(nn.Module):
547
+ def __init__(self, config):
548
+ super().__init__()
549
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
550
+ self.activation = nn.Tanh()
551
+
552
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
553
+ # We "pool" the model by simply taking the hidden state corresponding
554
+ # to the first token.
555
+ first_token_tensor = hidden_states[:, 0]
556
+ pooled_output = self.dense(first_token_tensor)
557
+ pooled_output = self.activation(pooled_output)
558
+ return pooled_output
559
+
560
+
561
+ @auto_docstring
562
+ class LiltPreTrainedModel(PreTrainedModel):
563
+ config: LiltConfig
564
+ base_model_prefix = "lilt"
565
+ supports_gradient_checkpointing = True
566
+ _no_split_modules = []
567
+
568
+ def _init_weights(self, module):
569
+ """Initialize the weights"""
570
+ if isinstance(module, nn.Linear):
571
+ # Slightly different from the TF version which uses truncated_normal for initialization
572
+ # cf https://github.com/pytorch/pytorch/pull/5617
573
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
574
+ if module.bias is not None:
575
+ module.bias.data.zero_()
576
+ elif isinstance(module, nn.Embedding):
577
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
578
+ if module.padding_idx is not None:
579
+ module.weight.data[module.padding_idx].zero_()
580
+ elif isinstance(module, nn.LayerNorm):
581
+ module.bias.data.zero_()
582
+ module.weight.data.fill_(1.0)
583
+
584
+
585
+ @auto_docstring
586
+ class LiltModel(LiltPreTrainedModel):
587
+ def __init__(self, config, add_pooling_layer=True):
588
+ r"""
589
+ add_pooling_layer (bool, *optional*, defaults to `True`):
590
+ Whether to add a pooling layer
591
+ """
592
+ super().__init__(config)
593
+ self.config = config
594
+
595
+ self.embeddings = LiltTextEmbeddings(config)
596
+ self.layout_embeddings = LiltLayoutEmbeddings(config)
597
+ self.encoder = LiltEncoder(config)
598
+
599
+ self.pooler = LiltPooler(config) if add_pooling_layer else None
600
+
601
+ # Initialize weights and apply final processing
602
+ self.post_init()
603
+
604
+ def get_input_embeddings(self):
605
+ return self.embeddings.word_embeddings
606
+
607
+ def set_input_embeddings(self, value):
608
+ self.embeddings.word_embeddings = value
609
+
610
+ def _prune_heads(self, heads_to_prune):
611
+ """
612
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
613
+ class PreTrainedModel
614
+ """
615
+ for layer, heads in heads_to_prune.items():
616
+ self.encoder.layer[layer].attention.prune_heads(heads)
617
+
618
+ @auto_docstring
619
+ def forward(
620
+ self,
621
+ input_ids: Optional[torch.Tensor] = None,
622
+ bbox: Optional[torch.Tensor] = None,
623
+ attention_mask: Optional[torch.Tensor] = None,
624
+ token_type_ids: Optional[torch.Tensor] = None,
625
+ position_ids: Optional[torch.Tensor] = None,
626
+ head_mask: Optional[torch.Tensor] = None,
627
+ inputs_embeds: Optional[torch.Tensor] = None,
628
+ output_attentions: Optional[bool] = None,
629
+ output_hidden_states: Optional[bool] = None,
630
+ return_dict: Optional[bool] = None,
631
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPooling]:
632
+ r"""
633
+ bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*):
634
+ Bounding boxes of each input sequence tokens. Selected in the range `[0,
635
+ config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
636
+ format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
637
+ y1) represents the position of the lower right corner. See [Overview](#Overview) for normalization.
638
+
639
+ Examples:
640
+
641
+ ```python
642
+ >>> from transformers import AutoTokenizer, AutoModel
643
+ >>> from datasets import load_dataset
644
+
645
+ >>> tokenizer = AutoTokenizer.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")
646
+ >>> model = AutoModel.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")
647
+
648
+ >>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train")
649
+ >>> example = dataset[0]
650
+ >>> words = example["tokens"]
651
+ >>> boxes = example["bboxes"]
652
+
653
+ >>> encoding = tokenizer(words, boxes=boxes, return_tensors="pt")
654
+
655
+ >>> outputs = model(**encoding)
656
+ >>> last_hidden_states = outputs.last_hidden_state
657
+ ```"""
658
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
659
+ output_hidden_states = (
660
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
661
+ )
662
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
663
+
664
+ if input_ids is not None and inputs_embeds is not None:
665
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
666
+ elif input_ids is not None:
667
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
668
+ input_shape = input_ids.size()
669
+ elif inputs_embeds is not None:
670
+ input_shape = inputs_embeds.size()[:-1]
671
+ else:
672
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
673
+
674
+ batch_size, seq_length = input_shape
675
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
676
+
677
+ if bbox is None:
678
+ bbox = torch.zeros(input_shape + (4,), dtype=torch.long, device=device)
679
+
680
+ if attention_mask is None:
681
+ attention_mask = torch.ones(((batch_size, seq_length)), device=device)
682
+
683
+ if token_type_ids is None:
684
+ if hasattr(self.embeddings, "token_type_ids"):
685
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
686
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
687
+ token_type_ids = buffered_token_type_ids_expanded
688
+ else:
689
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
690
+
691
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
692
+ # ourselves in which case we just need to make it broadcastable to all heads.
693
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
694
+
695
+ # Prepare head mask if needed
696
+ # 1.0 in head_mask indicate we keep the head
697
+ # attention_probs has shape bsz x n_heads x N x N
698
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
699
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
700
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
701
+
702
+ embedding_output, position_ids = self.embeddings(
703
+ input_ids=input_ids,
704
+ position_ids=position_ids,
705
+ token_type_ids=token_type_ids,
706
+ inputs_embeds=inputs_embeds,
707
+ )
708
+
709
+ layout_embedding_output = self.layout_embeddings(bbox=bbox, position_ids=position_ids)
710
+
711
+ encoder_outputs = self.encoder(
712
+ embedding_output,
713
+ layout_embedding_output,
714
+ attention_mask=extended_attention_mask,
715
+ head_mask=head_mask,
716
+ output_attentions=output_attentions,
717
+ output_hidden_states=output_hidden_states,
718
+ return_dict=return_dict,
719
+ )
720
+ sequence_output = encoder_outputs[0]
721
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
722
+
723
+ if not return_dict:
724
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
725
+
726
+ return BaseModelOutputWithPooling(
727
+ last_hidden_state=sequence_output,
728
+ pooler_output=pooled_output,
729
+ hidden_states=encoder_outputs.hidden_states,
730
+ attentions=encoder_outputs.attentions,
731
+ )
732
+
733
+
734
+ @auto_docstring(
735
+ custom_intro="""
736
+ LiLT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
737
+ output) e.g. for GLUE tasks.
738
+ """
739
+ )
740
+ class LiltForSequenceClassification(LiltPreTrainedModel):
741
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForSequenceClassification.__init__ with Roberta->Lilt, roberta->lilt
742
+ def __init__(self, config):
743
+ super().__init__(config)
744
+ self.num_labels = config.num_labels
745
+ self.config = config
746
+
747
+ self.lilt = LiltModel(config, add_pooling_layer=False)
748
+ self.classifier = LiltClassificationHead(config)
749
+
750
+ # Initialize weights and apply final processing
751
+ self.post_init()
752
+
753
+ @auto_docstring
754
+ def forward(
755
+ self,
756
+ input_ids: Optional[torch.LongTensor] = None,
757
+ bbox: Optional[torch.Tensor] = None,
758
+ attention_mask: Optional[torch.FloatTensor] = None,
759
+ token_type_ids: Optional[torch.LongTensor] = None,
760
+ position_ids: Optional[torch.LongTensor] = None,
761
+ head_mask: Optional[torch.FloatTensor] = None,
762
+ inputs_embeds: Optional[torch.FloatTensor] = None,
763
+ labels: Optional[torch.LongTensor] = None,
764
+ output_attentions: Optional[bool] = None,
765
+ output_hidden_states: Optional[bool] = None,
766
+ return_dict: Optional[bool] = None,
767
+ ) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
768
+ r"""
769
+ bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*):
770
+ Bounding boxes of each input sequence tokens. Selected in the range `[0,
771
+ config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
772
+ format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
773
+ y1) represents the position of the lower right corner. See [Overview](#Overview) for normalization.
774
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
775
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
776
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
777
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
778
+
779
+ Examples:
780
+
781
+ ```python
782
+ >>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
783
+ >>> from datasets import load_dataset
784
+
785
+ >>> tokenizer = AutoTokenizer.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")
786
+ >>> model = AutoModelForSequenceClassification.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")
787
+
788
+ >>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train")
789
+ >>> example = dataset[0]
790
+ >>> words = example["tokens"]
791
+ >>> boxes = example["bboxes"]
792
+
793
+ >>> encoding = tokenizer(words, boxes=boxes, return_tensors="pt")
794
+
795
+ >>> outputs = model(**encoding)
796
+ >>> predicted_class_idx = outputs.logits.argmax(-1).item()
797
+ >>> predicted_class = model.config.id2label[predicted_class_idx]
798
+ ```"""
799
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
800
+
801
+ outputs = self.lilt(
802
+ input_ids,
803
+ bbox=bbox,
804
+ attention_mask=attention_mask,
805
+ token_type_ids=token_type_ids,
806
+ position_ids=position_ids,
807
+ head_mask=head_mask,
808
+ inputs_embeds=inputs_embeds,
809
+ output_attentions=output_attentions,
810
+ output_hidden_states=output_hidden_states,
811
+ return_dict=return_dict,
812
+ )
813
+ sequence_output = outputs[0]
814
+ logits = self.classifier(sequence_output)
815
+
816
+ loss = None
817
+ if labels is not None:
818
+ # move labels to correct device to enable model parallelism
819
+ labels = labels.to(logits.device)
820
+ if self.config.problem_type is None:
821
+ if self.num_labels == 1:
822
+ self.config.problem_type = "regression"
823
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
824
+ self.config.problem_type = "single_label_classification"
825
+ else:
826
+ self.config.problem_type = "multi_label_classification"
827
+
828
+ if self.config.problem_type == "regression":
829
+ loss_fct = MSELoss()
830
+ if self.num_labels == 1:
831
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
832
+ else:
833
+ loss = loss_fct(logits, labels)
834
+ elif self.config.problem_type == "single_label_classification":
835
+ loss_fct = CrossEntropyLoss()
836
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
837
+ elif self.config.problem_type == "multi_label_classification":
838
+ loss_fct = BCEWithLogitsLoss()
839
+ loss = loss_fct(logits, labels)
840
+
841
+ if not return_dict:
842
+ output = (logits,) + outputs[2:]
843
+ return ((loss,) + output) if loss is not None else output
844
+
845
+ return SequenceClassifierOutput(
846
+ loss=loss,
847
+ logits=logits,
848
+ hidden_states=outputs.hidden_states,
849
+ attentions=outputs.attentions,
850
+ )
851
+
852
+
853
+ @auto_docstring
854
+ class LiltForTokenClassification(LiltPreTrainedModel):
855
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForTokenClassification.__init__ with Roberta->Lilt, roberta->lilt
856
+ def __init__(self, config):
857
+ super().__init__(config)
858
+ self.num_labels = config.num_labels
859
+
860
+ self.lilt = LiltModel(config, add_pooling_layer=False)
861
+ classifier_dropout = (
862
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
863
+ )
864
+ self.dropout = nn.Dropout(classifier_dropout)
865
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
866
+
867
+ # Initialize weights and apply final processing
868
+ self.post_init()
869
+
870
+ @auto_docstring
871
+ def forward(
872
+ self,
873
+ input_ids: Optional[torch.LongTensor] = None,
874
+ bbox: Optional[torch.LongTensor] = None,
875
+ attention_mask: Optional[torch.FloatTensor] = None,
876
+ token_type_ids: Optional[torch.LongTensor] = None,
877
+ position_ids: Optional[torch.LongTensor] = None,
878
+ head_mask: Optional[torch.FloatTensor] = None,
879
+ inputs_embeds: Optional[torch.FloatTensor] = None,
880
+ labels: Optional[torch.LongTensor] = None,
881
+ output_attentions: Optional[bool] = None,
882
+ output_hidden_states: Optional[bool] = None,
883
+ return_dict: Optional[bool] = None,
884
+ ) -> Union[tuple[torch.Tensor], TokenClassifierOutput]:
885
+ r"""
886
+ bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*):
887
+ Bounding boxes of each input sequence tokens. Selected in the range `[0,
888
+ config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
889
+ format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
890
+ y1) represents the position of the lower right corner. See [Overview](#Overview) for normalization.
891
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
892
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
893
+
894
+ Examples:
895
+
896
+ ```python
897
+ >>> from transformers import AutoTokenizer, AutoModelForTokenClassification
898
+ >>> from datasets import load_dataset
899
+
900
+ >>> tokenizer = AutoTokenizer.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")
901
+ >>> model = AutoModelForTokenClassification.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")
902
+
903
+ >>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train")
904
+ >>> example = dataset[0]
905
+ >>> words = example["tokens"]
906
+ >>> boxes = example["bboxes"]
907
+
908
+ >>> encoding = tokenizer(words, boxes=boxes, return_tensors="pt")
909
+
910
+ >>> outputs = model(**encoding)
911
+ >>> predicted_class_indices = outputs.logits.argmax(-1)
912
+ ```"""
913
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
914
+
915
+ outputs = self.lilt(
916
+ input_ids,
917
+ bbox=bbox,
918
+ attention_mask=attention_mask,
919
+ token_type_ids=token_type_ids,
920
+ position_ids=position_ids,
921
+ head_mask=head_mask,
922
+ inputs_embeds=inputs_embeds,
923
+ output_attentions=output_attentions,
924
+ output_hidden_states=output_hidden_states,
925
+ return_dict=return_dict,
926
+ )
927
+
928
+ sequence_output = outputs[0]
929
+
930
+ sequence_output = self.dropout(sequence_output)
931
+ logits = self.classifier(sequence_output)
932
+
933
+ loss = None
934
+ if labels is not None:
935
+ # move labels to correct device to enable model parallelism
936
+ labels = labels.to(logits.device)
937
+ loss_fct = CrossEntropyLoss()
938
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
939
+
940
+ if not return_dict:
941
+ output = (logits,) + outputs[2:]
942
+ return ((loss,) + output) if loss is not None else output
943
+
944
+ return TokenClassifierOutput(
945
+ loss=loss,
946
+ logits=logits,
947
+ hidden_states=outputs.hidden_states,
948
+ attentions=outputs.attentions,
949
+ )
950
+
951
+
952
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaClassificationHead with Roberta->Lilt
953
+ class LiltClassificationHead(nn.Module):
954
+ """Head for sentence-level classification tasks."""
955
+
956
+ def __init__(self, config):
957
+ super().__init__()
958
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
959
+ classifier_dropout = (
960
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
961
+ )
962
+ self.dropout = nn.Dropout(classifier_dropout)
963
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
964
+
965
+ def forward(self, features, **kwargs):
966
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
967
+ x = self.dropout(x)
968
+ x = self.dense(x)
969
+ x = torch.tanh(x)
970
+ x = self.dropout(x)
971
+ x = self.out_proj(x)
972
+ return x
973
+
974
+
975
+ @auto_docstring
976
+ class LiltForQuestionAnswering(LiltPreTrainedModel):
977
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForQuestionAnswering.__init__ with Roberta->Lilt, roberta->lilt
978
+ def __init__(self, config):
979
+ super().__init__(config)
980
+ self.num_labels = config.num_labels
981
+
982
+ self.lilt = LiltModel(config, add_pooling_layer=False)
983
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
984
+
985
+ # Initialize weights and apply final processing
986
+ self.post_init()
987
+
988
+ @auto_docstring
989
+ def forward(
990
+ self,
991
+ input_ids: Optional[torch.LongTensor] = None,
992
+ bbox: Optional[torch.LongTensor] = None,
993
+ attention_mask: Optional[torch.FloatTensor] = None,
994
+ token_type_ids: Optional[torch.LongTensor] = None,
995
+ position_ids: Optional[torch.LongTensor] = None,
996
+ head_mask: Optional[torch.FloatTensor] = None,
997
+ inputs_embeds: Optional[torch.FloatTensor] = None,
998
+ start_positions: Optional[torch.LongTensor] = None,
999
+ end_positions: Optional[torch.LongTensor] = None,
1000
+ output_attentions: Optional[bool] = None,
1001
+ output_hidden_states: Optional[bool] = None,
1002
+ return_dict: Optional[bool] = None,
1003
+ ) -> Union[tuple[torch.Tensor], QuestionAnsweringModelOutput]:
1004
+ r"""
1005
+ bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*):
1006
+ Bounding boxes of each input sequence tokens. Selected in the range `[0,
1007
+ config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
1008
+ format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
1009
+ y1) represents the position of the lower right corner. See [Overview](#Overview) for normalization.
1010
+
1011
+ Examples:
1012
+
1013
+ ```python
1014
+ >>> from transformers import AutoTokenizer, AutoModelForQuestionAnswering
1015
+ >>> from datasets import load_dataset
1016
+
1017
+ >>> tokenizer = AutoTokenizer.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")
1018
+ >>> model = AutoModelForQuestionAnswering.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")
1019
+
1020
+ >>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train")
1021
+ >>> example = dataset[0]
1022
+ >>> words = example["tokens"]
1023
+ >>> boxes = example["bboxes"]
1024
+
1025
+ >>> encoding = tokenizer(words, boxes=boxes, return_tensors="pt")
1026
+
1027
+ >>> outputs = model(**encoding)
1028
+
1029
+ >>> answer_start_index = outputs.start_logits.argmax()
1030
+ >>> answer_end_index = outputs.end_logits.argmax()
1031
+
1032
+ >>> predict_answer_tokens = encoding.input_ids[0, answer_start_index : answer_end_index + 1]
1033
+ >>> predicted_answer = tokenizer.decode(predict_answer_tokens)
1034
+ ```"""
1035
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1036
+
1037
+ outputs = self.lilt(
1038
+ input_ids,
1039
+ bbox=bbox,
1040
+ attention_mask=attention_mask,
1041
+ token_type_ids=token_type_ids,
1042
+ position_ids=position_ids,
1043
+ head_mask=head_mask,
1044
+ inputs_embeds=inputs_embeds,
1045
+ output_attentions=output_attentions,
1046
+ output_hidden_states=output_hidden_states,
1047
+ return_dict=return_dict,
1048
+ )
1049
+
1050
+ sequence_output = outputs[0]
1051
+
1052
+ logits = self.qa_outputs(sequence_output)
1053
+ start_logits, end_logits = logits.split(1, dim=-1)
1054
+ start_logits = start_logits.squeeze(-1).contiguous()
1055
+ end_logits = end_logits.squeeze(-1).contiguous()
1056
+
1057
+ total_loss = None
1058
+ if start_positions is not None and end_positions is not None:
1059
+ # If we are on multi-GPU, split add a dimension
1060
+ if len(start_positions.size()) > 1:
1061
+ start_positions = start_positions.squeeze(-1)
1062
+ if len(end_positions.size()) > 1:
1063
+ end_positions = end_positions.squeeze(-1)
1064
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1065
+ ignored_index = start_logits.size(1)
1066
+ start_positions = start_positions.clamp(0, ignored_index)
1067
+ end_positions = end_positions.clamp(0, ignored_index)
1068
+
1069
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1070
+ start_loss = loss_fct(start_logits, start_positions)
1071
+ end_loss = loss_fct(end_logits, end_positions)
1072
+ total_loss = (start_loss + end_loss) / 2
1073
+
1074
+ if not return_dict:
1075
+ output = (start_logits, end_logits) + outputs[2:]
1076
+ return ((total_loss,) + output) if total_loss is not None else output
1077
+
1078
+ return QuestionAnsweringModelOutput(
1079
+ loss=total_loss,
1080
+ start_logits=start_logits,
1081
+ end_logits=end_logits,
1082
+ hidden_states=outputs.hidden_states,
1083
+ attentions=outputs.attentions,
1084
+ )
1085
+
1086
+
1087
+ __all__ = [
1088
+ "LiltForQuestionAnswering",
1089
+ "LiltForSequenceClassification",
1090
+ "LiltForTokenClassification",
1091
+ "LiltModel",
1092
+ "LiltPreTrainedModel",
1093
+ ]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama/__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_llama import *
22
+ from .modeling_flax_llama import *
23
+ from .modeling_llama import *
24
+ from .tokenization_llama import *
25
+ from .tokenization_llama_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-5cbfd9f64dbc/environment/source/src/transformers/models/llama/configuration_llama.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """LLaMA model configuration"""
21
+
22
+ from ...configuration_utils import PretrainedConfig
23
+ from ...modeling_rope_utils import rope_config_validation
24
+
25
+
26
+ class LlamaConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
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 LLaMA-7B.
31
+ e.g. [meta-llama/Llama-2-7b-hf](https://huggingface.co/meta-llama/Llama-2-7b-hf)
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 32000):
39
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`LlamaModel`]
41
+ hidden_size (`int`, *optional*, defaults to 4096):
42
+ Dimension of the hidden representations.
43
+ intermediate_size (`int`, *optional*, defaults to 11008):
44
+ Dimension of the MLP representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 32):
46
+ Number of hidden layers in the Transformer decoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 32):
48
+ Number of attention heads for each attention layer in the Transformer decoder.
49
+ num_key_value_heads (`int`, *optional*):
50
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
51
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
52
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
53
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
54
+ by meanpooling all the original heads within that group. For more details, check out [this
55
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
56
+ `num_attention_heads`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
60
+ The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
61
+ Llama 2 up to 4096, CodeLlama up to 16384.
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
65
+ The epsilon used by the rms normalization layers.
66
+ use_cache (`bool`, *optional*, defaults to `True`):
67
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
68
+ relevant if `config.is_decoder=True`.
69
+ pad_token_id (`int`, *optional*):
70
+ Padding token id.
71
+ bos_token_id (`int`, *optional*, defaults to 1):
72
+ Beginning of stream token id.
73
+ eos_token_id (`int`, *optional*, defaults to 2):
74
+ End of stream token id.
75
+ pretraining_tp (`int`, *optional*, defaults to 1):
76
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
77
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
78
+ understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
79
+ results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
80
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
81
+ Whether to tie weight embeddings
82
+ rope_theta (`float`, *optional*, defaults to 10000.0):
83
+ The base period of the RoPE embeddings.
84
+ rope_scaling (`Dict`, *optional*):
85
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
86
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
87
+ accordingly.
88
+ Expected contents:
89
+ `rope_type` (`str`):
90
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
91
+ 'llama3'], with 'default' being the original RoPE implementation.
92
+ `factor` (`float`, *optional*):
93
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
94
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
95
+ original maximum pre-trained length.
96
+ `original_max_position_embeddings` (`int`, *optional*):
97
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
98
+ pretraining.
99
+ `attention_factor` (`float`, *optional*):
100
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
101
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
102
+ `factor` field to infer the suggested value.
103
+ `beta_fast` (`float`, *optional*):
104
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
105
+ ramp function. If unspecified, it defaults to 32.
106
+ `beta_slow` (`float`, *optional*):
107
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
108
+ ramp function. If unspecified, it defaults to 1.
109
+ `short_factor` (`list[float]`, *optional*):
110
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
111
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
112
+ size divided by the number of attention heads divided by 2
113
+ `long_factor` (`list[float]`, *optional*):
114
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
115
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
116
+ size divided by the number of attention heads divided by 2
117
+ `low_freq_factor` (`float`, *optional*):
118
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
119
+ `high_freq_factor` (`float`, *optional*):
120
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
121
+ attention_bias (`bool`, *optional*, defaults to `False`):
122
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
123
+ attention_dropout (`float`, *optional*, defaults to 0.0):
124
+ The dropout ratio for the attention probabilities.
125
+ mlp_bias (`bool`, *optional*, defaults to `False`):
126
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
127
+ head_dim (`int`, *optional*):
128
+ The attention head dimension. If None, it will default to hidden_size // num_attention_heads
129
+
130
+ ```python
131
+ >>> from transformers import LlamaModel, LlamaConfig
132
+
133
+ >>> # Initializing a LLaMA llama-7b style configuration
134
+ >>> configuration = LlamaConfig()
135
+
136
+ >>> # Initializing a model from the llama-7b style configuration
137
+ >>> model = LlamaModel(configuration)
138
+
139
+ >>> # Accessing the model configuration
140
+ >>> configuration = model.config
141
+ ```"""
142
+
143
+ model_type = "llama"
144
+ keys_to_ignore_at_inference = ["past_key_values"]
145
+ # Default tensor parallel plan for base model `LlamaModel`
146
+ base_model_tp_plan = {
147
+ "layers.*.self_attn.q_proj": "colwise",
148
+ "layers.*.self_attn.k_proj": "colwise",
149
+ "layers.*.self_attn.v_proj": "colwise",
150
+ "layers.*.self_attn.o_proj": "rowwise",
151
+ "layers.*.mlp.gate_proj": "colwise",
152
+ "layers.*.mlp.up_proj": "colwise",
153
+ "layers.*.mlp.down_proj": "rowwise",
154
+ }
155
+ base_model_pp_plan = {
156
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
157
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
158
+ "norm": (["hidden_states"], ["hidden_states"]),
159
+ }
160
+
161
+ def __init__(
162
+ self,
163
+ vocab_size=32000,
164
+ hidden_size=4096,
165
+ intermediate_size=11008,
166
+ num_hidden_layers=32,
167
+ num_attention_heads=32,
168
+ num_key_value_heads=None,
169
+ hidden_act="silu",
170
+ max_position_embeddings=2048,
171
+ initializer_range=0.02,
172
+ rms_norm_eps=1e-6,
173
+ use_cache=True,
174
+ pad_token_id=None,
175
+ bos_token_id=1,
176
+ eos_token_id=2,
177
+ pretraining_tp=1,
178
+ tie_word_embeddings=False,
179
+ rope_theta=10000.0,
180
+ rope_scaling=None,
181
+ attention_bias=False,
182
+ attention_dropout=0.0,
183
+ mlp_bias=False,
184
+ head_dim=None,
185
+ **kwargs,
186
+ ):
187
+ self.vocab_size = vocab_size
188
+ self.max_position_embeddings = max_position_embeddings
189
+ self.hidden_size = hidden_size
190
+ self.intermediate_size = intermediate_size
191
+ self.num_hidden_layers = num_hidden_layers
192
+ self.num_attention_heads = num_attention_heads
193
+
194
+ # for backward compatibility
195
+ if num_key_value_heads is None:
196
+ num_key_value_heads = num_attention_heads
197
+
198
+ self.num_key_value_heads = num_key_value_heads
199
+ self.hidden_act = hidden_act
200
+ self.initializer_range = initializer_range
201
+ self.rms_norm_eps = rms_norm_eps
202
+ self.pretraining_tp = pretraining_tp
203
+ self.use_cache = use_cache
204
+ self.rope_theta = rope_theta
205
+ self.rope_scaling = rope_scaling
206
+ self.attention_bias = attention_bias
207
+ self.attention_dropout = attention_dropout
208
+ self.mlp_bias = mlp_bias
209
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
210
+ # Validate the correctness of rotary position embeddings parameters
211
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
212
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
213
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
214
+ rope_config_validation(self)
215
+
216
+ super().__init__(
217
+ pad_token_id=pad_token_id,
218
+ bos_token_id=bos_token_id,
219
+ eos_token_id=eos_token_id,
220
+ tie_word_embeddings=tie_word_embeddings,
221
+ **kwargs,
222
+ )
223
+
224
+
225
+ __all__ = ["LlamaConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama/convert_llama_weights_to_hf.py ADDED
@@ -0,0 +1,605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 EleutherAI 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
+ import argparse
15
+ import gc
16
+ import json
17
+ import os
18
+ import tempfile
19
+ import warnings
20
+
21
+ import torch
22
+ from tokenizers import AddedToken, processors
23
+
24
+ from transformers import GenerationConfig, LlamaConfig, LlamaForCausalLM, LlamaTokenizer, PreTrainedTokenizerFast
25
+ from transformers.convert_slow_tokenizer import TikTokenConverter
26
+
27
+
28
+ try:
29
+ from transformers import LlamaTokenizerFast
30
+ except ImportError as e:
31
+ warnings.warn(e)
32
+ warnings.warn(
33
+ "The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion"
34
+ )
35
+ LlamaTokenizerFast = None
36
+
37
+ """
38
+ Sample usage:
39
+
40
+ ```
41
+ python src/transformers/models/llama/convert_llama_weights_to_hf.py \
42
+ --input_dir /path/to/downloaded/llama/weights --model_size 1B --llama_version 3.2 --output_dir /output/path
43
+ ```
44
+
45
+ Thereafter, models can be loaded via:
46
+
47
+ ```py
48
+ from transformers import LlamaForCausalLM, LlamaTokenizer
49
+
50
+ model = LlamaForCausalLM.from_pretrained("/output/path")
51
+ tokenizer = LlamaTokenizer.from_pretrained("/output/path")
52
+ ```
53
+
54
+ Important note: you need to be able to host the whole model in RAM to execute this script (even if the biggest versions
55
+ come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM).
56
+
57
+ If you want your tokenizer to add a bos automatically you should update the tokenizer._tokenizers.post_processor:
58
+
59
+ ```py
60
+ from tokenizers import processors
61
+ bos = "<|begin_of_text|>"
62
+ tokenizer._tokenizers.post_processor = processors.Sequence(
63
+ [
64
+ processors.ByteLevel(trim_offsets=False),
65
+ processors.TemplateProcessing(
66
+ single=f"{bos}:0 $A:0",
67
+ pair=f"{bos}:0 $A:0 {bos}:1 $B:1",
68
+ special_tokens=[
69
+ (bos, tokenizer.encode(bos)),
70
+ ],
71
+ ),
72
+ ]
73
+ )
74
+ ```
75
+ """
76
+
77
+ NUM_SHARDS = {
78
+ "1B": 1,
79
+ "3B": 1,
80
+ "7B": 1,
81
+ "8B": 1,
82
+ "8Bf": 1,
83
+ "7Bf": 1,
84
+ "13B": 2,
85
+ "13Bf": 2,
86
+ "34B": 4,
87
+ "30B": 4,
88
+ "65B": 8,
89
+ "70B": 8,
90
+ "70Bf": 8,
91
+ "405B": 8,
92
+ "405B-MP16": 16,
93
+ }
94
+
95
+ CONTEXT_LENGTH_FOR_VERSION = {"Guard-3": 131072, "3.2": 131072, "3.1": 131072, "3": 8192, "2": 4096, "1": 2048}
96
+
97
+ BOS_ADDED_TOKEN = AddedToken(
98
+ "<|begin_of_text|>", single_word=False, lstrip=False, rstrip=False, normalized=False, special=True
99
+ )
100
+ EOS_ADDED_TOKEN = AddedToken(
101
+ "<|end_of_text|>", single_word=False, lstrip=False, rstrip=False, normalized=False, special=True
102
+ )
103
+ EOT_ADDED_TOKEN = AddedToken(
104
+ "<|eot_id|>", single_word=False, lstrip=False, rstrip=False, normalized=False, special=True
105
+ )
106
+
107
+ DEFAULT_LLAMA_SPECIAL_TOKENS = {
108
+ "3": [
109
+ "<|begin_of_text|>",
110
+ "<|end_of_text|>",
111
+ "<|reserved_special_token_0|>",
112
+ "<|reserved_special_token_1|>",
113
+ "<|reserved_special_token_2|>",
114
+ "<|reserved_special_token_3|>",
115
+ "<|start_header_id|>",
116
+ "<|end_header_id|>",
117
+ "<|reserved_special_token_4|>",
118
+ "<|eot_id|>", # end of turn
119
+ ]
120
+ + [f"<|reserved_special_token_{i}|>" for i in range(5, 256 - 5)],
121
+ "3.1": [
122
+ "<|begin_of_text|>",
123
+ "<|end_of_text|>",
124
+ "<|reserved_special_token_0|>",
125
+ "<|reserved_special_token_1|>",
126
+ "<|finetune_right_pad_id|>",
127
+ "<|reserved_special_token_2|>",
128
+ "<|start_header_id|>",
129
+ "<|end_header_id|>",
130
+ "<|eom_id|>", # end of message
131
+ "<|eot_id|>", # end of turn
132
+ "<|python_tag|>",
133
+ ]
134
+ + [f"<|reserved_special_token_{i}|>" for i in range(3, 256 - 8)],
135
+ "3.2": [
136
+ "<|begin_of_text|>",
137
+ "<|end_of_text|>",
138
+ "<|reserved_special_token_0|>",
139
+ "<|reserved_special_token_1|>",
140
+ "<|finetune_right_pad_id|>",
141
+ "<|reserved_special_token_2|>",
142
+ "<|start_header_id|>",
143
+ "<|end_header_id|>",
144
+ "<|eom_id|>", # end of message
145
+ "<|eot_id|>", # end of turn
146
+ "<|python_tag|>",
147
+ ]
148
+ + [f"<|reserved_special_token_{i}|>" for i in range(3, 256 - 8)],
149
+ "Guard-3": [
150
+ "<|begin_of_text|>",
151
+ "<|end_of_text|>",
152
+ "<|reserved_special_token_0|>",
153
+ "<|reserved_special_token_1|>",
154
+ "<|finetune_right_pad_id|>",
155
+ "<|reserved_special_token_2|>",
156
+ "<|start_header_id|>",
157
+ "<|end_header_id|>",
158
+ "<|eom_id|>", # end of message
159
+ "<|eot_id|>", # end of turn
160
+ "<|python_tag|>",
161
+ ]
162
+ + [f"<|reserved_special_token_{i}|>" for i in range(3, 256 - 8)],
163
+ }
164
+
165
+
166
+ def is_llama_3(version):
167
+ return version in ["3", "3.1", "3.2", "Guard-3"]
168
+
169
+
170
+ def compute_intermediate_size(n, ffn_dim_multiplier=1, multiple_of=256):
171
+ return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3)) + multiple_of - 1) // multiple_of)
172
+
173
+
174
+ def read_json(path):
175
+ with open(path, "r") as f:
176
+ return json.load(f)
177
+
178
+
179
+ def write_json(text, path):
180
+ with open(path, "w") as f:
181
+ json.dump(text, f)
182
+
183
+
184
+ def write_model(
185
+ model_path,
186
+ input_base_path,
187
+ model_size=None,
188
+ safe_serialization=True,
189
+ llama_version="1",
190
+ vocab_size=None,
191
+ num_shards=None,
192
+ instruct=False,
193
+ push_to_hub=False,
194
+ ):
195
+ print("Converting the model.")
196
+ params = read_json(os.path.join(input_base_path, "params.json"))
197
+ num_shards = NUM_SHARDS[model_size] if num_shards is None else num_shards
198
+ params = params.get("model", params)
199
+ n_layers = params["n_layers"]
200
+ n_heads = params["n_heads"]
201
+ n_heads_per_shard = n_heads // num_shards
202
+ dim = params["dim"]
203
+ dims_per_head = dim // n_heads
204
+ base = params.get("rope_theta", 10000.0)
205
+ inv_freq = 1.0 / (base ** (torch.arange(0, dims_per_head, 2).float() / dims_per_head))
206
+ if base > 10000.0 and not is_llama_3(llama_version):
207
+ max_position_embeddings = 16384
208
+ else:
209
+ max_position_embeddings = CONTEXT_LENGTH_FOR_VERSION[llama_version]
210
+
211
+ if params.get("n_kv_heads", None) is not None:
212
+ num_key_value_heads = params["n_kv_heads"] # for GQA / MQA
213
+ num_key_value_heads_per_shard = num_key_value_heads // num_shards
214
+ key_value_dim = dims_per_head * num_key_value_heads
215
+ else: # compatibility with other checkpoints
216
+ num_key_value_heads = n_heads
217
+ num_key_value_heads_per_shard = n_heads_per_shard
218
+ key_value_dim = dim
219
+
220
+ # permute for sliced rotary
221
+ def permute(w, n_heads, dim1=dim, dim2=dim):
222
+ return w.view(n_heads, dim1 // n_heads // 2, 2, dim2).transpose(1, 2).reshape(dim1, dim2)
223
+
224
+ with tempfile.TemporaryDirectory() as tmp_model_path:
225
+ print(f"Fetching all parameters from the checkpoint at {input_base_path}.")
226
+ # Load weights
227
+ if num_shards == 1:
228
+ # Not sharded
229
+ # (The sharded implementation would also work, but this is simpler.)
230
+ loaded = torch.load(
231
+ os.path.join(input_base_path, "consolidated.00.pth"), map_location="cpu", weights_only=True
232
+ )
233
+ else:
234
+ # Sharded
235
+ checkpoint_list = sorted([file for file in os.listdir(input_base_path) if file.endswith(".pth")])
236
+ print("Loading in order:", checkpoint_list)
237
+ loaded = [
238
+ torch.load(os.path.join(input_base_path, file), map_location="cpu", weights_only=True)
239
+ for file in checkpoint_list
240
+ ]
241
+ param_count = 0
242
+ index_dict = {"weight_map": {}}
243
+ for layer_i in range(n_layers):
244
+ filename = f"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin"
245
+ if num_shards == 1:
246
+ # Unsharded
247
+ state_dict = {
248
+ f"model.layers.{layer_i}.self_attn.q_proj.weight": permute(
249
+ loaded[f"layers.{layer_i}.attention.wq.weight"], n_heads=n_heads
250
+ ),
251
+ f"model.layers.{layer_i}.self_attn.k_proj.weight": permute(
252
+ loaded[f"layers.{layer_i}.attention.wk.weight"],
253
+ n_heads=num_key_value_heads,
254
+ dim1=key_value_dim,
255
+ ),
256
+ f"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[f"layers.{layer_i}.attention.wv.weight"],
257
+ f"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[f"layers.{layer_i}.attention.wo.weight"],
258
+ f"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w1.weight"],
259
+ f"model.layers.{layer_i}.mlp.down_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w2.weight"],
260
+ f"model.layers.{layer_i}.mlp.up_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w3.weight"],
261
+ f"model.layers.{layer_i}.input_layernorm.weight": loaded[
262
+ f"layers.{layer_i}.attention_norm.weight"
263
+ ],
264
+ f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[
265
+ f"layers.{layer_i}.ffn_norm.weight"
266
+ ],
267
+ }
268
+ else:
269
+ # Sharded
270
+ # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share
271
+ # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is
272
+ # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned.
273
+
274
+ state_dict = {
275
+ f"model.layers.{layer_i}.input_layernorm.weight": loaded[0][
276
+ f"layers.{layer_i}.attention_norm.weight"
277
+ ].clone(),
278
+ f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][
279
+ f"layers.{layer_i}.ffn_norm.weight"
280
+ ].clone(),
281
+ }
282
+ state_dict[f"model.layers.{layer_i}.self_attn.q_proj.weight"] = permute(
283
+ torch.cat(
284
+ [
285
+ loaded[i][f"layers.{layer_i}.attention.wq.weight"].view(
286
+ n_heads_per_shard, dims_per_head, dim
287
+ )
288
+ for i in range(len(loaded))
289
+ ],
290
+ dim=0,
291
+ ).reshape(dim, dim),
292
+ n_heads=n_heads,
293
+ )
294
+ state_dict[f"model.layers.{layer_i}.self_attn.k_proj.weight"] = permute(
295
+ torch.cat(
296
+ [
297
+ loaded[i][f"layers.{layer_i}.attention.wk.weight"].view(
298
+ num_key_value_heads_per_shard, dims_per_head, dim
299
+ )
300
+ for i in range(len(loaded))
301
+ ],
302
+ dim=0,
303
+ ).reshape(key_value_dim, dim),
304
+ num_key_value_heads,
305
+ key_value_dim,
306
+ dim,
307
+ )
308
+ state_dict[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = torch.cat(
309
+ [
310
+ loaded[i][f"layers.{layer_i}.attention.wv.weight"].view(
311
+ num_key_value_heads_per_shard, dims_per_head, dim
312
+ )
313
+ for i in range(len(loaded))
314
+ ],
315
+ dim=0,
316
+ ).reshape(key_value_dim, dim)
317
+
318
+ state_dict[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = torch.cat(
319
+ [loaded[i][f"layers.{layer_i}.attention.wo.weight"] for i in range(len(loaded))], dim=1
320
+ )
321
+ state_dict[f"model.layers.{layer_i}.mlp.gate_proj.weight"] = torch.cat(
322
+ [loaded[i][f"layers.{layer_i}.feed_forward.w1.weight"] for i in range(len(loaded))], dim=0
323
+ )
324
+ state_dict[f"model.layers.{layer_i}.mlp.down_proj.weight"] = torch.cat(
325
+ [loaded[i][f"layers.{layer_i}.feed_forward.w2.weight"] for i in range(len(loaded))], dim=1
326
+ )
327
+ state_dict[f"model.layers.{layer_i}.mlp.up_proj.weight"] = torch.cat(
328
+ [loaded[i][f"layers.{layer_i}.feed_forward.w3.weight"] for i in range(len(loaded))], dim=0
329
+ )
330
+
331
+ state_dict[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = inv_freq
332
+ for k, v in state_dict.items():
333
+ index_dict["weight_map"][k] = filename
334
+ param_count += v.numel()
335
+ torch.save(state_dict, os.path.join(tmp_model_path, filename))
336
+
337
+ filename = f"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin"
338
+ if num_shards == 1:
339
+ # Unsharded
340
+ state_dict = {
341
+ "model.embed_tokens.weight": loaded["tok_embeddings.weight"],
342
+ "model.norm.weight": loaded["norm.weight"],
343
+ "lm_head.weight": loaded["output.weight"],
344
+ }
345
+ else:
346
+ concat_dim = 0 if is_llama_3(llama_version) else 1
347
+ state_dict = {
348
+ "model.norm.weight": loaded[0]["norm.weight"],
349
+ "model.embed_tokens.weight": torch.cat(
350
+ [loaded[i]["tok_embeddings.weight"] for i in range(len(loaded))], dim=concat_dim
351
+ ),
352
+ "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(len(loaded))], dim=0),
353
+ }
354
+
355
+ for k, v in state_dict.items():
356
+ index_dict["weight_map"][k] = filename
357
+ param_count += v.numel()
358
+ torch.save(state_dict, os.path.join(tmp_model_path, filename))
359
+
360
+ # Write configs
361
+ index_dict["metadata"] = {"total_size": param_count * 2}
362
+ write_json(index_dict, os.path.join(tmp_model_path, "pytorch_model.bin.index.json"))
363
+ ffn_dim_multiplier = params.get("ffn_dim_multiplier", 1)
364
+ multiple_of = params.get("multiple_of", 256)
365
+
366
+ if is_llama_3(llama_version):
367
+ bos_token_id = 128000
368
+
369
+ if instruct:
370
+ eos_token_id = [128001, 128008, 128009]
371
+ else:
372
+ eos_token_id = 128001
373
+ else:
374
+ bos_token_id = 1
375
+ eos_token_id = 2
376
+
377
+ if llama_version in ["3.1", "3.2", "Guard-3"]:
378
+ rope_scaling = {
379
+ "factor": 32.0 if llama_version == "3.2" else 8.0,
380
+ "low_freq_factor": 1.0,
381
+ "high_freq_factor": 4.0,
382
+ "original_max_position_embeddings": 8192,
383
+ "rope_type": "llama3",
384
+ }
385
+ else:
386
+ rope_scaling = None
387
+
388
+ config = LlamaConfig(
389
+ hidden_size=dim,
390
+ intermediate_size=compute_intermediate_size(dim, ffn_dim_multiplier, multiple_of),
391
+ num_attention_heads=params["n_heads"],
392
+ num_hidden_layers=params["n_layers"],
393
+ rms_norm_eps=params["norm_eps"],
394
+ num_key_value_heads=num_key_value_heads,
395
+ vocab_size=vocab_size,
396
+ rope_theta=base,
397
+ rope_scaling=rope_scaling,
398
+ max_position_embeddings=max_position_embeddings,
399
+ bos_token_id=bos_token_id,
400
+ eos_token_id=eos_token_id,
401
+ tie_word_embeddings=llama_version in ["3.2"],
402
+ )
403
+
404
+ config.save_pretrained(tmp_model_path)
405
+
406
+ generation_config = GenerationConfig(
407
+ do_sample=True,
408
+ temperature=0.6,
409
+ top_p=0.9,
410
+ bos_token_id=bos_token_id,
411
+ eos_token_id=eos_token_id,
412
+ )
413
+ generation_config.save_pretrained(tmp_model_path)
414
+
415
+ # Make space so we can load the model properly now.
416
+ del state_dict
417
+ del loaded
418
+ gc.collect()
419
+
420
+ print("Loading the checkpoint in a Llama model.")
421
+ model = LlamaForCausalLM.from_pretrained(tmp_model_path, torch_dtype=torch.bfloat16)
422
+
423
+ # Avoid saving this as part of the config.
424
+ del model.config._name_or_path
425
+ model.config.torch_dtype = torch.float16
426
+
427
+ print("Saving in the Transformers format.")
428
+ if push_to_hub:
429
+ print("Pushing to the hub.")
430
+ model.push_to_hub(model_path, safe_serialization=safe_serialization, private=True, use_temp_dir=True)
431
+ else:
432
+ print("Saving to disk.")
433
+ model.save_pretrained(model_path, safe_serialization=safe_serialization)
434
+
435
+
436
+ class Llama3Converter(TikTokenConverter):
437
+ def __init__(self, vocab_file, special_tokens=None, instruct=False, llama_version="3.2", **kwargs):
438
+ super().__init__(vocab_file, additional_special_tokens=special_tokens, **kwargs)
439
+ tokenizer = self.converted()
440
+
441
+ # References for chat templates in instruct models
442
+ templates_for_version = {
443
+ "2": ("meta-llama/Llama-2-7b-chat-hf", "f5db02db724555f92da89c216ac04704f23d4590"),
444
+ "3": ("meta-llama/Meta-Llama-3-8B-Instruct", "5f0b02c75b57c5855da9ae460ce51323ea669d8a"),
445
+ "3.1": ("meta-llama/Llama-3.1-8B-Instruct", "0e9e39f249a16976918f6564b8830bc894c89659"),
446
+ "3.2": ("meta-llama/Llama-3.2-1B-Instruct", "e9f8effbab1cbdc515c11ee6e098e3d5a9f51e14"),
447
+ "Guard-3": ("meta-llama/Llama-Guard-3-1B", "acf7aafa60f0410f8f42b1fa35e077d705892029"),
448
+ }
449
+
450
+ # Add chat_template only if instruct is True.
451
+ # Prevents a null chat_template, which triggers
452
+ # a parsing warning in the Hub.
453
+ additional_kwargs = {}
454
+ if instruct or llama_version in ["Guard-3"]:
455
+ model_id, revision = templates_for_version.get(llama_version, (None, None))
456
+ if model_id is not None:
457
+ from transformers import AutoTokenizer
458
+
459
+ t = AutoTokenizer.from_pretrained(model_id, revision=revision)
460
+ additional_kwargs["chat_template"] = t.chat_template
461
+
462
+ self.converted_tokenizer = PreTrainedTokenizerFast(
463
+ tokenizer_object=tokenizer,
464
+ bos_token="<|begin_of_text|>",
465
+ eos_token="<|end_of_text|>" if not instruct else "<|eot_id|>",
466
+ model_input_names=["input_ids", "attention_mask"],
467
+ model_max_length=CONTEXT_LENGTH_FOR_VERSION[llama_version],
468
+ clean_up_tokenization_spaces=True,
469
+ **additional_kwargs,
470
+ )
471
+ self.update_post_processor(self.converted_tokenizer)
472
+ # finer special_tokens_map.json
473
+ self.converted_tokenizer._bos_token = BOS_ADDED_TOKEN
474
+ self.converted_tokenizer._eos_token = EOT_ADDED_TOKEN if instruct else EOS_ADDED_TOKEN
475
+
476
+ # We can't do this while building the tokenizer because we have no easy access to the bos token id
477
+ def update_post_processor(self, tokenizer):
478
+ tokenizer._tokenizer.post_processor = processors.Sequence(
479
+ [
480
+ processors.ByteLevel(trim_offsets=False),
481
+ processors.TemplateProcessing(
482
+ single="<|begin_of_text|> $A",
483
+ pair="<|begin_of_text|>:0 $A:0 <|begin_of_text|>:1 $B:1",
484
+ special_tokens=[
485
+ ("<|begin_of_text|>", tokenizer.convert_tokens_to_ids("<|begin_of_text|>")),
486
+ ],
487
+ ),
488
+ ]
489
+ )
490
+
491
+
492
+ def write_tokenizer(
493
+ tokenizer_path, input_tokenizer_path, llama_version="2", special_tokens=None, instruct=False, push_to_hub=False
494
+ ):
495
+ print("Converting the tokenizer.")
496
+ tokenizer_class = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast
497
+ if is_llama_3(llama_version):
498
+ tokenizer = Llama3Converter(
499
+ input_tokenizer_path,
500
+ special_tokens,
501
+ instruct,
502
+ llama_version,
503
+ ).converted_tokenizer
504
+ else:
505
+ try:
506
+ tokenizer = tokenizer_class(input_tokenizer_path)
507
+ except Exception:
508
+ raise ValueError(
509
+ "Failed to instantiate tokenizer. Please, make sure you have sentencepiece and protobuf installed."
510
+ )
511
+
512
+ if push_to_hub:
513
+ print(f"Pushing a {tokenizer_class.__name__} to the Hub repo - {tokenizer_path}.")
514
+ tokenizer.push_to_hub(tokenizer_path, private=True, use_temp_dir=True)
515
+ else:
516
+ print(f"Saving a {tokenizer_class.__name__} to {tokenizer_path}.")
517
+ tokenizer.save_pretrained(tokenizer_path)
518
+ return tokenizer
519
+
520
+
521
+ def main():
522
+ parser = argparse.ArgumentParser()
523
+ parser.add_argument(
524
+ "--input_dir",
525
+ help="Location of Llama weights, which contains tokenizer.model and model folders",
526
+ )
527
+ parser.add_argument(
528
+ "--model_size",
529
+ default=None,
530
+ help="'f' Deprecated in favor of `num_shards`: models correspond to the finetuned versions, and are specific to the Llama2 official release. For more details on Llama2, check out the original repo: https://huggingface.co/meta-llama",
531
+ )
532
+ parser.add_argument(
533
+ "--output_dir",
534
+ help="Location to write HF model and tokenizer",
535
+ )
536
+ parser.add_argument(
537
+ "--push_to_hub",
538
+ help="Whether or not to push the model to the hub at `output_dir` instead of saving it locally.",
539
+ action="store_true",
540
+ default=False,
541
+ )
542
+ parser.add_argument(
543
+ "--safe_serialization", action="store_true", default=True, help="Whether or not to save using `safetensors`."
544
+ )
545
+ # Different Llama versions used different default values for max_position_embeddings, hence the need to be able to specify which version is being used.
546
+ parser.add_argument(
547
+ "--llama_version",
548
+ choices=["1", "2", "3", "3.1", "3.2", "Guard-3"],
549
+ default="1",
550
+ type=str,
551
+ help="Version of the Llama model to convert. Currently supports Llama1 and Llama2. Controls the context size",
552
+ )
553
+ parser.add_argument(
554
+ "--num_shards",
555
+ default=None,
556
+ type=int,
557
+ help="The number of individual shards used for the model. Does not have to be the same as the number of consolidated_xx.pth",
558
+ )
559
+ parser.add_argument(
560
+ "--special_tokens",
561
+ default=None,
562
+ type=list[str],
563
+ help="The list of special tokens that should be added to the model.",
564
+ )
565
+ parser.add_argument(
566
+ "--instruct",
567
+ action="store_true",
568
+ default=False,
569
+ help="Whether the model is an instruct model or not. Will affect special tokens and chat template.",
570
+ )
571
+ args = parser.parse_args()
572
+ if args.model_size is None and args.num_shards is None:
573
+ raise ValueError("You have to set at least `num_shards` if you are not giving the `model_size`")
574
+ if args.special_tokens is None:
575
+ # no special tokens by default
576
+ args.special_tokens = DEFAULT_LLAMA_SPECIAL_TOKENS.get(str(args.llama_version), [])
577
+
578
+ spm_path = os.path.join(args.input_dir, "tokenizer.model")
579
+ vocab_size = len(
580
+ write_tokenizer(
581
+ args.output_dir,
582
+ spm_path,
583
+ llama_version=args.llama_version,
584
+ special_tokens=args.special_tokens,
585
+ instruct=args.instruct,
586
+ push_to_hub=args.push_to_hub,
587
+ )
588
+ )
589
+
590
+ if args.model_size != "tokenizer_only":
591
+ write_model(
592
+ model_path=args.output_dir,
593
+ input_base_path=args.input_dir,
594
+ model_size=args.model_size,
595
+ safe_serialization=args.safe_serialization,
596
+ llama_version=args.llama_version,
597
+ vocab_size=vocab_size,
598
+ num_shards=args.num_shards,
599
+ instruct=args.instruct,
600
+ push_to_hub=args.push_to_hub,
601
+ )
602
+
603
+
604
+ if __name__ == "__main__":
605
+ main()
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama/modeling_flax_llama.py ADDED
@@ -0,0 +1,747 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Meta AI, EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """Flax LLaMA model."""
21
+
22
+ from functools import partial
23
+ from typing import Optional
24
+
25
+ import flax.linen as nn
26
+ import jax
27
+ import jax.numpy as jnp
28
+ import numpy as np
29
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
30
+ from flax.linen import combine_masks, make_causal_mask
31
+ from flax.linen.attention import dot_product_attention_weights
32
+ from flax.traverse_util import flatten_dict, unflatten_dict
33
+ from jax import lax
34
+
35
+ from ...modeling_flax_outputs import FlaxBaseModelOutput, FlaxCausalLMOutput
36
+ from ...modeling_flax_utils import ACT2FN, FlaxPreTrainedModel, append_call_sample_docstring
37
+ from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging
38
+ from .configuration_llama import LlamaConfig
39
+
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+ _CONFIG_FOR_DOC = "LlamaConfig"
44
+ _CHECKPOINT_FOR_DOC = "afmck/testing-llama-tiny"
45
+ _REAL_CHECKPOINT_FOR_DOC = "openlm-research/open_llama_3b_v2"
46
+
47
+ LLAMA_START_DOCSTRING = r"""
48
+
49
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
50
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
51
+ etc.)
52
+
53
+ This model is also a Flax Linen
54
+ [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
55
+ regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
56
+
57
+ Finally, this model supports inherent JAX features such as:
58
+
59
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
60
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
61
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
62
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
63
+
64
+ Parameters:
65
+ config ([`LlamaConfig`]): Model configuration class with all the parameters of the model.
66
+ Initializing with a config file does not load the weights associated with the model, only the
67
+ configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
68
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
69
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16`, or
70
+ `jax.numpy.bfloat16`.
71
+
72
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
73
+ specified all the computation will be performed with the given `dtype`.
74
+
75
+ **Note that this only specifies the dtype of the computation and does not influence the dtype of model
76
+ parameters.**
77
+
78
+ If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
79
+ [`~FlaxPreTrainedModel.to_bf16`].
80
+ """
81
+
82
+ LLAMA_INPUTS_DOCSTRING = r"""
83
+ Args:
84
+ input_ids (`numpy.ndarray` of shape `(batch_size, input_ids_length)`):
85
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
86
+ it.
87
+
88
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
89
+ [`PreTrainedTokenizer.__call__`] for details.
90
+
91
+ [What are input IDs?](../glossary#input-ids)
92
+ attention_mask (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
93
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
94
+
95
+ - 1 for tokens that are **not masked**,
96
+ - 0 for tokens that are **masked**.
97
+
98
+ [What are attention masks?](../glossary#attention-mask)
99
+
100
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
101
+ [`PreTrainedTokenizer.__call__`] for details.
102
+
103
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
104
+ `past_key_values`).
105
+
106
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
107
+ and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
108
+ information on the default strategy.
109
+
110
+ - 1 indicates the head is **not masked**,
111
+ - 0 indicates the head is **masked**.
112
+ position_ids (`numpy.ndarray` of shape `(batch_size, input_ids_length)`, *optional*):
113
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
114
+ config.n_positions - 1]`.
115
+
116
+ [What are position IDs?](../glossary#position-ids)
117
+ past_key_values (`dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
118
+ Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
119
+ auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
120
+ output_attentions (`bool`, *optional*):
121
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
122
+ tensors for more detail.
123
+ output_hidden_states (`bool`, *optional*):
124
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
125
+ more detail.
126
+ return_dict (`bool`, *optional*):
127
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
128
+ """
129
+
130
+
131
+ def create_sinusoidal_positions(num_pos, dim):
132
+ inv_freq = 1.0 / (10000 ** (np.arange(0, dim, 2) / dim))
133
+ freqs = np.einsum("i , j -> i j", np.arange(num_pos), inv_freq).astype("float32")
134
+
135
+ emb = np.concatenate((freqs, freqs), axis=-1)
136
+ out = np.concatenate((np.sin(emb)[:, None, :], np.cos(emb)[:, None, :]), axis=-1)
137
+ return jnp.array(out[:, :, :num_pos])
138
+
139
+
140
+ def rotate_half(tensor):
141
+ """Rotates half the hidden dims of the input."""
142
+ rotate_half_tensor = jnp.concatenate(
143
+ (-tensor[..., tensor.shape[-1] // 2 :], tensor[..., : tensor.shape[-1] // 2]), axis=-1
144
+ )
145
+ return rotate_half_tensor
146
+
147
+
148
+ def apply_rotary_pos_emb(tensor, sin_pos, cos_pos):
149
+ return (tensor * cos_pos) + (rotate_half(tensor) * sin_pos)
150
+
151
+
152
+ class FlaxLlamaRMSNorm(nn.Module):
153
+ config: LlamaConfig
154
+ dtype: jnp.dtype = jnp.float32
155
+
156
+ def setup(self):
157
+ self.epsilon = self.config.rms_norm_eps
158
+ self.weight = self.param("weight", lambda _, shape: jnp.ones(shape), self.config.hidden_size)
159
+
160
+ def __call__(self, hidden_states):
161
+ variance = jnp.asarray(hidden_states, dtype=jnp.float32)
162
+ variance = jnp.power(variance, 2)
163
+ variance = variance.mean(-1, keepdims=True)
164
+ # use `jax.numpy.sqrt` as `jax.lax.rsqrt` does not match `torch.rsqrt`
165
+ hidden_states = hidden_states / jnp.sqrt(variance + self.epsilon)
166
+
167
+ return self.weight * jnp.asarray(hidden_states, dtype=self.dtype)
168
+
169
+
170
+ class FlaxLlamaRotaryEmbedding(nn.Module):
171
+ config: LlamaConfig
172
+ dtype: jnp.dtype = jnp.float32
173
+
174
+ def setup(self):
175
+ head_dim = self.config.hidden_size // self.config.num_attention_heads
176
+ self.sincos = create_sinusoidal_positions(self.config.max_position_embeddings, head_dim)
177
+
178
+ def __call__(self, key, query, position_ids):
179
+ sincos = self.sincos[position_ids]
180
+ sin_pos, cos_pos = jnp.split(sincos, 2, axis=-1)
181
+
182
+ key = apply_rotary_pos_emb(key, sin_pos, cos_pos)
183
+ query = apply_rotary_pos_emb(query, sin_pos, cos_pos)
184
+
185
+ key = jnp.asarray(key, dtype=self.dtype)
186
+ query = jnp.asarray(query, dtype=self.dtype)
187
+
188
+ return key, query
189
+
190
+
191
+ class FlaxLlamaAttention(nn.Module):
192
+ config: LlamaConfig
193
+ dtype: jnp.dtype = jnp.float32
194
+ causal: bool = True
195
+ is_cross_attention: bool = False
196
+
197
+ def setup(self):
198
+ config = self.config
199
+ self.embed_dim = config.hidden_size
200
+ self.num_heads = config.num_attention_heads
201
+ self.head_dim = self.embed_dim // self.num_heads
202
+ self.num_key_value_heads = config.num_key_value_heads
203
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
204
+ self.attention_softmax_in_fp32 = self.dtype is not jnp.float32
205
+
206
+ dense = partial(
207
+ nn.Dense,
208
+ use_bias=config.attention_bias,
209
+ dtype=self.dtype,
210
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
211
+ )
212
+
213
+ self.q_proj = dense(self.num_heads * self.head_dim)
214
+ self.k_proj = dense(self.num_key_value_heads * self.head_dim)
215
+ self.v_proj = dense(self.num_key_value_heads * self.head_dim)
216
+ self.o_proj = dense(self.embed_dim)
217
+ self.causal_mask = make_causal_mask(jnp.ones((1, config.max_position_embeddings), dtype="bool"), dtype="bool")
218
+ self.rotary_emb = FlaxLlamaRotaryEmbedding(config, dtype=self.dtype)
219
+
220
+ def _split_heads(self, hidden_states, num_heads):
221
+ return hidden_states.reshape(hidden_states.shape[:2] + (num_heads, self.head_dim))
222
+
223
+ def _merge_heads(self, hidden_states):
224
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
225
+
226
+ @nn.compact
227
+ # Copied from transformers.models.gpt_neo.modeling_flax_gpt_neo.FlaxGPTNeoSelfAttention._concatenate_to_cache
228
+ def _concatenate_to_cache(self, key, value, query, attention_mask):
229
+ """
230
+ This function takes projected key, value states from a single input token and concatenates the states to cached
231
+ states from previous steps. This function is slightly adapted from the official Flax repository:
232
+ https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
233
+ """
234
+ # detect if we're initializing by absence of existing cache data.
235
+ is_initialized = self.has_variable("cache", "cached_key")
236
+ cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
237
+ cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
238
+ cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
239
+
240
+ if is_initialized:
241
+ *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
242
+ # update key, value caches with our new 1d spatial slices
243
+ cur_index = cache_index.value
244
+ indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
245
+ key = lax.dynamic_update_slice(cached_key.value, key, indices)
246
+ value = lax.dynamic_update_slice(cached_value.value, value, indices)
247
+ cached_key.value = key
248
+ cached_value.value = value
249
+ num_updated_cache_vectors = query.shape[1]
250
+ cache_index.value = cache_index.value + num_updated_cache_vectors
251
+ # 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.
252
+ pad_mask = jnp.broadcast_to(
253
+ jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
254
+ tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
255
+ )
256
+ attention_mask = combine_masks(pad_mask, attention_mask)
257
+ return key, value, attention_mask
258
+
259
+ def __call__(
260
+ self,
261
+ hidden_states,
262
+ attention_mask,
263
+ position_ids,
264
+ deterministic: bool = True,
265
+ init_cache: bool = False,
266
+ output_attentions: bool = False,
267
+ ):
268
+ query = self.q_proj(hidden_states)
269
+ key = self.k_proj(hidden_states)
270
+ value = self.v_proj(hidden_states)
271
+
272
+ query = self._split_heads(query, self.num_heads)
273
+ key = self._split_heads(key, self.num_key_value_heads)
274
+ value = self._split_heads(value, self.num_key_value_heads)
275
+
276
+ key, query = self.rotary_emb(key, query, position_ids)
277
+
278
+ query_length, key_length = query.shape[1], key.shape[1]
279
+
280
+ if self.has_variable("cache", "cached_key"):
281
+ mask_shift = self.variables["cache"]["cache_index"]
282
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
283
+ causal_mask = lax.dynamic_slice(
284
+ self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
285
+ )
286
+ else:
287
+ causal_mask = self.causal_mask[:, :, :query_length, :key_length]
288
+
289
+ batch_size = hidden_states.shape[0]
290
+ causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
291
+
292
+ attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
293
+ attention_mask = combine_masks(attention_mask, causal_mask)
294
+
295
+ dropout_rng = None
296
+ if not deterministic and self.config.attention_dropout > 0.0:
297
+ dropout_rng = self.make_rng("dropout")
298
+
299
+ # During fast autoregressive decoding, we feed one position at a time,
300
+ # and cache the keys and values step by step.
301
+ if self.has_variable("cache", "cached_key") or init_cache:
302
+ key, value, attention_mask = self._concatenate_to_cache(key, value, query, attention_mask)
303
+
304
+ key = jnp.repeat(key, self.num_key_value_groups, axis=2)
305
+ value = jnp.repeat(value, self.num_key_value_groups, axis=2)
306
+
307
+ # transform boolean mask into float mask
308
+ attention_bias = lax.select(
309
+ attention_mask > 0,
310
+ jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
311
+ jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
312
+ )
313
+
314
+ # usual dot product attention
315
+ attention_dtype = jnp.float32 if self.attention_softmax_in_fp32 else self.dtype
316
+ attn_weights = dot_product_attention_weights(
317
+ query,
318
+ key,
319
+ bias=attention_bias,
320
+ dropout_rng=dropout_rng,
321
+ dropout_rate=self.config.attention_dropout,
322
+ deterministic=deterministic,
323
+ dtype=attention_dtype,
324
+ )
325
+
326
+ if self.attention_softmax_in_fp32:
327
+ attn_weights = attn_weights.astype(self.dtype)
328
+
329
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value)
330
+ attn_output = self._merge_heads(attn_output)
331
+ attn_output = self.o_proj(attn_output)
332
+
333
+ outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
334
+ return outputs
335
+
336
+
337
+ class FlaxLlamaMLP(nn.Module):
338
+ config: LlamaConfig
339
+ dtype: jnp.dtype = jnp.float32
340
+
341
+ def setup(self):
342
+ embed_dim = self.config.hidden_size
343
+ inner_dim = self.config.intermediate_size if self.config.intermediate_size is not None else 4 * embed_dim
344
+
345
+ kernel_init = jax.nn.initializers.normal(self.config.initializer_range)
346
+ self.act = ACT2FN[self.config.hidden_act]
347
+
348
+ self.gate_proj = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
349
+ self.down_proj = nn.Dense(embed_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
350
+ self.up_proj = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
351
+
352
+ def __call__(self, hidden_states):
353
+ up_proj_states = self.up_proj(hidden_states)
354
+ gate_states = self.act(self.gate_proj(hidden_states))
355
+
356
+ hidden_states = self.down_proj(up_proj_states * gate_states)
357
+ return hidden_states
358
+
359
+
360
+ class FlaxLlamaDecoderLayer(nn.Module):
361
+ config: LlamaConfig
362
+ dtype: jnp.dtype = jnp.float32
363
+
364
+ def setup(self):
365
+ self.input_layernorm = FlaxLlamaRMSNorm(self.config, dtype=self.dtype)
366
+ self.self_attn = FlaxLlamaAttention(self.config, dtype=self.dtype)
367
+ self.post_attention_layernorm = FlaxLlamaRMSNorm(self.config, dtype=self.dtype)
368
+ self.mlp = FlaxLlamaMLP(self.config, dtype=self.dtype)
369
+
370
+ def __call__(
371
+ self,
372
+ hidden_states,
373
+ attention_mask=None,
374
+ position_ids=None,
375
+ deterministic: bool = True,
376
+ init_cache: bool = False,
377
+ output_attentions: bool = False,
378
+ ):
379
+ residual = hidden_states
380
+ hidden_states = self.input_layernorm(hidden_states)
381
+ outputs = self.self_attn(
382
+ hidden_states,
383
+ attention_mask=attention_mask,
384
+ position_ids=position_ids,
385
+ deterministic=deterministic,
386
+ init_cache=init_cache,
387
+ output_attentions=output_attentions,
388
+ )
389
+ # residual connection
390
+ attn_output = outputs[0]
391
+ hidden_states = residual + attn_output
392
+
393
+ residual = hidden_states
394
+ hidden_states = self.post_attention_layernorm(hidden_states)
395
+ hidden_states = self.mlp(hidden_states)
396
+ # residual connection
397
+ hidden_states = residual + hidden_states
398
+
399
+ return (hidden_states,) + outputs[1:]
400
+
401
+
402
+ # Copied from transformers.models.gpt_neo.modeling_flax_gpt_neo.FlaxGPTNeoPreTrainedModel with GPTNeo->Llama, GPT_NEO->LLAMA, transformer->model
403
+ class FlaxLlamaPreTrainedModel(FlaxPreTrainedModel):
404
+ """
405
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
406
+ models.
407
+ """
408
+
409
+ config_class = LlamaConfig
410
+ base_model_prefix = "model"
411
+ module_class: nn.Module = None
412
+
413
+ def __init__(
414
+ self,
415
+ config: LlamaConfig,
416
+ input_shape: tuple = (1, 1),
417
+ seed: int = 0,
418
+ dtype: jnp.dtype = jnp.float32,
419
+ _do_init: bool = True,
420
+ **kwargs,
421
+ ):
422
+ module = self.module_class(config=config, dtype=dtype, **kwargs)
423
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
424
+
425
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: tuple, params: FrozenDict = None) -> FrozenDict:
426
+ # init input tensors
427
+ input_ids = jnp.zeros(input_shape, dtype="i4")
428
+ attention_mask = jnp.ones_like(input_ids)
429
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_shape)
430
+ params_rng, dropout_rng = jax.random.split(rng)
431
+ rngs = {"params": params_rng, "dropout": dropout_rng}
432
+
433
+ random_params = self.module.init(rngs, input_ids, attention_mask, position_ids, return_dict=False)["params"]
434
+
435
+ if params is not None:
436
+ random_params = flatten_dict(unfreeze(random_params))
437
+ params = flatten_dict(unfreeze(params))
438
+ for missing_key in self._missing_keys:
439
+ params[missing_key] = random_params[missing_key]
440
+ self._missing_keys = set()
441
+ return freeze(unflatten_dict(params))
442
+ else:
443
+ return random_params
444
+
445
+ def init_cache(self, batch_size, max_length):
446
+ r"""
447
+ Args:
448
+ batch_size (`int`):
449
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
450
+ max_length (`int`):
451
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
452
+ cache.
453
+ """
454
+ # init input variables to retrieve cache
455
+ input_ids = jnp.ones((batch_size, max_length))
456
+ attention_mask = jnp.ones_like(input_ids)
457
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
458
+
459
+ init_variables = self.module.init(
460
+ jax.random.PRNGKey(0), input_ids, attention_mask, position_ids, return_dict=False, init_cache=True
461
+ )
462
+ return unfreeze(init_variables["cache"])
463
+
464
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
465
+ def __call__(
466
+ self,
467
+ input_ids,
468
+ attention_mask=None,
469
+ position_ids=None,
470
+ params: Optional[dict] = None,
471
+ past_key_values: Optional[dict] = None,
472
+ dropout_rng: jax.random.PRNGKey = None,
473
+ train: bool = False,
474
+ output_attentions: Optional[bool] = None,
475
+ output_hidden_states: Optional[bool] = None,
476
+ return_dict: Optional[bool] = None,
477
+ ):
478
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
479
+ output_hidden_states = (
480
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
481
+ )
482
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
483
+
484
+ batch_size, sequence_length = input_ids.shape
485
+
486
+ if position_ids is None:
487
+ if past_key_values is not None:
488
+ raise ValueError("Make sure to provide `position_ids` when passing `past_key_values`.")
489
+
490
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
491
+
492
+ if attention_mask is None:
493
+ attention_mask = jnp.ones((batch_size, sequence_length))
494
+
495
+ # Handle any PRNG if needed
496
+ rngs = {}
497
+ if dropout_rng is not None:
498
+ rngs["dropout"] = dropout_rng
499
+
500
+ inputs = {"params": params or self.params}
501
+
502
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that it can be changed by FlaxLlamaAttention module
503
+ if past_key_values:
504
+ inputs["cache"] = past_key_values
505
+ mutable = ["cache"]
506
+ else:
507
+ mutable = False
508
+
509
+ outputs = self.module.apply(
510
+ inputs,
511
+ jnp.array(input_ids, dtype="i4"),
512
+ jnp.array(attention_mask, dtype="i4"),
513
+ jnp.array(position_ids, dtype="i4"),
514
+ not train,
515
+ False,
516
+ output_attentions,
517
+ output_hidden_states,
518
+ return_dict,
519
+ rngs=rngs,
520
+ mutable=mutable,
521
+ )
522
+
523
+ # add updated cache to model output
524
+ if past_key_values is not None and return_dict:
525
+ outputs, past_key_values = outputs
526
+ outputs["past_key_values"] = unfreeze(past_key_values["cache"])
527
+ return outputs
528
+ elif past_key_values is not None and not return_dict:
529
+ outputs, past_key_values = outputs
530
+ outputs = outputs[:1] + (unfreeze(past_key_values["cache"]),) + outputs[1:]
531
+
532
+ return outputs
533
+
534
+
535
+ class FlaxLlamaLayerCollection(nn.Module):
536
+ config: LlamaConfig
537
+ dtype: jnp.dtype = jnp.float32
538
+
539
+ def setup(self):
540
+ self.blocks = [
541
+ FlaxLlamaDecoderLayer(self.config, dtype=self.dtype, name=str(i))
542
+ for i in range(self.config.num_hidden_layers)
543
+ ]
544
+
545
+ def __call__(
546
+ self,
547
+ hidden_states,
548
+ attention_mask=None,
549
+ position_ids=None,
550
+ deterministic: bool = True,
551
+ init_cache: bool = False,
552
+ output_attentions: bool = False,
553
+ output_hidden_states: bool = False,
554
+ return_dict: bool = False,
555
+ ):
556
+ all_attentions = () if output_attentions else None
557
+ all_hidden_states = () if output_hidden_states else None
558
+
559
+ for block in self.blocks:
560
+ if output_hidden_states:
561
+ all_hidden_states += (hidden_states,)
562
+ layer_outputs = block(
563
+ hidden_states,
564
+ attention_mask=attention_mask,
565
+ position_ids=position_ids,
566
+ deterministic=deterministic,
567
+ init_cache=init_cache,
568
+ output_attentions=output_attentions,
569
+ )
570
+ hidden_states = layer_outputs[0]
571
+
572
+ if output_attentions:
573
+ all_attentions += (layer_outputs[1],)
574
+
575
+ # this contains possible `None` values - `FlaxLlamaModule` will filter them out
576
+ outputs = (hidden_states, all_hidden_states, all_attentions)
577
+
578
+ return outputs
579
+
580
+
581
+ class FlaxLlamaModule(nn.Module):
582
+ config: LlamaConfig
583
+ dtype: jnp.dtype = jnp.float32
584
+
585
+ def setup(self):
586
+ self.hidden_size = self.config.hidden_size
587
+ embedding_init = jax.nn.initializers.normal(stddev=self.config.initializer_range)
588
+ self.embed_tokens = nn.Embed(
589
+ self.config.vocab_size,
590
+ self.hidden_size,
591
+ embedding_init=embedding_init,
592
+ dtype=self.dtype,
593
+ )
594
+ self.layers = FlaxLlamaLayerCollection(self.config, dtype=self.dtype)
595
+ self.norm = FlaxLlamaRMSNorm(self.config, dtype=self.dtype)
596
+
597
+ def __call__(
598
+ self,
599
+ input_ids,
600
+ attention_mask=None,
601
+ position_ids=None,
602
+ deterministic=True,
603
+ init_cache: bool = False,
604
+ output_attentions: bool = False,
605
+ output_hidden_states: bool = False,
606
+ return_dict: bool = True,
607
+ ):
608
+ input_embeds = self.embed_tokens(input_ids.astype("i4"))
609
+
610
+ outputs = self.layers(
611
+ input_embeds,
612
+ position_ids=position_ids,
613
+ attention_mask=attention_mask,
614
+ deterministic=deterministic,
615
+ init_cache=init_cache,
616
+ output_attentions=output_attentions,
617
+ output_hidden_states=output_hidden_states,
618
+ return_dict=return_dict,
619
+ )
620
+
621
+ hidden_states = outputs[0]
622
+ hidden_states = self.norm(hidden_states)
623
+
624
+ if output_hidden_states:
625
+ all_hidden_states = outputs[1] + (hidden_states,)
626
+ outputs = (hidden_states, all_hidden_states) + outputs[2:]
627
+ else:
628
+ outputs = (hidden_states,) + outputs[1:]
629
+
630
+ if not return_dict:
631
+ return tuple(v for v in outputs if v is not None)
632
+
633
+ return FlaxBaseModelOutput(
634
+ last_hidden_state=hidden_states,
635
+ hidden_states=outputs[1],
636
+ attentions=outputs[-1],
637
+ )
638
+
639
+
640
+ @add_start_docstrings(
641
+ "The bare Llama Model transformer outputting raw hidden-states without any specific head on top.",
642
+ LLAMA_START_DOCSTRING,
643
+ )
644
+ class FlaxLlamaModel(FlaxLlamaPreTrainedModel):
645
+ module_class = FlaxLlamaModule
646
+
647
+
648
+ append_call_sample_docstring(
649
+ FlaxLlamaModel,
650
+ _CHECKPOINT_FOR_DOC,
651
+ FlaxBaseModelOutput,
652
+ _CONFIG_FOR_DOC,
653
+ real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
654
+ )
655
+
656
+
657
+ class FlaxLlamaForCausalLMModule(nn.Module):
658
+ config: LlamaConfig
659
+ dtype: jnp.dtype = jnp.float32
660
+
661
+ def setup(self):
662
+ self.model = FlaxLlamaModule(self.config, dtype=self.dtype)
663
+ self.lm_head = nn.Dense(
664
+ self.config.vocab_size,
665
+ use_bias=False,
666
+ dtype=self.dtype,
667
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
668
+ )
669
+
670
+ def __call__(
671
+ self,
672
+ input_ids,
673
+ attention_mask=None,
674
+ position_ids=None,
675
+ deterministic: bool = True,
676
+ init_cache: bool = False,
677
+ output_attentions: bool = False,
678
+ output_hidden_states: bool = False,
679
+ return_dict: bool = True,
680
+ ):
681
+ outputs = self.model(
682
+ input_ids,
683
+ position_ids=position_ids,
684
+ attention_mask=attention_mask,
685
+ deterministic=deterministic,
686
+ init_cache=init_cache,
687
+ output_attentions=output_attentions,
688
+ output_hidden_states=output_hidden_states,
689
+ return_dict=return_dict,
690
+ )
691
+
692
+ hidden_states = outputs[0]
693
+ lm_logits = self.lm_head(hidden_states)
694
+
695
+ if not return_dict:
696
+ return (lm_logits,) + outputs[1:]
697
+
698
+ return FlaxCausalLMOutput(logits=lm_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
699
+
700
+
701
+ @add_start_docstrings(
702
+ """
703
+ The Llama Model transformer with a language modeling head (linear layer) on top.
704
+ """,
705
+ LLAMA_START_DOCSTRING,
706
+ )
707
+ # Copied from transformers.models.gptj.modeling_flax_gptj.FlaxGPTJForCausalLM with GPTJ->Llama
708
+ class FlaxLlamaForCausalLM(FlaxLlamaPreTrainedModel):
709
+ module_class = FlaxLlamaForCausalLMModule
710
+
711
+ def prepare_inputs_for_generation(self, input_ids, max_length, attention_mask: Optional[jax.Array] = None):
712
+ # initializing the cache
713
+ batch_size, seq_length = input_ids.shape
714
+
715
+ past_key_values = self.init_cache(batch_size, max_length)
716
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
717
+ # But since Llama uses a causal mask, those positions are masked anyways.
718
+ # Thus we can create a single static attention_mask here, which is more efficient for compilation
719
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
720
+ if attention_mask is not None:
721
+ position_ids = attention_mask.cumsum(axis=-1) - 1
722
+ extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, attention_mask, (0, 0))
723
+ else:
724
+ position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
725
+
726
+ return {
727
+ "past_key_values": past_key_values,
728
+ "attention_mask": extended_attention_mask,
729
+ "position_ids": position_ids,
730
+ }
731
+
732
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
733
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
734
+ model_kwargs["position_ids"] = model_kwargs["position_ids"][:, -1:] + 1
735
+ return model_kwargs
736
+
737
+
738
+ append_call_sample_docstring(
739
+ FlaxLlamaForCausalLM,
740
+ _CHECKPOINT_FOR_DOC,
741
+ FlaxCausalLMOutput,
742
+ _CONFIG_FOR_DOC,
743
+ real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
744
+ )
745
+
746
+
747
+ __all__ = ["FlaxLlamaForCausalLM", "FlaxLlamaModel", "FlaxLlamaPreTrainedModel"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama/modeling_llama.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ from typing import Callable, Optional, Union
21
+
22
+ import torch
23
+ from torch import nn
24
+
25
+ from ...activations import ACT2FN
26
+ from ...cache_utils import Cache, DynamicCache
27
+ from ...generation import GenerationMixin
28
+ from ...integrations import use_kernel_forward_from_hub
29
+ from ...masking_utils import create_causal_mask
30
+ from ...modeling_layers import (
31
+ GenericForQuestionAnswering,
32
+ GenericForSequenceClassification,
33
+ GenericForTokenClassification,
34
+ GradientCheckpointingLayer,
35
+ )
36
+ from ...modeling_outputs import (
37
+ BaseModelOutputWithPast,
38
+ CausalLMOutputWithPast,
39
+ )
40
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
41
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
42
+ from ...processing_utils import Unpack
43
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
44
+ from ...utils.deprecation import deprecate_kwarg
45
+ from ...utils.generic import check_model_inputs
46
+ from .configuration_llama import LlamaConfig
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+
52
+ @use_kernel_forward_from_hub("RMSNorm")
53
+ class LlamaRMSNorm(nn.Module):
54
+ def __init__(self, hidden_size, eps=1e-6):
55
+ """
56
+ LlamaRMSNorm is equivalent to T5LayerNorm
57
+ """
58
+ super().__init__()
59
+ self.weight = nn.Parameter(torch.ones(hidden_size))
60
+ self.variance_epsilon = eps
61
+
62
+ def forward(self, hidden_states):
63
+ input_dtype = hidden_states.dtype
64
+ hidden_states = hidden_states.to(torch.float32)
65
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
66
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
67
+ return self.weight * hidden_states.to(input_dtype)
68
+
69
+ def extra_repr(self):
70
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
71
+
72
+
73
+ class LlamaRotaryEmbedding(nn.Module):
74
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
75
+
76
+ def __init__(self, config: LlamaConfig, device=None):
77
+ super().__init__()
78
+ # BC: "rope_type" was originally "type"
79
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
80
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
81
+ else:
82
+ self.rope_type = "default"
83
+ self.max_seq_len_cached = config.max_position_embeddings
84
+ self.original_max_seq_len = config.max_position_embeddings
85
+
86
+ self.config = config
87
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
88
+
89
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
90
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
91
+ self.original_inv_freq = self.inv_freq
92
+
93
+ @torch.no_grad()
94
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
95
+ def forward(self, x, position_ids):
96
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
97
+ position_ids_expanded = position_ids[:, None, :].float()
98
+
99
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
100
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
101
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
102
+ emb = torch.cat((freqs, freqs), dim=-1)
103
+ cos = emb.cos() * self.attention_scaling
104
+ sin = emb.sin() * self.attention_scaling
105
+
106
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
107
+
108
+
109
+ def rotate_half(x):
110
+ """Rotates half the hidden dims of the input."""
111
+ x1 = x[..., : x.shape[-1] // 2]
112
+ x2 = x[..., x.shape[-1] // 2 :]
113
+ return torch.cat((-x2, x1), dim=-1)
114
+
115
+
116
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
117
+ """Applies Rotary Position Embedding to the query and key tensors.
118
+
119
+ Args:
120
+ q (`torch.Tensor`): The query tensor.
121
+ k (`torch.Tensor`): The key tensor.
122
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
123
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
124
+ position_ids (`torch.Tensor`, *optional*):
125
+ Deprecated and unused.
126
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
127
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
128
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
129
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
130
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
131
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
132
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
133
+ Returns:
134
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
135
+ """
136
+ cos = cos.unsqueeze(unsqueeze_dim)
137
+ sin = sin.unsqueeze(unsqueeze_dim)
138
+ q_embed = (q * cos) + (rotate_half(q) * sin)
139
+ k_embed = (k * cos) + (rotate_half(k) * sin)
140
+ return q_embed, k_embed
141
+
142
+
143
+ class LlamaMLP(nn.Module):
144
+ def __init__(self, config):
145
+ super().__init__()
146
+ self.config = config
147
+ self.hidden_size = config.hidden_size
148
+ self.intermediate_size = config.intermediate_size
149
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
150
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
151
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
152
+ self.act_fn = ACT2FN[config.hidden_act]
153
+
154
+ def forward(self, x):
155
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
156
+ return down_proj
157
+
158
+
159
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
160
+ """
161
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
162
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
163
+ """
164
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
165
+ if n_rep == 1:
166
+ return hidden_states
167
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
168
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
169
+
170
+
171
+ def eager_attention_forward(
172
+ module: nn.Module,
173
+ query: torch.Tensor,
174
+ key: torch.Tensor,
175
+ value: torch.Tensor,
176
+ attention_mask: Optional[torch.Tensor],
177
+ scaling: float,
178
+ dropout: float = 0.0,
179
+ **kwargs: Unpack[TransformersKwargs],
180
+ ):
181
+ key_states = repeat_kv(key, module.num_key_value_groups)
182
+ value_states = repeat_kv(value, module.num_key_value_groups)
183
+
184
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
185
+ if attention_mask is not None:
186
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
187
+ attn_weights = attn_weights + causal_mask
188
+
189
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
190
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
191
+ attn_output = torch.matmul(attn_weights, value_states)
192
+ attn_output = attn_output.transpose(1, 2).contiguous()
193
+
194
+ return attn_output, attn_weights
195
+
196
+
197
+ class LlamaAttention(nn.Module):
198
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
199
+
200
+ def __init__(self, config: LlamaConfig, layer_idx: int):
201
+ super().__init__()
202
+ self.config = config
203
+ self.layer_idx = layer_idx
204
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
205
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
206
+ self.scaling = self.head_dim**-0.5
207
+ self.attention_dropout = config.attention_dropout
208
+ self.is_causal = True
209
+
210
+ self.q_proj = nn.Linear(
211
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
212
+ )
213
+ self.k_proj = nn.Linear(
214
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
215
+ )
216
+ self.v_proj = nn.Linear(
217
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
218
+ )
219
+ self.o_proj = nn.Linear(
220
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
221
+ )
222
+
223
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
224
+ def forward(
225
+ self,
226
+ hidden_states: torch.Tensor,
227
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
228
+ attention_mask: Optional[torch.Tensor],
229
+ past_key_values: Optional[Cache] = None,
230
+ cache_position: Optional[torch.LongTensor] = None,
231
+ **kwargs: Unpack[TransformersKwargs],
232
+ ) -> tuple[torch.Tensor, torch.Tensor]:
233
+ input_shape = hidden_states.shape[:-1]
234
+ hidden_shape = (*input_shape, -1, self.head_dim)
235
+
236
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
237
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
238
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
239
+
240
+ cos, sin = position_embeddings
241
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
242
+
243
+ if past_key_values is not None:
244
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
245
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
246
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
247
+
248
+ attention_interface: Callable = eager_attention_forward
249
+ if self.config._attn_implementation != "eager":
250
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
251
+
252
+ attn_output, attn_weights = attention_interface(
253
+ self,
254
+ query_states,
255
+ key_states,
256
+ value_states,
257
+ attention_mask,
258
+ dropout=0.0 if not self.training else self.attention_dropout,
259
+ scaling=self.scaling,
260
+ **kwargs,
261
+ )
262
+
263
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
264
+ attn_output = self.o_proj(attn_output)
265
+ return attn_output, attn_weights
266
+
267
+
268
+ class LlamaDecoderLayer(GradientCheckpointingLayer):
269
+ def __init__(self, config: LlamaConfig, layer_idx: int):
270
+ super().__init__()
271
+ self.hidden_size = config.hidden_size
272
+
273
+ self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
274
+
275
+ self.mlp = LlamaMLP(config)
276
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
277
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
278
+
279
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
280
+ def forward(
281
+ self,
282
+ hidden_states: torch.Tensor,
283
+ attention_mask: Optional[torch.Tensor] = None,
284
+ position_ids: Optional[torch.LongTensor] = None,
285
+ past_key_values: Optional[Cache] = None,
286
+ use_cache: Optional[bool] = False,
287
+ cache_position: Optional[torch.LongTensor] = None,
288
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
289
+ **kwargs: Unpack[TransformersKwargs],
290
+ ) -> torch.Tensor:
291
+ residual = hidden_states
292
+ hidden_states = self.input_layernorm(hidden_states)
293
+ # Self Attention
294
+ hidden_states, _ = self.self_attn(
295
+ hidden_states=hidden_states,
296
+ attention_mask=attention_mask,
297
+ position_ids=position_ids,
298
+ past_key_values=past_key_values,
299
+ use_cache=use_cache,
300
+ cache_position=cache_position,
301
+ position_embeddings=position_embeddings,
302
+ **kwargs,
303
+ )
304
+ hidden_states = residual + hidden_states
305
+
306
+ # Fully Connected
307
+ residual = hidden_states
308
+ hidden_states = self.post_attention_layernorm(hidden_states)
309
+ hidden_states = self.mlp(hidden_states)
310
+ hidden_states = residual + hidden_states
311
+ return hidden_states
312
+
313
+
314
+ @auto_docstring
315
+ class LlamaPreTrainedModel(PreTrainedModel):
316
+ config: LlamaConfig
317
+ base_model_prefix = "model"
318
+ supports_gradient_checkpointing = True
319
+ _no_split_modules = ["LlamaDecoderLayer"]
320
+ _skip_keys_device_placement = ["past_key_values"]
321
+ _supports_flash_attn = True
322
+ _supports_sdpa = True
323
+ _supports_flex_attn = True
324
+
325
+ _can_compile_fullgraph = True
326
+ _supports_attention_backend = True
327
+ _can_record_outputs = {
328
+ "hidden_states": LlamaDecoderLayer,
329
+ "attentions": LlamaAttention,
330
+ }
331
+
332
+
333
+ @auto_docstring
334
+ class LlamaModel(LlamaPreTrainedModel):
335
+ def __init__(self, config: LlamaConfig):
336
+ super().__init__(config)
337
+ self.padding_idx = config.pad_token_id
338
+ self.vocab_size = config.vocab_size
339
+
340
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
341
+ self.layers = nn.ModuleList(
342
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
343
+ )
344
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
345
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
346
+ self.gradient_checkpointing = False
347
+
348
+ # Initialize weights and apply final processing
349
+ self.post_init()
350
+
351
+ @check_model_inputs
352
+ @auto_docstring
353
+ def forward(
354
+ self,
355
+ input_ids: Optional[torch.LongTensor] = None,
356
+ attention_mask: Optional[torch.Tensor] = None,
357
+ position_ids: Optional[torch.LongTensor] = None,
358
+ past_key_values: Optional[Cache] = None,
359
+ inputs_embeds: Optional[torch.FloatTensor] = None,
360
+ cache_position: Optional[torch.LongTensor] = None,
361
+ use_cache: Optional[bool] = None,
362
+ **kwargs: Unpack[TransformersKwargs],
363
+ ) -> BaseModelOutputWithPast:
364
+ if (input_ids is None) ^ (inputs_embeds is not None):
365
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
366
+
367
+ if inputs_embeds is None:
368
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
369
+
370
+ if use_cache and past_key_values is None:
371
+ past_key_values = DynamicCache(config=self.config)
372
+
373
+ if cache_position is None:
374
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
375
+ cache_position: torch.Tensor = torch.arange(
376
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
377
+ )
378
+
379
+ if position_ids is None:
380
+ position_ids = cache_position.unsqueeze(0)
381
+
382
+ causal_mask = create_causal_mask(
383
+ config=self.config,
384
+ input_embeds=inputs_embeds,
385
+ attention_mask=attention_mask,
386
+ cache_position=cache_position,
387
+ past_key_values=past_key_values,
388
+ position_ids=position_ids,
389
+ )
390
+
391
+ hidden_states = inputs_embeds
392
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
393
+
394
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
395
+ hidden_states = decoder_layer(
396
+ hidden_states,
397
+ attention_mask=causal_mask,
398
+ position_ids=position_ids,
399
+ past_key_values=past_key_values,
400
+ cache_position=cache_position,
401
+ position_embeddings=position_embeddings,
402
+ **kwargs,
403
+ )
404
+
405
+ hidden_states = self.norm(hidden_states)
406
+ return BaseModelOutputWithPast(
407
+ last_hidden_state=hidden_states,
408
+ past_key_values=past_key_values,
409
+ )
410
+
411
+
412
+ @auto_docstring
413
+ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
414
+ _tied_weights_keys = ["lm_head.weight"]
415
+ _tp_plan = {"lm_head": "colwise_rep"}
416
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
417
+
418
+ def __init__(self, config):
419
+ super().__init__(config)
420
+ self.model = LlamaModel(config)
421
+ self.vocab_size = config.vocab_size
422
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
423
+
424
+ # Initialize weights and apply final processing
425
+ self.post_init()
426
+
427
+ def set_decoder(self, decoder):
428
+ self.model = decoder
429
+
430
+ def get_decoder(self):
431
+ return self.model
432
+
433
+ @can_return_tuple
434
+ @auto_docstring
435
+ def forward(
436
+ self,
437
+ input_ids: Optional[torch.LongTensor] = None,
438
+ attention_mask: Optional[torch.Tensor] = None,
439
+ position_ids: Optional[torch.LongTensor] = None,
440
+ past_key_values: Optional[Cache] = None,
441
+ inputs_embeds: Optional[torch.FloatTensor] = None,
442
+ labels: Optional[torch.LongTensor] = None,
443
+ use_cache: Optional[bool] = None,
444
+ cache_position: Optional[torch.LongTensor] = None,
445
+ logits_to_keep: Union[int, torch.Tensor] = 0,
446
+ **kwargs: Unpack[TransformersKwargs],
447
+ ) -> CausalLMOutputWithPast:
448
+ r"""
449
+ Example:
450
+
451
+ ```python
452
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
453
+
454
+ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
455
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
456
+
457
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
458
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
459
+
460
+ >>> # Generate
461
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
462
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
463
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
464
+ ```"""
465
+ outputs: BaseModelOutputWithPast = self.model(
466
+ input_ids=input_ids,
467
+ attention_mask=attention_mask,
468
+ position_ids=position_ids,
469
+ past_key_values=past_key_values,
470
+ inputs_embeds=inputs_embeds,
471
+ use_cache=use_cache,
472
+ cache_position=cache_position,
473
+ **kwargs,
474
+ )
475
+
476
+ hidden_states = outputs.last_hidden_state
477
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
478
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
479
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
480
+
481
+ loss = None
482
+ if labels is not None:
483
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
484
+
485
+ return CausalLMOutputWithPast(
486
+ loss=loss,
487
+ logits=logits,
488
+ past_key_values=outputs.past_key_values,
489
+ hidden_states=outputs.hidden_states,
490
+ attentions=outputs.attentions,
491
+ )
492
+
493
+
494
+ class LlamaForSequenceClassification(GenericForSequenceClassification, LlamaPreTrainedModel): ...
495
+
496
+
497
+ class LlamaForQuestionAnswering(GenericForQuestionAnswering, LlamaPreTrainedModel):
498
+ base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
499
+
500
+
501
+ class LlamaForTokenClassification(GenericForTokenClassification, LlamaPreTrainedModel): ...
502
+
503
+
504
+ __all__ = [
505
+ "LlamaForCausalLM",
506
+ "LlamaModel",
507
+ "LlamaPreTrainedModel",
508
+ "LlamaForSequenceClassification",
509
+ "LlamaForQuestionAnswering",
510
+ "LlamaForTokenClassification",
511
+ ]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama/tokenization_llama.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ """Tokenization classes for LLaMA."""
22
+
23
+ import os
24
+ from shutil import copyfile
25
+ from typing import TYPE_CHECKING, Any, Optional
26
+
27
+ import sentencepiece as spm
28
+
29
+ from ...convert_slow_tokenizer import import_protobuf
30
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
31
+ from ...utils import logging
32
+ from ...utils.import_utils import requires
33
+
34
+
35
+ if TYPE_CHECKING:
36
+ from ...tokenization_utils_base import TextInput
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
41
+
42
+ SPIECE_UNDERLINE = "▁"
43
+
44
+ B_INST, E_INST = "[INST]", "[/INST]"
45
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
46
+
47
+ DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
48
+ answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
49
+ that your responses are socially unbiased and positive in nature.
50
+
51
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
52
+ correct. If you don't know the answer to a question, please don't share false information.""" # fmt: skip
53
+
54
+
55
+ @requires(backends=("sentencepiece",))
56
+ class LlamaTokenizer(PreTrainedTokenizer):
57
+ """
58
+ Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
59
+ no padding token in the original model.
60
+
61
+ Args:
62
+ vocab_file (`str`):
63
+ Path to the vocabulary file.
64
+ unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
65
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
66
+ token instead.
67
+ bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<s>"`):
68
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
69
+ eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"</s>"`):
70
+ The end of sequence token.
71
+ pad_token (`str` or `tokenizers.AddedToken`, *optional*):
72
+ A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
73
+ attention mechanisms or loss computation.
74
+ sp_model_kwargs (`dict[str, Any]`, `Optional`, *optional*):
75
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
76
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
77
+ to set:
78
+
79
+ - `enable_sampling`: Enable subword regularization.
80
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
81
+
82
+ - `nbest_size = {0,1}`: No sampling is performed.
83
+ - `nbest_size > 1`: samples from the nbest_size results.
84
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
85
+ using forward-filtering-and-backward-sampling algorithm.
86
+
87
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
88
+ BPE-dropout.
89
+
90
+ add_bos_token (`bool`, *optional*, defaults to `True`):
91
+ Whether or not to add an `bos_token` at the start of sequences.
92
+ add_eos_token (`bool`, *optional*, defaults to `False`):
93
+ Whether or not to add an `eos_token` at the end of sequences.
94
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
95
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
96
+ extra spaces.
97
+ use_default_system_prompt (`bool`, *optional*, defaults to `False`):
98
+ Whether or not the default system prompt for Llama should be used.
99
+ spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):
100
+ Whether or not to add spaces between special tokens.
101
+ legacy (`bool`, *optional*):
102
+ Whether or not the `legacy` behavior of the tokenizer should be used. Legacy is before the merge of #24622
103
+ and #25224 which includes fixes to properly handle tokens that appear after special tokens.
104
+ Make sure to also set `from_slow` to `True`.
105
+ A simple example:
106
+
107
+ - `legacy=True`:
108
+ ```python
109
+ >>> from transformers import LlamaTokenizerFast
110
+
111
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b", legacy=True, from_slow=True)
112
+ >>> tokenizer.encode("Hello <s>.") # 869 is '▁.'
113
+ [1, 15043, 29871, 1, 869]
114
+ ```
115
+ - `legacy=False`:
116
+ ```python
117
+ >>> from transformers import LlamaTokenizerFast
118
+
119
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b", legacy=False, from_slow=True)
120
+ >>> tokenizer.encode("Hello <s>.") # 29889 is '.'
121
+ [1, 15043, 29871, 1, 29889]
122
+ ```
123
+ Checkout the [pull request](https://github.com/huggingface/transformers/pull/24565) for more details.
124
+ add_prefix_space (`bool`, *optional*, defaults to `True`):
125
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
126
+ other word. Again, this should be set with `from_slow=True` to make sure it's taken into account.
127
+ """
128
+
129
+ vocab_files_names = VOCAB_FILES_NAMES
130
+ model_input_names = ["input_ids", "attention_mask"]
131
+
132
+ def __init__(
133
+ self,
134
+ vocab_file,
135
+ unk_token="<unk>",
136
+ bos_token="<s>",
137
+ eos_token="</s>",
138
+ pad_token=None,
139
+ sp_model_kwargs: Optional[dict[str, Any]] = None,
140
+ add_bos_token=True,
141
+ add_eos_token=False,
142
+ clean_up_tokenization_spaces=False,
143
+ use_default_system_prompt=False,
144
+ spaces_between_special_tokens=False,
145
+ legacy=None,
146
+ add_prefix_space=True,
147
+ **kwargs,
148
+ ):
149
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
150
+ bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
151
+ eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
152
+ unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
153
+ pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token
154
+
155
+ if legacy is None:
156
+ logger.warning_once(
157
+ f"You are using the default legacy behaviour of the {self.__class__}. This is"
158
+ " expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you."
159
+ " If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it"
160
+ " means, and thoroughly read the reason why this was added as explained in"
161
+ " https://github.com/huggingface/transformers/pull/24565 - if you loaded a llama tokenizer from a GGUF file"
162
+ " you can ignore this message"
163
+ )
164
+ legacy = True
165
+
166
+ self.legacy = legacy
167
+ self.vocab_file = vocab_file
168
+ self.add_bos_token = add_bos_token
169
+ self.add_eos_token = add_eos_token
170
+ self.use_default_system_prompt = use_default_system_prompt
171
+ self.sp_model = self.get_spm_processor(kwargs.pop("from_slow", False))
172
+ self.add_prefix_space = add_prefix_space
173
+
174
+ super().__init__(
175
+ bos_token=bos_token,
176
+ eos_token=eos_token,
177
+ unk_token=unk_token,
178
+ pad_token=pad_token,
179
+ add_bos_token=add_bos_token,
180
+ add_eos_token=add_eos_token,
181
+ sp_model_kwargs=self.sp_model_kwargs,
182
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
183
+ use_default_system_prompt=use_default_system_prompt,
184
+ spaces_between_special_tokens=spaces_between_special_tokens,
185
+ legacy=legacy,
186
+ add_prefix_space=add_prefix_space,
187
+ **kwargs,
188
+ )
189
+
190
+ @property
191
+ def unk_token_length(self):
192
+ return len(self.sp_model.encode(str(self.unk_token)))
193
+
194
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_spm_processor
195
+ def get_spm_processor(self, from_slow=False):
196
+ tokenizer = spm.SentencePieceProcessor(**self.sp_model_kwargs)
197
+ if self.legacy or from_slow: # no dependency on protobuf
198
+ tokenizer.Load(self.vocab_file)
199
+ return tokenizer
200
+
201
+ with open(self.vocab_file, "rb") as f:
202
+ sp_model = f.read()
203
+ model_pb2 = import_protobuf(f"The new behaviour of {self.__class__.__name__} (with `self.legacy = False`)")
204
+ model = model_pb2.ModelProto.FromString(sp_model)
205
+ normalizer_spec = model_pb2.NormalizerSpec()
206
+ normalizer_spec.add_dummy_prefix = False
207
+ model.normalizer_spec.MergeFrom(normalizer_spec)
208
+ sp_model = model.SerializeToString()
209
+ tokenizer.LoadFromSerializedProto(sp_model)
210
+ return tokenizer
211
+
212
+ def __getstate__(self):
213
+ state = self.__dict__.copy()
214
+ state["sp_model"] = None
215
+ state["sp_model_proto"] = self.sp_model.serialized_model_proto()
216
+ return state
217
+
218
+ def __setstate__(self, d):
219
+ self.__dict__.update(d)
220
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
221
+ self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
222
+
223
+ @property
224
+ def vocab_size(self):
225
+ """Returns vocab size"""
226
+ return self.sp_model.get_piece_size()
227
+
228
+ def get_vocab(self):
229
+ """Returns vocab as a dict"""
230
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
231
+ vocab.update(self.added_tokens_encoder)
232
+ return vocab
233
+
234
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.tokenize
235
+ def tokenize(self, text: "TextInput", **kwargs) -> list[str]:
236
+ """
237
+ Converts a string to a list of tokens. If `self.legacy` is set to `False`, a prefix token is added unless the
238
+ first token is special.
239
+ """
240
+ if self.legacy or len(text) == 0:
241
+ return super().tokenize(text, **kwargs)
242
+
243
+ text = text.replace(SPIECE_UNDERLINE, " ")
244
+ if self.add_prefix_space:
245
+ text = SPIECE_UNDERLINE + text
246
+
247
+ tokens = super().tokenize(text, **kwargs)
248
+
249
+ if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:
250
+ tokens = tokens[1:]
251
+ return tokens
252
+
253
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._tokenize
254
+ def _tokenize(self, text, **kwargs):
255
+ """
256
+ Returns a tokenized string.
257
+
258
+ We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any
259
+ SPIECE_UNDERLINE. For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give
260
+ `['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f"{unk_token}text"` and strip the
261
+ `unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`.
262
+ `self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`.
263
+ """
264
+ if self.legacy or not text.startswith((SPIECE_UNDERLINE, " ")):
265
+ return self.sp_model.encode(text, out_type=str)
266
+
267
+ # 1. Encode string + prefix ex: "<unk> Hey"
268
+ tokens = self.sp_model.encode(self.unk_token + text, out_type=str)
269
+ # 2. Remove self.unk_token from ['<','unk','>', '▁Hey']
270
+ return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens
271
+
272
+ def _convert_token_to_id(self, token):
273
+ """Converts a token (str) in an id using the vocab."""
274
+ return self.sp_model.piece_to_id(token)
275
+
276
+ def _convert_id_to_token(self, index):
277
+ """Converts an index (integer) in a token (str) using the vocab."""
278
+ token = self.sp_model.IdToPiece(index)
279
+ return token
280
+
281
+ def convert_tokens_to_string(self, tokens):
282
+ """Converts a sequence of tokens (string) in a single string."""
283
+ # since we manually add the prefix space, we have to remove it when decoding
284
+ if tokens[0].startswith(SPIECE_UNDERLINE) and self.add_prefix_space:
285
+ tokens[0] = tokens[0][1:]
286
+
287
+ current_sub_tokens = []
288
+ out_string = ""
289
+ prev_is_special = False
290
+ for i, token in enumerate(tokens):
291
+ # make sure that special tokens are not decoded using sentencepiece model
292
+ if token in self.all_special_tokens:
293
+ if not prev_is_special and i != 0 and self.legacy:
294
+ out_string += " "
295
+ out_string += self.sp_model.decode(current_sub_tokens) + token
296
+ prev_is_special = True
297
+ current_sub_tokens = []
298
+ else:
299
+ if prev_is_special and i == 1 and self.add_prefix_space and not token.startswith(SPIECE_UNDERLINE):
300
+ out_string += " "
301
+ current_sub_tokens.append(token)
302
+ prev_is_special = False
303
+ out_string += self.sp_model.decode(current_sub_tokens)
304
+ return out_string
305
+
306
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> tuple[str]:
307
+ """
308
+ Save the vocabulary and special tokens file to a directory.
309
+
310
+ Args:
311
+ save_directory (`str`):
312
+ The directory in which to save the vocabulary.
313
+
314
+ Returns:
315
+ `Tuple(str)`: Paths to the files saved.
316
+ """
317
+ if not os.path.isdir(save_directory):
318
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
319
+ return
320
+ out_vocab_file = os.path.join(
321
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
322
+ )
323
+
324
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
325
+ copyfile(self.vocab_file, out_vocab_file)
326
+ elif not os.path.isfile(self.vocab_file):
327
+ with open(out_vocab_file, "wb") as fi:
328
+ content_spiece_model = self.sp_model.serialized_model_proto()
329
+ fi.write(content_spiece_model)
330
+
331
+ return (out_vocab_file,)
332
+
333
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
334
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
335
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
336
+
337
+ output = bos_token_id + token_ids_0 + eos_token_id
338
+
339
+ if token_ids_1 is not None:
340
+ output = output + bos_token_id + token_ids_1 + eos_token_id
341
+
342
+ return output
343
+
344
+ def get_special_tokens_mask(
345
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
346
+ ) -> list[int]:
347
+ """
348
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
349
+ special tokens using the tokenizer `prepare_for_model` method.
350
+
351
+ Args:
352
+ token_ids_0 (`list[int]`):
353
+ List of IDs.
354
+ token_ids_1 (`list[int]`, *optional*):
355
+ Optional second list of IDs for sequence pairs.
356
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
357
+ Whether or not the token list is already formatted with special tokens for the model.
358
+
359
+ Returns:
360
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
361
+ """
362
+ if already_has_special_tokens:
363
+ return super().get_special_tokens_mask(
364
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
365
+ )
366
+
367
+ bos_token_id = [1] if self.add_bos_token else []
368
+ eos_token_id = [1] if self.add_eos_token else []
369
+
370
+ if token_ids_1 is None:
371
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
372
+ return (
373
+ bos_token_id
374
+ + ([0] * len(token_ids_0))
375
+ + eos_token_id
376
+ + bos_token_id
377
+ + ([0] * len(token_ids_1))
378
+ + eos_token_id
379
+ )
380
+
381
+ def create_token_type_ids_from_sequences(
382
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
383
+ ) -> list[int]:
384
+ """
385
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
386
+ sequence pair mask has the following format:
387
+
388
+ ```
389
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
390
+ | first sequence | second sequence |
391
+ ```
392
+
393
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
394
+
395
+ Args:
396
+ token_ids_0 (`list[int]`):
397
+ List of ids.
398
+ token_ids_1 (`list[int]`, *optional*):
399
+ Optional second list of IDs for sequence pairs.
400
+
401
+ Returns:
402
+ `list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
403
+ """
404
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
405
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
406
+
407
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
408
+
409
+ if token_ids_1 is not None:
410
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
411
+
412
+ return output
413
+
414
+
415
+ __all__ = ["LlamaTokenizer"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama/tokenization_llama_fast.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import os
16
+ from shutil import copyfile
17
+ from typing import Optional
18
+
19
+ from tokenizers import processors
20
+
21
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
22
+ from ...utils import is_sentencepiece_available, logging
23
+
24
+
25
+ if is_sentencepiece_available():
26
+ from .tokenization_llama import LlamaTokenizer
27
+ else:
28
+ LlamaTokenizer = None
29
+
30
+ logger = logging.get_logger(__name__)
31
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model", "tokenizer_file": "tokenizer.json"}
32
+
33
+ B_INST, E_INST = "[INST]", "[/INST]"
34
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
35
+
36
+ # fmt: off
37
+ DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
38
+ answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
39
+ that your responses are socially unbiased and positive in nature.
40
+
41
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
42
+ correct. If you don't know the answer to a question, please don't share false information."""
43
+ # fmt: on
44
+
45
+
46
+ class LlamaTokenizerFast(PreTrainedTokenizerFast):
47
+ """
48
+ Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding.
49
+
50
+ This uses notably ByteFallback and no normalization.
51
+
52
+ ```python
53
+ >>> from transformers import LlamaTokenizerFast
54
+
55
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("hf-internal-testing/llama-tokenizer")
56
+ >>> tokenizer.encode("Hello this is a test")
57
+ [1, 15043, 445, 338, 263, 1243]
58
+ ```
59
+
60
+ If you want to change the `bos_token` or the `eos_token`, make sure to specify them when initializing the model, or
61
+ call `tokenizer.update_post_processor()` to make sure that the post-processing is correctly done (otherwise the
62
+ values of the first token and final token of an encoded sequence will not be correct). For more details, checkout
63
+ [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) documentation.
64
+
65
+
66
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
67
+ refer to this superclass for more information regarding those methods.
68
+
69
+ Args:
70
+ vocab_file (`str`, *optional*):
71
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .model extension) that
72
+ contains the vocabulary necessary to instantiate a tokenizer.
73
+ tokenizer_file (`str`, *optional*):
74
+ [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
75
+ contains everything needed to load the tokenizer.
76
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
77
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
78
+ extra spaces.
79
+ unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
80
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
81
+ token instead.
82
+ bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<s>"`):
83
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
84
+ eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"</s>"`):
85
+ The end of sequence token.
86
+ add_bos_token (`bool`, *optional*, defaults to `True`):
87
+ Whether or not to add an `bos_token` at the start of sequences.
88
+ add_eos_token (`bool`, *optional*, defaults to `False`):
89
+ Whether or not to add an `eos_token` at the end of sequences.
90
+ use_default_system_prompt (`bool`, *optional*, defaults to `False`):
91
+ Whether or not the default system prompt for Llama should be used
92
+ legacy (`bool`, *optional*):
93
+ Whether or not the `legacy` behavior of the tokenizer should be used. Legacy is before the merge of #24622
94
+ and #25224 which includes fixes to properly handle tokens that appear after special tokens.
95
+ Make sure to also set `from_slow` to `True`.
96
+ A simple example:
97
+
98
+ - `legacy=True`:
99
+ ```python
100
+ >>> from transformers import LlamaTokenizerFast
101
+
102
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b", legacy=True, from_slow=True)
103
+ >>> tokenizer.encode("Hello <s>.") # 869 is '▁.'
104
+ [1, 15043, 29871, 1, 869]
105
+ ```
106
+ - `legacy=False`:
107
+ ```python
108
+ >>> from transformers import LlamaTokenizerFast
109
+
110
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b", legacy=False, from_slow=True)
111
+ >>> tokenizer.encode("Hello <s>.") # 29889 is '.'
112
+ [1, 15043, 29871, 1, 29889]
113
+ ```
114
+ Checkout the [pull request](https://github.com/huggingface/transformers/pull/24565) for more details.
115
+ add_prefix_space (`bool`, *optional*):
116
+ Whether or not the tokenizer should automatically add a prefix space
117
+ """
118
+
119
+ vocab_files_names = VOCAB_FILES_NAMES
120
+ slow_tokenizer_class = LlamaTokenizer
121
+ padding_side = "left"
122
+ model_input_names = ["input_ids", "attention_mask"]
123
+
124
+ def __init__(
125
+ self,
126
+ vocab_file=None,
127
+ tokenizer_file=None,
128
+ clean_up_tokenization_spaces=False,
129
+ unk_token="<unk>",
130
+ bos_token="<s>",
131
+ eos_token="</s>",
132
+ add_bos_token=True,
133
+ add_eos_token=False,
134
+ use_default_system_prompt=False,
135
+ legacy=None,
136
+ add_prefix_space=None,
137
+ **kwargs,
138
+ ):
139
+ if legacy is None:
140
+ logger.warning_once(
141
+ f"You are using the default legacy behaviour of the {self.__class__}. This is"
142
+ " expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you."
143
+ " If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it"
144
+ " means, and thoroughly read the reason why this was added as explained in"
145
+ " https://github.com/huggingface/transformers/pull/24565 - if you loaded a llama tokenizer from a GGUF file"
146
+ " you can ignore this message."
147
+ )
148
+ legacy = True
149
+ self.legacy = legacy
150
+
151
+ if add_prefix_space is not None:
152
+ kwargs["from_slow"] = True
153
+
154
+ super().__init__(
155
+ vocab_file=vocab_file,
156
+ tokenizer_file=tokenizer_file,
157
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
158
+ unk_token=unk_token,
159
+ bos_token=bos_token,
160
+ eos_token=eos_token,
161
+ add_bos_token=add_bos_token,
162
+ add_eos_token=add_eos_token,
163
+ use_default_system_prompt=use_default_system_prompt,
164
+ add_prefix_space=add_prefix_space,
165
+ legacy=legacy,
166
+ **kwargs,
167
+ )
168
+ self._add_bos_token = add_bos_token
169
+ self._add_eos_token = add_eos_token
170
+ self.update_post_processor()
171
+ self.use_default_system_prompt = use_default_system_prompt
172
+ self.vocab_file = vocab_file
173
+
174
+ def update_post_processor(self):
175
+ """
176
+ Updates the underlying post processor with the current `bos_token` and `eos_token`.
177
+ """
178
+ bos = self.bos_token
179
+ bos_token_id = self.bos_token_id
180
+ if bos is None and self.add_bos_token:
181
+ raise ValueError("add_bos_token = True but bos_token = None")
182
+
183
+ eos = self.eos_token
184
+ eos_token_id = self.eos_token_id
185
+ if eos is None and self.add_eos_token:
186
+ raise ValueError("add_eos_token = True but eos_token = None")
187
+
188
+ single = f"{(bos + ':0 ') if self.add_bos_token else ''}$A:0{(' ' + eos + ':0') if self.add_eos_token else ''}"
189
+ pair = f"{single}{(' ' + bos + ':1') if self.add_bos_token else ''} $B:1{(' ' + eos + ':1') if self.add_eos_token else ''}"
190
+
191
+ special_tokens = []
192
+ if self.add_bos_token:
193
+ special_tokens.append((bos, bos_token_id))
194
+ if self.add_eos_token:
195
+ special_tokens.append((eos, eos_token_id))
196
+ self._tokenizer.post_processor = processors.TemplateProcessing(
197
+ single=single, pair=pair, special_tokens=special_tokens
198
+ )
199
+
200
+ @property
201
+ def add_eos_token(self):
202
+ return self._add_eos_token
203
+
204
+ @property
205
+ def add_bos_token(self):
206
+ return self._add_bos_token
207
+
208
+ @add_eos_token.setter
209
+ def add_eos_token(self, value):
210
+ self._add_eos_token = value
211
+ self.update_post_processor()
212
+
213
+ @add_bos_token.setter
214
+ def add_bos_token(self, value):
215
+ self._add_bos_token = value
216
+ self.update_post_processor()
217
+
218
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
219
+ if not self.can_save_slow_tokenizer:
220
+ raise ValueError(
221
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
222
+ "tokenizer."
223
+ )
224
+
225
+ if not os.path.isdir(save_directory):
226
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
227
+ return
228
+ out_vocab_file = os.path.join(
229
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
230
+ )
231
+
232
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
233
+ copyfile(self.vocab_file, out_vocab_file)
234
+
235
+ return (out_vocab_file,)
236
+
237
+ # TODO ArthurZ let's rely on the template processor instead, refactor all fast tokenizers
238
+ # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.build_inputs_with_special_tokens
239
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
240
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
241
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
242
+
243
+ output = bos_token_id + token_ids_0 + eos_token_id
244
+
245
+ if token_ids_1 is not None:
246
+ output = output + bos_token_id + token_ids_1 + eos_token_id
247
+
248
+ return output
249
+
250
+
251
+ __all__ = ["LlamaTokenizerFast"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama4/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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_llama4 import *
22
+ from .image_processing_llama4_fast import *
23
+ from .modeling_llama4 import *
24
+ from .processing_llama4 import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama4/configuration_llama4.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The LLAMA4 and HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+
18
+ from ...configuration_utils import PretrainedConfig, layer_type_validation
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class Llama4VisionConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`Llama4VisionModel`]. It is used to instantiate a
28
+ Llama4 vision model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of the Llama4 109B.
30
+
31
+ e.g. [meta-llama/Llama-4-Scout-17B-16E](https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E)
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
+ Args:
37
+ hidden_size (`int`, *optional*, defaults to 768):
38
+ Dimensionality of the encoder layers and the pooler layer.
39
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
40
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
41
+ `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
42
+ num_hidden_layers (`int`, *optional*, defaults to 34):
43
+ Number of hidden layers in the Transformer encoder.
44
+ num_attention_heads (`int`, *optional*, defaults to 16):
45
+ Number of attention heads for each attention layer in the Transformer encoder.
46
+ num_channels (`int`, *optional*, defaults to 3):
47
+ Number of channels in the input image.
48
+ intermediate_size (`int`, *optional*, defaults to 5632):
49
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
50
+ vision_output_dim (`int`, *optional*, defaults to 7680):
51
+ Dimensionality of the vision model output. Includes output of transformer
52
+ encoder with intermediate layers and global transformer encoder.
53
+ image_size (`int`, *optional*, defaults to 448):
54
+ The size (resolution) of each image *tile*.
55
+ patch_size (`int`, *optional*, defaults to 14):
56
+ The size (resolution) of each patch.
57
+ norm_eps (`float`, *optional*, defaults to 1e-05):
58
+ The epsilon used by the layer normalization layers.
59
+ vision_feature_layer (``, *optional*, defaults to -1): TODO
60
+ vision_feature_select_strategy (`int`, *optional*, defaults to `"default"`): TODO
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ pixel_shuffle_ratio (`int`, *optional*, defaults to 0.5): TODO
64
+ projector_input_dim (`int`, *optional*, defaults to 4096): TODO
65
+ projector_output_dim (`int`, *optional*, defaults to 4096): TODO
66
+ multi_modal_projector_bias (`int`, *optional*, defaults to `False`): TODO
67
+ projector_dropout (`int`, *optional*, defaults to 0.0): TODO
68
+ attention_dropout (`int`, *optional*, defaults to 0.0): TODO
69
+ rope_theta (`int`, *optional*, defaults to 10000): TODO
70
+ """
71
+
72
+ base_model_tp_plan = {
73
+ "model.layers.*.self_attn.q_proj": "colwise",
74
+ "model.layers.*.self_attn.k_proj": "colwise",
75
+ "model.layers.*.self_attn.v_proj": "colwise",
76
+ "model.layers.*.self_attn.o_proj": "rowwise",
77
+ "vision_adapter.mlp.fc1": "colwise",
78
+ "vision_adapter.mlp.fc2": "rowwise",
79
+ "patch_embedding.linear": "colwise_rep",
80
+ }
81
+ model_type = "llama4_vision_model"
82
+ base_config_key = "vision_config"
83
+
84
+ def __init__(
85
+ self,
86
+ hidden_size: int = 768,
87
+ hidden_act: str = "gelu",
88
+ num_hidden_layers: int = 34,
89
+ num_attention_heads: int = 16,
90
+ num_channels: int = 3,
91
+ intermediate_size: int = 5632,
92
+ vision_output_dim: int = 7680,
93
+ image_size: int = 448,
94
+ patch_size: int = 14,
95
+ norm_eps: float = 1e-5,
96
+ vision_feature_layer=-1,
97
+ vision_feature_select_strategy="default",
98
+ initializer_range: float = 0.02,
99
+ pixel_shuffle_ratio=0.5,
100
+ projector_input_dim=4096,
101
+ projector_output_dim=4096,
102
+ multi_modal_projector_bias=False,
103
+ projector_dropout=0.0,
104
+ attention_dropout=0.0,
105
+ rope_theta=10000,
106
+ **kwargs,
107
+ ):
108
+ self.hidden_size = hidden_size
109
+ self.hidden_act = hidden_act
110
+ self.num_hidden_layers = num_hidden_layers
111
+ self.num_channels = num_channels
112
+ self.intermediate_size = intermediate_size
113
+ self.image_size = image_size
114
+ self.vision_output_dim = vision_output_dim
115
+ self.patch_size = patch_size
116
+ self.norm_eps = norm_eps
117
+ self.num_attention_heads = num_attention_heads
118
+ self.initializer_range = initializer_range
119
+ self.pixel_shuffle_ratio = pixel_shuffle_ratio
120
+ self.projector_input_dim = projector_input_dim
121
+ self.projector_output_dim = projector_output_dim
122
+ self.multi_modal_projector_bias = multi_modal_projector_bias
123
+ self.projector_dropout = projector_dropout
124
+ self.attention_dropout = attention_dropout
125
+ self.vision_feature_layer = vision_feature_layer
126
+ self.vision_feature_select_strategy = vision_feature_select_strategy
127
+ self.rope_theta = rope_theta
128
+ super().__init__(**kwargs)
129
+
130
+
131
+ class Llama4TextConfig(PretrainedConfig):
132
+ r"""
133
+ This is the configuration class to store the configuration of a [`Llama4TextModel`]. It is used to instantiate a
134
+ Llama4 text model according to the specified arguments, defining the model architecture. Instantiating a configuration
135
+ with the defaults will yield a similar configuration to that of the Llama4 109B.
136
+
137
+ e.g. [meta-llama/Llama-4-Scout-17B-16E](https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E)
138
+
139
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
140
+ documentation from [`PretrainedConfig`] for more information.
141
+
142
+ Args:
143
+ vocab_size (`int`, *optional*, defaults to 202048):
144
+ Vocabulary size of the Llama4 text model. Defines the maximum number of different tokens that can be represented
145
+ by the `inputs_ids` passed when calling [`Llama4TextModel`].
146
+ hidden_size (`int`, *optional*, defaults to 5120):
147
+ Dimensionality of the embeddings and hidden states.
148
+ intermediate_size (`int`, *optional*, defaults to 8192):
149
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
150
+ intermediate_size_mlp (`int`, *optional*, defaults to 16384): TODO
151
+ num_hidden_layers (`int`, *optional*, defaults to 48):
152
+ Number of hidden layers in the Transformer encoder.
153
+ num_attention_heads (`int`, *optional*, defaults to 40):
154
+ Number of attention heads for each attention layer in the Transformer encoder.
155
+ num_key_value_heads (`int`, *optional*, defaults to 8):
156
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If not
157
+ specified, will default to `num_attention_heads`.
158
+ head_dim (`int`, *optional*, defaults to 128): TODO
159
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"silu"`):
160
+ The non-linear activation function (function or string) in the encoder and pooler.
161
+ max_position_embeddings (`int`, *optional*, defaults to 131072):
162
+ The maximum sequence length that this model might ever be used with.
163
+ initializer_range (`float`, *optional*, defaults to 0.02):
164
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
165
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
166
+ The epsilon used by the rms normalization layers.
167
+ use_cache (`bool`, *optional*, defaults to `True`):
168
+ Whether or not the model should return the last key/values attentions.
169
+ pad_token_id (`int`, *optional*, defaults to 128004):
170
+ The id of the padding token.
171
+ bos_token_id (`int`, *optional*, defaults to 1):
172
+ The id of the beginning of sentence token.
173
+ eos_token_id (`int`, *optional*, defaults to 2):
174
+ The id of the end of sentence token.
175
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
176
+ Whether to tie weight embeddings
177
+ rope_theta (`float`, *optional*, defaults to `500000.0`):
178
+ The base period of the RoPE embeddings.
179
+ attention_dropout (`int`, *optional*, defaults to 0.0): TODO
180
+ num_experts_per_tok (`int`, *optional*, defaults to 1): TODO
181
+ num_local_experts (`int`, *optional*, defaults to 16): TODO
182
+ moe_layers (`int`, *optional*): TODO
183
+ interleave_moe_layer_step (`int`, *optional*, defaults to 1): TODO
184
+ use_qk_norm (`int`, *optional*, defaults to `True`): TODO
185
+ output_router_logits (`int`, *optional*, defaults to `False`): TODO
186
+ router_aux_loss_coef (`int`, *optional*, defaults to 0.001): TODO
187
+ router_jitter_noise (`int`, *optional*, defaults to 0.0): TODO
188
+ rope_scaling (`Dict`, *optional*):
189
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
190
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
191
+ accordingly.
192
+ Expected contents:
193
+ `rope_type` (`str`):
194
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
195
+ 'llama3'], with 'default' being the original RoPE implementation.
196
+ `factor` (`float`, *optional*):
197
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
198
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
199
+ original maximum pre-trained length.
200
+ `original_max_position_embeddings` (`int`, *optional*):
201
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
202
+ pretraining.
203
+ `attention_factor` (`float`, *optional*):
204
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
205
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
206
+ `factor` field to infer the suggested value.
207
+ `beta_fast` (`float`, *optional*):
208
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
209
+ ramp function. If unspecified, it defaults to 32.
210
+ `beta_slow` (`float`, *optional*):
211
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
212
+ ramp function. If unspecified, it defaults to 1.
213
+ `short_factor` (`list[float]`, *optional*):
214
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
215
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
216
+ size divided by the number of attention heads divided by 2
217
+ `long_factor` (`list[float]`, *optional*):
218
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
219
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
220
+ size divided by the number of attention heads divided by 2
221
+ `low_freq_factor` (`float`, *optional*):
222
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
223
+ `high_freq_factor` (`float`, *optional*):
224
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
225
+ <TODO>
226
+ <TODO>
227
+ no_rope_layers (`list[int]`, *optional*):
228
+ List with at least the same length as the number of layers in the model.
229
+ A `1` at an index position indicates that the corresponding layer will use RoPE,
230
+ while a `0` indicates that it's a NoPE layer.
231
+ no_rope_layer_interval (`int`, *optional*, defaults to 4):
232
+ If `no_rope_layers` is `None`, it will be created using a NoPE layer every
233
+ `no_rope_layer_interval` layers.
234
+ attention_chunk_size (`int`, *optional*, defaults to 8192):
235
+ <TODO>
236
+ layer_types (`list`, *optional*):
237
+ Attention pattern for each layer.
238
+ attn_temperature_tuning (`bool`, *optional*, defaults to `True`):
239
+ Whether to dynamically scale the attention temperature for each query token based on sequence length.
240
+ Recommended for long sequences (e.g., >32k tokens) to maintain stable output results.
241
+ floor_scale (`int`, *optional*, defaults to 8192): TODO
242
+ attn_scale (`int`, *optional*, defaults to 0.1): TODO
243
+
244
+ Example:
245
+ """
246
+
247
+ model_type = "llama4_text"
248
+ keys_to_ignore_at_inference = ["past_key_values"]
249
+ base_model_tp_plan = {
250
+ "layers.*.self_attn.q_proj": "colwise",
251
+ "layers.*.self_attn.k_proj": "colwise",
252
+ "layers.*.self_attn.v_proj": "colwise",
253
+ "layers.*.self_attn.o_proj": "rowwise",
254
+ "layers.*.feed_forward.shared_expert.gate_proj": "local_colwise",
255
+ "layers.*.feed_forward.shared_expert.up_proj": "local_colwise",
256
+ "layers.*.feed_forward.shared_expert.down_proj": "local_rowwise",
257
+ "layers.*.feed_forward.experts.gate_up_proj": "local_packed_rowwise", # row because not linear
258
+ "layers.*.feed_forward.experts.down_proj": "local_colwise", # col because not linear
259
+ "layers.*.feed_forward.experts": "local",
260
+ "layers.*.feed_forward.gate_proj": "local_colwise",
261
+ "layers.*.feed_forward.up_proj": "local_colwise",
262
+ "layers.*.feed_forward.down_proj": "local_rowwise",
263
+ "layers.*.feed_forward": "gather",
264
+ }
265
+ base_model_ep_plan = {
266
+ "layers.*.self_attn.q_proj": "colwise",
267
+ "layers.*.self_attn.k_proj": "colwise",
268
+ "layers.*.self_attn.v_proj": "colwise",
269
+ "layers.*.self_attn.o_proj": "rowwise",
270
+ "layers.*.feed_forward.experts.gate_up_proj": "grouped_gemm", # row because not linear
271
+ "layers.*.feed_forward.experts.down_proj": "grouped_gemm", # col because not linear
272
+ "layers.*.feed_forward.experts": "gather", # all reduce
273
+ "layers.*.feed_forward.gate_proj": "local_colwise",
274
+ "layers.*.feed_forward.up_proj": "local_colwise",
275
+ "layers.*.feed_forward.down_proj": "local_rowwise",
276
+ "layers.*.feed_forward.router": "ep_router",
277
+ }
278
+
279
+ def __init__(
280
+ self,
281
+ vocab_size=202048,
282
+ hidden_size=5120,
283
+ intermediate_size=8192,
284
+ intermediate_size_mlp=16384,
285
+ num_hidden_layers=48,
286
+ num_attention_heads=40,
287
+ num_key_value_heads=8,
288
+ head_dim=128,
289
+ hidden_act="silu",
290
+ max_position_embeddings=4096 * 32,
291
+ initializer_range=0.02,
292
+ rms_norm_eps=1e-5,
293
+ use_cache=True,
294
+ pad_token_id=None,
295
+ bos_token_id=1,
296
+ eos_token_id=2,
297
+ tie_word_embeddings=False,
298
+ rope_theta=500000,
299
+ attention_dropout=0.0,
300
+ num_experts_per_tok=1,
301
+ num_local_experts=16,
302
+ moe_layers=None,
303
+ interleave_moe_layer_step=1,
304
+ use_qk_norm=True,
305
+ output_router_logits=False,
306
+ router_aux_loss_coef=0.001,
307
+ router_jitter_noise=0.0,
308
+ rope_scaling=None,
309
+ no_rope_layers=None,
310
+ no_rope_layer_interval=4,
311
+ attention_chunk_size=8192,
312
+ layer_types=None,
313
+ attn_temperature_tuning=True,
314
+ floor_scale=8192,
315
+ attn_scale=0.1,
316
+ **kwargs,
317
+ ):
318
+ super().__init__(
319
+ pad_token_id=pad_token_id,
320
+ bos_token_id=bos_token_id,
321
+ eos_token_id=eos_token_id,
322
+ tie_word_embeddings=tie_word_embeddings,
323
+ **kwargs,
324
+ )
325
+ self.attn_temperature_tuning = attn_temperature_tuning
326
+ self.attn_scale = attn_scale
327
+ self.floor_scale = floor_scale
328
+ self.vocab_size = vocab_size
329
+ self.max_position_embeddings = max_position_embeddings
330
+ self.hidden_size = hidden_size
331
+ self.intermediate_size = intermediate_size
332
+ self.intermediate_size_mlp = intermediate_size_mlp
333
+ self.num_hidden_layers = num_hidden_layers
334
+ self.num_attention_heads = num_attention_heads
335
+ self.rope_scaling = rope_scaling
336
+ self.attention_bias = False
337
+ # for backward compatibility
338
+ if num_key_value_heads is None:
339
+ num_key_value_heads = num_attention_heads
340
+
341
+ self.num_key_value_heads = num_key_value_heads
342
+ self.hidden_act = hidden_act
343
+ self.initializer_range = initializer_range
344
+ self.rms_norm_eps = rms_norm_eps
345
+ self.use_cache = use_cache
346
+ self.rope_theta = rope_theta
347
+ self.attention_dropout = attention_dropout
348
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
349
+ self.use_qk_norm = use_qk_norm
350
+
351
+ self.num_experts_per_tok = num_experts_per_tok
352
+ self.num_local_experts = num_local_experts
353
+
354
+ self.output_router_logits = output_router_logits
355
+ self.router_aux_loss_coef = router_aux_loss_coef
356
+ self.router_jitter_noise = router_jitter_noise
357
+
358
+ # Backwards compatibility
359
+ if no_rope_layers == []:
360
+ no_rope_layers = None
361
+
362
+ default_no_rope_layers = [
363
+ int((layer_idx + 1) % no_rope_layer_interval != 0) for layer_idx in range(self.num_hidden_layers)
364
+ ]
365
+
366
+ self.no_rope_layers = no_rope_layers if no_rope_layers else default_no_rope_layers
367
+
368
+ self.interleave_moe_layer_step = interleave_moe_layer_step
369
+ self.moe_layers = (
370
+ moe_layers
371
+ if moe_layers is not None
372
+ else list(range(interleave_moe_layer_step - 1, num_hidden_layers, interleave_moe_layer_step))
373
+ )
374
+ self.attention_chunk_size = attention_chunk_size
375
+
376
+ self.layer_types = layer_types
377
+ if layer_types is None:
378
+ self.layer_types = [
379
+ "chunked_attention" if no_rope else "full_attention" for no_rope in self.no_rope_layers
380
+ ]
381
+ layer_type_validation(self.layer_types)
382
+
383
+
384
+ class Llama4Config(PretrainedConfig):
385
+ r"""
386
+ This is the configuration class to store the configuration of a [`Llama4Model`]. It is used to instantiate an
387
+ Llama4 model according to the specified arguments, defining the model architecture. Instantiating a configuration
388
+ with the defaults will yield a similar configuration to that of the Llama4 109B.
389
+
390
+ e.g. [meta-llama/Llama-4-Scout-17B-16E](https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E)
391
+
392
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
393
+ documentation from [`PretrainedConfig`] for more information.
394
+
395
+
396
+ Args:
397
+ vision_config (`Llama4VisionConfig`, *optional*):
398
+ The Llama4 Vision config.
399
+ text_config (`Llama4TextConfig`, *optional*):
400
+ The Llama4 Text config.
401
+ boi_token_index (`int`, *optional*, defaults to 200080):
402
+ The begin-of-image token index to wrap the image prompt.
403
+ eoi_token_index (`int`, *optional*, defaults to 200081):
404
+ The end-of-image token index to wrap the image prompt.
405
+ image_token_index (`int`, *optional*, defaults to 200092):
406
+ The image token index to encode the image prompt.
407
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
408
+ Whether the model's input and output word embeddings should be tied.
409
+
410
+ ```python
411
+ >>> from transformers import Llama4Model, Llama4Config
412
+
413
+ >>> # Initializing a Llama4 7B style configuration
414
+ >>> configuration = Llama4Config()
415
+
416
+ >>> # Initializing a model from the Llama4 7B style configuration
417
+ >>> model = Llama4Model(configuration)
418
+
419
+ >>> # Accessing the model configuration
420
+ >>> configuration = model.config
421
+ ```"""
422
+
423
+ model_type = "llama4"
424
+ attribute_map = {
425
+ "image_token_id": "image_token_index",
426
+ "boi_token_id": "boi_token_index",
427
+ "eoi_token_id": "eoi_token_index",
428
+ }
429
+ sub_configs = {"text_config": Llama4TextConfig, "vision_config": Llama4VisionConfig}
430
+ base_model_tp_plan = {
431
+ "multi_modal_projector.linear_1": "colwise_rep",
432
+ }
433
+
434
+ def __init__(
435
+ self,
436
+ vision_config=None,
437
+ text_config=None,
438
+ boi_token_index=200080,
439
+ eoi_token_index=200081,
440
+ image_token_index=200092,
441
+ tie_word_embeddings=False,
442
+ **kwargs,
443
+ ):
444
+ if vision_config is None:
445
+ self.vision_config = Llama4VisionConfig()
446
+ logger.info("vision_config is None, using default llama4 vision config")
447
+ elif isinstance(vision_config, dict):
448
+ self.vision_config = Llama4VisionConfig(**vision_config)
449
+ elif isinstance(vision_config, Llama4VisionConfig):
450
+ self.vision_config = vision_config
451
+
452
+ self.boi_token_index = boi_token_index
453
+ self.eoi_token_index = eoi_token_index
454
+ self.image_token_index = image_token_index
455
+ if text_config is None:
456
+ self.text_config = Llama4TextConfig()
457
+ logger.info("text_config is None, using default llama4 text config")
458
+ elif isinstance(text_config, dict):
459
+ self.text_config = Llama4TextConfig(**text_config)
460
+ elif isinstance(text_config, Llama4TextConfig):
461
+ self.text_config = text_config
462
+
463
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
464
+
465
+
466
+ __all__ = ["Llama4Config", "Llama4TextConfig", "Llama4VisionConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama4/convert_llama4_weights_to_hf.py ADDED
@@ -0,0 +1,743 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gc
3
+ import io
4
+ import json
5
+ import os
6
+ import re
7
+ from typing import Optional
8
+
9
+ import torch
10
+ from tokenizers import AddedToken, processors
11
+ from tqdm import tqdm
12
+
13
+ from transformers import (
14
+ GenerationConfig,
15
+ Llama4Config,
16
+ Llama4ForConditionalGeneration,
17
+ Llama4ImageProcessorFast,
18
+ Llama4Processor,
19
+ Llama4TextConfig,
20
+ Llama4VisionConfig,
21
+ PreTrainedTokenizerFast,
22
+ )
23
+ from transformers.integrations.tiktoken import TikTokenConverter
24
+
25
+
26
+ _OFFLINE_QUANT_COMPATIBLE = os.environ.get("OFFLINE_QUANT_COMPATIBLE", "0") == "1"
27
+
28
+ torch.serialization.add_safe_globals([io.BytesIO])
29
+ # fmt: off
30
+ # `None` means we drop the key
31
+
32
+
33
+ weight_postfix = ".weight" if _OFFLINE_QUANT_COMPATIBLE else ""
34
+ ORIGINAL_TO_CONVERTED_KEY_MAPPING = {
35
+ # CausalLM keys
36
+ r"output.weight": r"language_model.lm_head.weight",
37
+ r"\nnorm.weight": r"\nlanguage_model.model.norm.weight",
38
+ # Model keys
39
+ r"tok_embeddings.weight": r"language_model.model.embed_tokens.weight",
40
+ r"freq_cis": None,
41
+ r"rope.freqs": None,
42
+ r"layers.(\d+).attention_norm.weight": r"language_model.model.layers.\1.input_layernorm.weight",
43
+ r"layers.(\d+).attention.wqkv.layer_norm_weight": r"language_model.model.layers.\1.input_layernorm.weight",
44
+ r"layers.(\d+).feed_forward.norm.weight": r"language_model.model.layers.\1.post_attention_layernorm.weight",
45
+ r"layers.(\d+).attention.wo.weight": r"language_model.model.layers.\1.self_attn.o_proj.weight",
46
+ r"layers.(\d+).attention.wqkv.weight": r"language_model.model.layers.\1.self_attn.qkv_proj.weight",
47
+
48
+ # MoE keys: no simple MLPmodel.
49
+ r"layers.(\d+).feed_forward.experts.moe_w_in_eD_F": r"language_model.model.layers.\1.feed_forward.experts.gate_proj" + weight_postfix, # will be fused with up
50
+ r"layers.(\d+).feed_forward.experts.moe_w_out_eF_D": r"language_model.model.layers.\1.feed_forward.experts.down_proj" + weight_postfix, # expert win
51
+ r"layers.(\d+).feed_forward.experts.moe_w_swiglu_eD_F": r"language_model.model.layers.\1.feed_forward.experts.up_proj" + weight_postfix, # fused with up
52
+ r"layers.(\d+).feed_forward.router_DE": r"language_model.model.layers.\1.feed_forward.router.weight", # used for top
53
+ r"layers.(\d+).feed_forward.w_in_shared_FD": r"language_model.model.layers.\1.feed_forward.shared_expert.gate_proj", # might need to be fused for efficiency?
54
+ r"layers.(\d+).feed_forward.w_out_shared_DF": r"language_model.model.layers.\1.feed_forward.shared_expert.down_proj", # might need to be fused for efficiency?
55
+ r"layers.(\d+).feed_forward.w_swiglu_FD": r"language_model.model.layers.\1.feed_forward.shared_expert.up_proj", # might need to be fused for efficiency?
56
+ r"layers.(\d+).feed_forward.global_gate_stats_3E": None,
57
+ # Unused keys in load hooks (explicitly removed)
58
+ r'layers.(\d+).attention.wqkv._extra_state': None,
59
+ r'layers.(\d+).attention.wo._extra_state': None,
60
+ # Key apparently unused in base models
61
+ r'layers.(\d+).feed_forward.expert_activation_DE': None,
62
+
63
+ # MLP layer variant
64
+ r"layers.(\d+).feed_forward.w1.weight": r"language_model.model.layers.\1.feed_forward.gate_proj.weight", # might need to be fused for efficiency?
65
+ r"layers.(\d+).feed_forward.w3.weight": r"language_model.model.layers.\1.feed_forward.up_proj.weight", # might need to be fused for efficiency?
66
+ # r"layers.(\d+).feed_forward.mlp.fc1_weight": r"language_model.model.layers.\1.feed_forward.gate_up_proj.weight",
67
+ r"layers.(\d+).feed_forward.mlp.fc2_weight": r"language_model.model.layers.\1.feed_forward.down_proj.weight",
68
+ r"layers.(\d+).feed_forward.w2.weight": r"language_model.model.layers.\1.feed_forward.down_proj.weight",
69
+ r"layers.(\d+).feed_forward.mlp.layer_norm.weight": r"language_model.model.layers.\1.post_attention_layernorm.weight",
70
+
71
+ # Vision encoder mapping
72
+ r"vision_embeddings.vision_encoder.conv1._linear": r"vision_model.patch_embedding.linear",
73
+ r'vision_embeddings.vision_adapter.mlp.c_fc': r"vision_model.vision_adapter.mlp.fc1",
74
+ r'vision_embeddings.vision_adapter.mlp.c_proj': r"vision_model.vision_adapter.mlp.fc2",
75
+ r"vision_embeddings.vision_encoder.transformer.resblocks.(\d+).attn.wq.(weight|bias)": r"vision_model.model.layers.\1.self_attn.q_proj.\2",
76
+ r"vision_embeddings.vision_encoder.transformer.resblocks.(\d+).attn.wk.(weight|bias)": r"vision_model.model.layers.\1.self_attn.k_proj.\2",
77
+ r"vision_embeddings.vision_encoder.transformer.resblocks.(\d+).attn.wv.(weight|bias)": r"vision_model.model.layers.\1.self_attn.v_proj.\2",
78
+ r"vision_embeddings.vision_encoder.transformer.resblocks.(\d+).attn.wo.(weight|bias)": r"vision_model.model.layers.\1.self_attn.o_proj.\2",
79
+ r"vision_embeddings.vision_encoder.transformer.resblocks.(\d+).mlp.c_fc": r"vision_model.model.layers.\1.mlp.fc1",
80
+ r"vision_embeddings.vision_encoder.transformer.resblocks.(\d+).mlp.c_proj": r"vision_model.model.layers.\1.mlp.fc2",
81
+ r"vision_embeddings.vision_encoder.transformer.resblocks.(\d+).ln_1.(weight|bias)": r"vision_model.model.layers.\1.input_layernorm.\2",
82
+ r"vision_embeddings.vision_encoder.transformer.resblocks.(\d+).ln_2.(weight|bias)": r"vision_model.model.layers.\1.post_attention_layernorm.\2",
83
+ # r'vision_embeddings.vision_encoder.ln_(1|2).(weight|bias)': r'vision_model.transformer.vision_encoder.layernorm_\1.\2',
84
+ r'vision_embeddings.vision_encoder.ln_post': r'vision_model.layernorm_post',
85
+ r'vision_embeddings.vision_encoder.ln_pre': r'vision_model.layernorm_pre',
86
+ r'vision_embeddings.vision_encoder.class_embedding': r'vision_model.class_embedding',
87
+ r"vision_embeddings.vision_encoder.positional_embedding_vlm": r"vision_model.positional_embedding_vlm",
88
+ r"vision_embeddings.vision_encoder.(?=\w)": r"vision_model.model.",
89
+ r"vision_projection.weight": r"multi_modal_projector.linear_1.weight",
90
+ }
91
+ # fmt: on
92
+
93
+
94
+ def convert_old_keys_to_new_keys(state_dict_keys: Optional[dict] = None):
95
+ """
96
+ This function should be applied only once, on the concatenated keys to efficiently rename using
97
+ the key mappings.
98
+ """
99
+ output_dict = {}
100
+ if state_dict_keys is not None:
101
+ old_text = "\n".join(state_dict_keys)
102
+ new_text = old_text
103
+ for pattern, replacement in ORIGINAL_TO_CONVERTED_KEY_MAPPING.items():
104
+ if replacement is None:
105
+ new_text = re.sub(pattern, "", new_text) # an empty line
106
+ continue
107
+ new_text = re.sub(pattern, replacement, new_text)
108
+ output_dict = dict(zip(old_text.split("\n"), new_text.split("\n")))
109
+ return output_dict
110
+
111
+
112
+ def permute_for_rope(input_tensor, n_heads, dim1, dim2):
113
+ """
114
+ When you go from the complex ROPE formulation to sin and cos one, you need
115
+ to permute the query and key weights (to avoid doing it on the fly)
116
+ """
117
+ input_tensor = input_tensor.view(n_heads, dim1 // n_heads // 2, 2, dim2)
118
+ input_tensor = input_tensor.transpose(1, 2).reshape(dim1, dim2)
119
+ return input_tensor
120
+
121
+
122
+ def is_param_same_across_shards(key):
123
+ """
124
+ Return `False` if the parameter is different across checkpoint shards
125
+ and needs to be concatenated.
126
+ """
127
+ patterns = [
128
+ r"language_model.layers.(\d+).(.*)layernorm.weight",
129
+ r"language_model.norm.weight",
130
+ r"router.weight",
131
+ r"feed_forward.global_gate_stats",
132
+ # not all vision weights are sharded, some are repeated
133
+ r"vision_model.class_embedding",
134
+ r"vision_model.positional_embedding_vlm",
135
+ r"vision_embeddings.vision_encoder.positional_embedding_vlm",
136
+ r"vision_model.model.layers.(\d+).self_attn.o_proj.bias",
137
+ r"vision_model.model.layers.(\d+).input_layernorm",
138
+ r"vision_model.model.layers.(\d+).post_attention_layernorm",
139
+ r"vision_model.layernorm_pre",
140
+ r"vision_model.layernorm_post",
141
+ r"vision_model.model.layers.(\d+).mlp.fc2.bias",
142
+ r"norm.weight",
143
+ ] # fmt: skip
144
+ return any(re.search(pattern, key) for pattern in patterns)
145
+
146
+
147
+ def get_concat_dim(key):
148
+ """
149
+ Return the dimension to concatenate the weights on.
150
+ """
151
+ concat_dim_1 = [
152
+ # language dim 1 sharded weights
153
+ "feed_forward.router.weight",
154
+ "self_attn.o_proj",
155
+ "experts.gate_proj",
156
+ "experts.up_proj",
157
+ "expert.down_proj",
158
+ # "feed_forward.up_proj",
159
+ # "feed_forward.gate_proj",
160
+ "feed_forward.down_proj",
161
+ "global_gate_stats",
162
+ # vision dim1 sharded stuff
163
+ "mlp.fc2.weight", # covers all rowparallels across vis
164
+ ] # fmt: off
165
+ if any(re.search(pattern, key) for pattern in concat_dim_1):
166
+ return 1
167
+ return 0
168
+
169
+
170
+ def compute_intermediate_size(hidden_dim, ffn_exp=4, multiple_of=1024, ffn_dim_multiplier=1.2):
171
+ hidden_dim = ffn_exp * int(2 * hidden_dim / 3)
172
+ hidden_dim = int(ffn_dim_multiplier * hidden_dim)
173
+ hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
174
+ return hidden_dim
175
+
176
+
177
+ # Ignore extra info - h/t Aritra
178
+ def safe_load(filename):
179
+ # Can use weights_only because io.BytesIO was registered, but we still need to skip those objects
180
+ shard = torch.load(filename, weights_only=True, map_location="cpu", mmap=True)
181
+ shard = {k: v for k, v in shard.items() if not isinstance(v, io.BytesIO)}
182
+ return shard
183
+
184
+
185
+ # Unpack mlp projections - possibly to be removed when they are fused
186
+ def preprocess_keys(state_dict):
187
+ new_state_dict = {}
188
+ for key, value in state_dict.items():
189
+ if "mlp.fc1_weight" in key:
190
+ prefix = key.split("mlp.fc1_weight")[0]
191
+ w1, w3 = value.chunk(2, dim=0)
192
+ new_state_dict[prefix + "w1.weight"] = w1
193
+ new_state_dict[prefix + "w3.weight"] = w3
194
+ else:
195
+ new_state_dict[key] = value
196
+ return new_state_dict
197
+
198
+
199
+ def max_context_length(model_path, instruct=False):
200
+ """256K for base, 1M for 128E instruct, 10M for 16E instruct."""
201
+ if not instruct:
202
+ return 256 * 1024
203
+
204
+ with open(os.path.join(model_path, "params.json"), "r") as f:
205
+ params = json.load(f)
206
+ params = params.get("model", params)
207
+ if params.get("moe_args") is None:
208
+ return 8192
209
+ num_experts = params["moe_args"]["num_experts"]
210
+ return 10485760 if num_experts == 16 else 1048576
211
+
212
+
213
+ def write_model(
214
+ model_path,
215
+ input_base_path,
216
+ num_shards,
217
+ convert_checkpoints,
218
+ safe_serialization=True,
219
+ instruct=False,
220
+ ):
221
+ os.makedirs(model_path, exist_ok=True)
222
+
223
+ with open(os.path.join(input_base_path, "params.json"), "r") as f:
224
+ params = json.load(f)
225
+
226
+ params = params.get("model", params)
227
+ torch_dtype = "bfloat16"
228
+
229
+ # ------------------------------------------------------------
230
+ # Text model params and config
231
+ # ------------------------------------------------------------
232
+
233
+ # params from config
234
+ vocab_size = 202048 # params["vocab_size"] # seems like the lm head is 25256 so padded instead of 202048
235
+ num_layers = params["n_layers"]
236
+ dim = params["dim"]
237
+ num_heads = params["n_heads"]
238
+ rms_norm_eps = params["norm_eps"]
239
+ rope_theta = params["rope_theta"]
240
+ no_rope_layer_interval = params["nope_layer_interval"]
241
+ attention_chunk_size = params["attention_chunk_size"]
242
+
243
+ config_kwargs = {}
244
+ if params["use_scaled_rope"]:
245
+ # some constants from original code
246
+ rope_scaling = {
247
+ "rope_type": "llama3",
248
+ "factor": params.get("rope_scaling_factor", 8.0),
249
+ "low_freq_factor": 1.0,
250
+ "high_freq_factor": params.get("rope_high_freq_factor", 4.0),
251
+ "original_max_position_embeddings": 8192,
252
+ }
253
+ config_kwargs.update({"rope_scaling": rope_scaling})
254
+
255
+ if attention_chunk_size is None:
256
+ config_kwargs.update({"cache_implementation": "static"})
257
+
258
+ # compute additional params for weight conversion
259
+ num_heads_per_shard = num_heads // num_shards
260
+ dim_per_head = dim // num_heads
261
+ intermediate_size_mlp = compute_intermediate_size(
262
+ dim,
263
+ ffn_exp=params["ffn_exp"],
264
+ multiple_of=params["multiple_of"],
265
+ ffn_dim_multiplier=params["ffn_dim_multiplier"],
266
+ )
267
+
268
+ num_key_value_heads = params["n_kv_heads"] # for GQA / MQA
269
+
270
+ if params.get("moe_args", False):
271
+ num_experts = params["moe_args"]["num_experts"]
272
+ interleave_moe_layer_step = params["moe_args"].get("interleave_moe_layer_step", 1)
273
+ else:
274
+ # Dense model (possibly Llama Guard) - disable all moe layers
275
+ num_experts = 0
276
+ interleave_moe_layer_step = 0
277
+ config_kwargs.update({"moe_layers": []})
278
+
279
+ # Ensure all layers are rope if `nope_layer_interval` is None
280
+ no_rope_layer_interval = params["nope_layer_interval"]
281
+ no_rope_layer_interval = num_heads * 2 if no_rope_layer_interval is None else no_rope_layer_interval
282
+
283
+ bos_token_id = 200000
284
+ eos_token_id = [200001, 200007, 200008] if instruct else 200001
285
+ pad_token_id = 200018
286
+
287
+ text_config = Llama4TextConfig(
288
+ num_attention_heads=num_heads,
289
+ vocab_size=vocab_size,
290
+ hidden_size=dim,
291
+ rms_norm_eps=rms_norm_eps,
292
+ rope_theta=rope_theta,
293
+ num_hidden_layers=num_layers,
294
+ intermediate_size=8192,
295
+ intermediate_size_mlp=intermediate_size_mlp,
296
+ max_position_embeddings=max_context_length(input_base_path, instruct),
297
+ num_local_experts=num_experts,
298
+ interleave_moe_layer_step=interleave_moe_layer_step,
299
+ use_qk_norm=params["use_qk_norm"],
300
+ no_rope_layer_interval=no_rope_layer_interval,
301
+ attention_chunk_size=attention_chunk_size,
302
+ bos_token_id=bos_token_id,
303
+ eos_token_id=eos_token_id,
304
+ pad_token_id=pad_token_id,
305
+ tie_word_embeddings=False, # Constant set to False
306
+ torch_dtype=torch_dtype,
307
+ for_llm_compressor=_OFFLINE_QUANT_COMPATIBLE,
308
+ **config_kwargs,
309
+ )
310
+ # default vision config from params
311
+
312
+ vision_params = params["vision_args"]
313
+ vision_dim = vision_params["dim"]
314
+ vision_num_layers = vision_params["n_layers"]
315
+ image_size = vision_params["image_size"]["height"] # siglip config is outdated
316
+ vision_num_heads = vision_params["n_heads"]
317
+
318
+ vision_output_dim = vision_params["output_dim"]
319
+
320
+ vision_config = Llama4VisionConfig(
321
+ hidden_act="gelu",
322
+ num_hidden_layers=vision_num_layers,
323
+ image_size=image_size,
324
+ num_attention_heads=vision_num_heads,
325
+ hidden_size=vision_dim,
326
+ vision_output_dim=vision_output_dim,
327
+ )
328
+
329
+ config = Llama4Config(text_config=text_config, vision_config=vision_config)
330
+ config.save_pretrained(model_path)
331
+
332
+ print("Model config saved successfully...")
333
+
334
+ # ------------------------------------------------------------
335
+ # Convert weights
336
+ # ------------------------------------------------------------
337
+
338
+ if convert_checkpoints:
339
+ print(f"Fetching all parameters from the checkpoint at {input_base_path}...")
340
+ if num_shards == 1:
341
+ if os.path.exists(os.path.join(input_base_path, "consolidated.00.pth")):
342
+ path = os.path.join(input_base_path, "consolidated.00.pth")
343
+ else:
344
+ path = os.path.join(input_base_path, "consolidated.pth")
345
+ loaded = [safe_load(path)]
346
+ else:
347
+ loaded = [
348
+ safe_load(os.path.join(input_base_path, f"consolidated.{i:02d}.pth"))
349
+ for i in tqdm(range(num_shards), desc="Loading shards", unit="shard")
350
+ ]
351
+ loaded = [preprocess_keys(d) for d in loaded]
352
+
353
+ all_keys_raw = list(loaded[0].keys())
354
+ repeated_keys = []
355
+ sharded_keys = []
356
+ for _key in all_keys_raw:
357
+ try:
358
+ if num_shards == 1 or (loaded[0][_key] == loaded[1][_key]).all():
359
+ repeated_keys.append(_key)
360
+ else:
361
+ sharded_keys.append(_key)
362
+ except Exception as e:
363
+ print(f"Encountered exception {e} for {_key}")
364
+ print("Initializing an empty model")
365
+ with torch.device("meta"):
366
+ model = Llama4ForConditionalGeneration(config)
367
+
368
+ print("Converting model...")
369
+ all_keys = list(loaded[0].keys())
370
+ new_keys = convert_old_keys_to_new_keys(all_keys)
371
+ state_dict = {}
372
+ replicated_params = [] # To keep track of replicated weights.
373
+ for key in tqdm(all_keys, desc="Renaming and processing all keys", unit="key"):
374
+ new_key = new_keys[key]
375
+ print(key, new_key)
376
+ if num_shards > 1 and not is_param_same_across_shards(new_key):
377
+ current_parameter = [chunk.pop(key) for chunk in loaded if not isinstance(chunk[key], io.BytesIO)]
378
+ else:
379
+ print(f"{key} (now {new_key}) is the same across all shards.")
380
+ replicated_params.append((key, new_key))
381
+ current_parameter = [loaded[0].pop(key)] if not isinstance(loaded[0][key], io.BytesIO) else []
382
+
383
+ if "running_gate_stats_3E" in key:
384
+ new_keys.pop(new_key)
385
+ continue
386
+
387
+ concat_dim = get_concat_dim(new_key)
388
+
389
+ # Post-process the current_parameter.
390
+ if "qkv_proj" in new_key:
391
+ queries = []
392
+ keys = []
393
+ values = []
394
+ for param in current_parameter:
395
+ query, key_, value = param.split(
396
+ [
397
+ num_heads * dim_per_head // num_shards,
398
+ num_key_value_heads * dim_per_head // num_shards,
399
+ num_key_value_heads * dim_per_head // num_shards,
400
+ ]
401
+ )
402
+ queries.append(query.reshape(num_heads_per_shard, -1, dim))
403
+ keys.append(key_.reshape(num_key_value_heads // num_shards, -1, dim))
404
+ values.append(value.reshape(num_key_value_heads // num_shards, -1, dim))
405
+
406
+ queries = torch.cat(queries, dim=0).reshape(dim, dim)
407
+ keys = torch.cat(keys, dim=0).reshape(num_key_value_heads * dim_per_head, dim)
408
+ values = torch.cat(values, dim=0).reshape(num_key_value_heads * dim_per_head, dim)
409
+ # queries = permute_for_rope(queries, num_heads, dim, dim)
410
+ # keys = permute_for_rope(keys, num_key_value_heads, num_key_value_heads*dim_per_head, dim)
411
+
412
+ q = new_key.replace("qkv", "q")
413
+ tqdm.write(f"Processing: {key.ljust(50)} ->\t {q}, {queries.shape}")
414
+ state_dict[q] = queries
415
+
416
+ k = new_key.replace("qkv", "k")
417
+ tqdm.write(f"Processing: {key.ljust(50)} ->\t {k}, {keys.shape}")
418
+ state_dict[k] = keys
419
+
420
+ v = new_key.replace("qkv", "v")
421
+ tqdm.write(f"Processing: {key.ljust(50)} ->\t {v}, {values.shape}")
422
+ state_dict[v] = values
423
+ elif _OFFLINE_QUANT_COMPATIBLE and "feed_forward.experts." in new_key:
424
+ # for experts, we need to split expert for offline quantization purpose and don't need to fuse
425
+ expert_lists = []
426
+ for k in current_parameter:
427
+ expert_lists.append(
428
+ list(k.reshape(num_experts, -1, k.shape[-1]).unbind(0))
429
+ ) # [#expert * IN, OUT] -> #experts * [IN, OUT]
430
+ for i in range(num_experts):
431
+ expert = torch.cat([expert_list[i] for expert_list in expert_lists], dim=concat_dim)
432
+ expert_key = new_key.replace("experts.", f"experts.{i}.")
433
+ state_dict[expert_key] = expert.transpose(0, 1).contiguous() # [OUT, IN]
434
+ tqdm.write(f"Processing: {key.ljust(50)} ->\t {expert_key}, {state_dict[expert_key].shape}")
435
+ elif re.search(r"(gate|up)_proj", new_key):
436
+ path = new_key.split(".")
437
+ gate_key = re.sub(r"(gate|up)_proj", lambda m: "gate_proj", new_key)
438
+ up_key = re.sub(r"(gate|up)_proj", lambda m: "up_proj", new_key)
439
+ if gate_key == new_key:
440
+ state_dict[new_key] = torch.cat(current_parameter, dim=concat_dim)
441
+ elif new_key == up_key:
442
+ if "experts" not in new_key:
443
+ state_dict[new_key] = torch.cat(current_parameter, dim=concat_dim)
444
+ else:
445
+ gate_proj = state_dict.pop(gate_key)
446
+ gate_proj = [
447
+ gate_proj.reshape(num_experts, -1, 8, 1024)[:, :, k, :].reshape(num_experts, -1, 1024)
448
+ for k in range(8)
449
+ ]
450
+ gate_proj = torch.cat(gate_proj, dim=-1)
451
+
452
+ up_proj = [
453
+ k.reshape(num_experts, -1, 8, 1024).reshape(num_experts, -1, 1024)
454
+ for k in current_parameter
455
+ ]
456
+ up_proj = torch.cat(up_proj, dim=-1)
457
+
458
+ gate_up_proj = torch.cat((gate_proj, up_proj), dim=-1)
459
+ new_key = new_key.replace("up_proj", "gate_up_proj")
460
+ state_dict[new_key] = gate_up_proj.contiguous()
461
+
462
+ tqdm.write(f"Processing: {key.ljust(50)} ->\t {new_key}, {state_dict[new_key].shape}")
463
+ elif "down_proj" in new_key:
464
+ current_parameter = torch.cat(current_parameter, dim=concat_dim)
465
+ if "experts" in new_key:
466
+ p = []
467
+ for i in range(8):
468
+ p += [current_parameter.reshape(8, -1, 5120)[i, :, :].view(num_experts, -1, 5120)]
469
+ current_parameter = torch.cat(p, dim=1)
470
+ state_dict[new_key] = current_parameter.contiguous()
471
+ tqdm.write(f"Processing: {key.ljust(50)} ->\t {new_key}, {state_dict[new_key].shape}")
472
+ elif "router" in new_key:
473
+ current_parameter = torch.cat(current_parameter, dim=concat_dim)
474
+ state_dict[new_key] = current_parameter.transpose(0, 1)
475
+ elif "lm_head" in new_key:
476
+ current_parameter = torch.cat(current_parameter, dim=concat_dim).clone()
477
+ # TODO we need to do better than mean, works for now
478
+ # if (vocab_size - current_parameter.shape[0]) > 0:
479
+ # mean_embedding = torch.mean(current_parameter, dim=0)[:, None].repeat(vocab_size-current_parameter.shape[0],1)
480
+ # print(mean_embedding.shape)
481
+ # current_parameter = torch.cat((current_parameter, mean_embedding), dim=0)
482
+ state_dict[new_key] = current_parameter
483
+ tqdm.write(
484
+ f"Processing: {key.ljust(50)} ->\t {new_key}, {state_dict[new_key].shape}, concat dim = {concat_dim}"
485
+ )
486
+ elif new_key == "vision_model.patch_embedding.linear.weight":
487
+ current_parameter = torch.cat(current_parameter, dim=concat_dim).clone()
488
+ # We don't reshape the patch embedding as we're using unfolded convolution as well
489
+ state_dict[new_key] = current_parameter # .reshape(-1, 3, vision_patch_size, vision_patch_size)
490
+ # generic concat for weights/select one for biases
491
+ elif isinstance(current_parameter, list) and len(current_parameter) > 0:
492
+ if not is_param_same_across_shards(new_key):
493
+ current_parameter = torch.cat(current_parameter, dim=concat_dim)
494
+ state_dict[new_key] = current_parameter
495
+ tqdm.write(
496
+ f"Processing: {key.ljust(50)} ->\t {new_key}, {state_dict[new_key].shape}, concat dim = {concat_dim}"
497
+ )
498
+ elif is_param_same_across_shards(new_key):
499
+ state_dict[new_key] = current_parameter[0]
500
+ tqdm.write(
501
+ f"Processing: {key.ljust(50)} ->\t {new_key}, {state_dict[new_key].shape}, concat dim = {concat_dim}"
502
+ )
503
+
504
+ elif new_key == "":
505
+ # skip empty keys
506
+ continue
507
+ else:
508
+ # just load the parameter
509
+ state_dict[new_key] = current_parameter
510
+ tqdm.write(
511
+ f"Processing: {key.ljust(50)} ->\t {new_key}, {state_dict[new_key].shape}, concat dim = {concat_dim}"
512
+ )
513
+ del loaded
514
+ gc.collect()
515
+
516
+ print("Loading the checkpoint in a Llama4 model.")
517
+ state_dict.pop("")
518
+ model.load_state_dict(state_dict, strict=True, assign=True)
519
+ print("Model reloaded successfully.")
520
+ print("Saving the model.")
521
+ model.save_pretrained(model_path, safe_serialization=safe_serialization)
522
+ del state_dict, model
523
+
524
+ # Safety check: reload the converted model
525
+ gc.collect()
526
+ print("Reloading the model to check if it's saved correctly.")
527
+ with torch.no_grad():
528
+ # TODO test if we can do `tp_plan="auto"``
529
+ model = Llama4ForConditionalGeneration.from_pretrained(
530
+ model_path, torch_dtype=torch.bfloat16, device_map="auto", attn_implementation="eager"
531
+ )
532
+
533
+ model.generation_config.top_p = 0.9
534
+ model.generation_config.temperature = 0.6
535
+ print("Model reloaded successfully.")
536
+
537
+ from transformers import AutoTokenizer
538
+
539
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
540
+ inputs = tokenizer(["Roses are red,"], return_tensors="pt").to(model.device)
541
+ out = model.generate(**inputs, max_new_tokens=4)
542
+ print(tokenizer.batch_decode(out))
543
+ # generation config
544
+ if instruct:
545
+ print("Saving generation config...")
546
+ generation_config = GenerationConfig(
547
+ do_sample=True,
548
+ temperature=0.6,
549
+ top_p=0.9,
550
+ bos_token_id=bos_token_id,
551
+ eos_token_id=eos_token_id,
552
+ pad_token_id=pad_token_id,
553
+ )
554
+ generation_config.save_pretrained(model_path)
555
+
556
+
557
+ BOS_ADDED_TOKEN = AddedToken(
558
+ "<|begin_of_text|>", single_word=False, lstrip=False, rstrip=False, normalized=False, special=True
559
+ )
560
+ EOS_ADDED_TOKEN = AddedToken(
561
+ "<|end_of_text|>", single_word=False, lstrip=False, rstrip=False, normalized=False, special=True
562
+ )
563
+ EOT_ADDED_TOKEN = AddedToken("<|eot|>", single_word=False, lstrip=False, rstrip=False, normalized=False, special=True)
564
+
565
+
566
+ def get_reserved_special_tokens(name, count, start_index=0):
567
+ return [f"<|{name}_reserved_special_token_{i}|>" for i in range(start_index, start_index + count)]
568
+
569
+
570
+ # 200005, ..., 200079
571
+ LLAMA4_TEXT_POST_TRAIN_SPECIAL_TOKENS = [
572
+ "<|header_start|>",
573
+ "<|header_end|>",
574
+ "<|eom|>",
575
+ "<|eot|>",
576
+ "<|step|>",
577
+ "<|text_post_train_reserved_special_token_0|>",
578
+ "<|text_post_train_reserved_special_token_1|>",
579
+ "<|text_post_train_reserved_special_token_2|>",
580
+ "<|text_post_train_reserved_special_token_3|>",
581
+ "<|text_post_train_reserved_special_token_4|>",
582
+ "<|text_post_train_reserved_special_token_5|>",
583
+ "<|python_start|>",
584
+ "<|python_end|>",
585
+ "<|finetune_right_pad|>",
586
+ ] + get_reserved_special_tokens(
587
+ "text_post_train", 61, 8
588
+ ) # <|text_post_train_reserved_special_token_8|>, ..., <|text_post_train_reserved_special_token_68|>
589
+
590
+ # 200080, ..., 201133
591
+ LLAMA4_VISION_SPECIAL_TOKENS = [
592
+ "<|image_start|>",
593
+ "<|image_end|>",
594
+ "<|vision_reserved_special_token_0|>",
595
+ "<|vision_reserved_special_token_1|>",
596
+ "<|tile_x_separator|>",
597
+ "<|tile_y_separator|>",
598
+ "<|vision_reserved_special_token_2|>",
599
+ "<|vision_reserved_special_token_3|>",
600
+ "<|vision_reserved_special_token_4|>",
601
+ "<|vision_reserved_special_token_5|>",
602
+ "<|image|>",
603
+ "<|vision_reserved_special_token_6|>",
604
+ "<|patch|>",
605
+ ] + get_reserved_special_tokens(
606
+ "vision", 1041, 7
607
+ ) # <|vision_reserved_special_token_7|>, ..., <|vision_reserved_special_token_1047|>
608
+
609
+ LLAMA4_SPECIAL_TOKENS = LLAMA4_TEXT_POST_TRAIN_SPECIAL_TOKENS + LLAMA4_VISION_SPECIAL_TOKENS
610
+
611
+ BASIC_SPECIAL_TOKENS = [
612
+ "<|begin_of_text|>",
613
+ "<|end_of_text|>",
614
+ "<|fim_prefix|>",
615
+ "<|fim_middle|>",
616
+ "<|fim_suffix|>",
617
+ ]
618
+
619
+
620
+ class Llama4Converter(TikTokenConverter):
621
+ def __init__(
622
+ self,
623
+ vocab_file,
624
+ special_tokens: list[str],
625
+ pattern: str,
626
+ model_max_length: int = 0,
627
+ chat_template: Optional[str] = None,
628
+ **kwargs,
629
+ ):
630
+ super().__init__(vocab_file, pattern=pattern)
631
+ self.additional_special_tokens = special_tokens
632
+ tokenizer = self.converted()
633
+ if chat_template is not None:
634
+ kwargs["chat_template"] = chat_template
635
+
636
+ self.converted_tokenizer = PreTrainedTokenizerFast(
637
+ tokenizer_object=tokenizer,
638
+ model_input_names=["input_ids", "attention_mask"],
639
+ model_max_length=model_max_length,
640
+ **kwargs,
641
+ )
642
+
643
+ instruct = chat_template is not None
644
+ self.update_post_processor(self.converted_tokenizer)
645
+ # finer special_tokens_map.json
646
+ self.converted_tokenizer._bos_token = BOS_ADDED_TOKEN
647
+ self.converted_tokenizer._eos_token = EOT_ADDED_TOKEN if instruct else EOS_ADDED_TOKEN
648
+
649
+ # We can't do this while building the tokenizer because we have no easy access to the bos token id
650
+ def update_post_processor(self, tokenizer):
651
+ tokenizer._tokenizer.post_processor = processors.Sequence(
652
+ [
653
+ processors.ByteLevel(trim_offsets=False),
654
+ processors.TemplateProcessing(
655
+ single="<|begin_of_text|> $A",
656
+ pair="<|begin_of_text|>:0 $A:0 <|begin_of_text|>:1 $B:1",
657
+ special_tokens=[
658
+ ("<|begin_of_text|>", tokenizer.convert_tokens_to_ids("<|begin_of_text|>")),
659
+ ],
660
+ ),
661
+ ]
662
+ )
663
+
664
+
665
+ O200K_PATTERN = r"""[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+""" # noqa: E501
666
+
667
+
668
+ def write_tokenizer(args):
669
+ tokenizer_path = os.path.join(args.input_dir, "tokenizer.model")
670
+ chat_template = "{{- bos_token }}\n{%- if custom_tools is defined %}\n {%- set tools = custom_tools %}\n{%- endif %}\n{%- if not tools_in_user_message is defined %}\n {%- set tools_in_user_message = true %}\n{%- endif %}\n{%- if not date_string is defined %}\n {%- if strftime_now is defined %}\n {%- set date_string = strftime_now(\"%d %b %Y\") %}\n {%- else %}\n {%- set date_string = \"26 Jul 2024\" %}\n {%- endif %}\n{%- endif %}\n{%- if not tools is defined %}\n {%- set tools = none %}\n{%- endif %}\n\n{#- This block extracts the system message, so we can slot it into the right place. #}\n{%- if messages[0]['role'] == 'system' %} \n {%- if messages[0]['content'] is string %}\n {%- set system_message = messages[0]['content']|trim %}\n {%- else %}\n {#- FIXME: The processor requires an array, always. #}\n {%- set system_message = messages[0]['content'][0]['text']|trim %}\n {%- endif %}\n {%- set messages = messages[1:] %}\n {%- set user_supplied_system_message = true %}\n{%- else %}\n {%- set system_message = \"\" %}\n {%- set user_supplied_system_message = false %}\n{%- endif %}\n\n{#- System message if the user supplied one #}\n{%- if user_supplied_system_message %}\n {{- \"<|header_start|>system<|header_end|>\n\n\" }}\n {%- if tools is not none %}\n {{- \"Environment: ipython\n\" }}\n {%- endif %}\n {%- if tools is not none and not tools_in_user_message %}\n {{- \"You have access to the following functions. To call a function, please respond with JSON for a function call.\" }}\n {{- 'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.' }}\n {{- \"Do not use variables.\n\n\" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- \"\n\n\" }}\n {%- endfor %}\n {%- endif %}\n {{- system_message }}\n {{- \"<|eot|>\" }}\n{%- endif %}\n\n{#- Custom tools are passed in a user message with some extra guidance #}\n{%- if tools_in_user_message and not tools is none %}\n {#- Extract the first user message so we can plug it in here #}\n {%- if messages | length != 0 %}\n {%- set first_user_message = messages[0]['content']|trim %}\n {%- set messages = messages[1:] %}\n {%- else %}\n {{- raise_exception(\"Cannot put tools in the first user message when there's no first user message!\") }}\n{%- endif %}\n {{- '<|header_start|>user<|header_end|>\n\n' -}}\n {{- \"Given the following functions, please respond with a JSON for a function call \" }}\n {{- \"with its proper arguments that best answers the given prompt.\n\n\" }}\n {{- 'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.' }}\n {{- \"Do not use variables.\n\n\" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- \"\n\n\" }}\n {%- endfor %}\n {{- first_user_message + \"<|eot|>\"}}\n{%- endif %}\n\n{%- for message in messages %}\n {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %}\n {{- '<|header_start|>' + message['role'] + '<|header_end|>\n\n' }}\n {%- if message['content'] is string %}\n {{- message['content'] }}\n {%- else %}\n {%- for content in message['content'] %}\n {%- if content['type'] == 'image' %}\n {{- '<|image|>' }}\n {%- elif content['type'] == 'text' %}\n {{- content['text'] }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- \"<|eot|>\" }}\n {%- elif 'tool_calls' in message and message.tool_calls|length > 0 %}\n {{- '<|header_start|>assistant<|header_end|>\n\n' -}}\n {{- '<|python_start|>' }}\n {%- if message['content'] is string %}\n {{- message['content'] }}\n {%- else %}\n {%- for content in message['content'] %}\n {%- if content['type'] == 'image' %}\n {{- '<|image|>' }}\n {%- elif content['type'] == 'text' %}\n {{- content['text'] }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '<|python_end|>' }}\n {%- for tool_call in message.tool_calls %}\n {{- '{\"name\": \"' + tool_call.function.name + '\", ' }}\n {{- '\"parameters\": ' }}\n {{- tool_call.function.arguments | tojson }}\n {{- \"}\" }}\n {%- endfor %}\n {{- \"<|eot|>\" }}\n {%- elif message.role == \"tool\" or message.role == \"ipython\" %}\n {{- \"<|header_start|>ipython<|header_end|>\n\n\" }}\n {%- if message.content is mapping or message.content is iterable %}\n {{- message.content | tojson }}\n {%- else %}\n {{- message.content }}\n {%- endif %}\n {{- \"<|eot|>\" }}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|header_start|>assistant<|header_end|>\n\n' }}\n{%- endif %}\n"
671
+
672
+ special_tokens = BASIC_SPECIAL_TOKENS + LLAMA4_SPECIAL_TOKENS
673
+ converter = Llama4Converter(
674
+ vocab_file=tokenizer_path,
675
+ pattern=O200K_PATTERN,
676
+ special_tokens=special_tokens,
677
+ chat_template=chat_template if args.instruct else None,
678
+ bos_token="<|begin_of_text|>",
679
+ eos_token="<|end_of_text|>" if not args.instruct else "<|eot|>",
680
+ pad_token="<|finetune_right_pad_id|>",
681
+ model_max_length=max_context_length(args.input_dir, args.instruct),
682
+ )
683
+ tokenizer = converter.converted_tokenizer
684
+
685
+ image_processor = Llama4ImageProcessorFast()
686
+ processor = Llama4Processor(
687
+ image_processor=image_processor,
688
+ tokenizer=tokenizer,
689
+ chat_template=tokenizer.chat_template,
690
+ )
691
+ processor.save_pretrained(args.output_dir)
692
+ del processor
693
+
694
+
695
+ if __name__ == "__main__":
696
+ parser = argparse.ArgumentParser()
697
+ parser.add_argument(
698
+ "--input_dir",
699
+ type=str,
700
+ help="Location of the local folder copied from the Hub.",
701
+ )
702
+ parser.add_argument(
703
+ "--output_dir",
704
+ type=str,
705
+ help="Location to write HF model and tokenizer",
706
+ )
707
+ parser.add_argument(
708
+ "--safe_serialization", default=True, type=bool, help="Whether or not to save using `safetensors`."
709
+ )
710
+ parser.add_argument(
711
+ "--special_tokens",
712
+ default=None,
713
+ type=list[str],
714
+ help="The list of special tokens that should be added to the model.",
715
+ )
716
+ parser.add_argument(
717
+ "--num_shards",
718
+ default=8,
719
+ type=int,
720
+ help="The number of individual shards used for the model. Does not have to be the same as the number of consolidated_xx.pth",
721
+ )
722
+ parser.add_argument(
723
+ "--instruct",
724
+ action="store_true",
725
+ help="Whether the model is an instruct model",
726
+ )
727
+ parser.add_argument(
728
+ "--convert_checkpoints",
729
+ action="store_true",
730
+ help="Whether to convert the original weights (or skip if previously converted)",
731
+ )
732
+
733
+ args = parser.parse_args()
734
+ write_tokenizer(args)
735
+
736
+ write_model(
737
+ model_path=args.output_dir,
738
+ input_base_path=args.input_dir,
739
+ safe_serialization=args.safe_serialization,
740
+ num_shards=args.num_shards,
741
+ instruct=args.instruct,
742
+ convert_checkpoints=args.convert_checkpoints,
743
+ )
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama4/image_processing_llama4_fast.py ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Fast Image processor class for Got-OCR-2."""
16
+
17
+ import math
18
+ from collections import defaultdict
19
+ from functools import lru_cache
20
+ from typing import Optional, Union
21
+
22
+ from ...image_processing_utils import BatchFeature
23
+ from ...image_processing_utils_fast import (
24
+ BaseImageProcessorFast,
25
+ DefaultFastImageProcessorKwargs,
26
+ group_images_by_shape,
27
+ reorder_images,
28
+ )
29
+ from ...image_utils import ImageInput, PILImageResampling, SizeDict
30
+ from ...processing_utils import Unpack
31
+ from ...utils import (
32
+ TensorType,
33
+ auto_docstring,
34
+ is_torch_available,
35
+ is_torchvision_available,
36
+ is_torchvision_v2_available,
37
+ )
38
+
39
+
40
+ if is_torch_available():
41
+ import torch
42
+
43
+ if is_torchvision_available():
44
+ if is_torchvision_v2_available():
45
+ from torchvision.transforms.v2 import functional as F
46
+ else:
47
+ from torchvision.transforms import functional as F
48
+
49
+
50
+ def get_factors(dividend: int) -> set[int]:
51
+ """
52
+ Calculate all factors of a given number, i.e. a divisor that leaves
53
+ no remainder. For example, if dividend=12, it will return {1, 2, 3, 4, 6, 12}.
54
+
55
+ Args:
56
+ dividend (int): The number to find factors for.
57
+
58
+ Returns:
59
+ set: A set containing all factors of the number.
60
+ """
61
+ factors_set = set()
62
+
63
+ for i in range(1, int(dividend**0.5) + 1):
64
+ if dividend % i == 0:
65
+ factors_set.add(i)
66
+ factors_set.add(dividend // i)
67
+ return factors_set
68
+
69
+
70
+ def get_max_res_without_distortion(
71
+ image_size: tuple[int, int],
72
+ target_size: tuple[int, int],
73
+ ) -> tuple[int, int]:
74
+ """
75
+ Determines the maximum resolution to which an image can be resized to without distorting its
76
+ aspect ratio, based on the target resolution.
77
+
78
+ Args:
79
+ image_size (tuple[int, int]): The original resolution of the image (height, width).
80
+ target_resolution (tuple[int, int]): The desired resolution to fit the image into (height, width).
81
+ Returns:
82
+ tuple[int, int]: The optimal dimensions (height, width) to which the image should be resized.
83
+ Example:
84
+ >>> _get_max_res_without_distortion([200, 300], target_size = [450, 200])
85
+ (134, 200)
86
+ >>> _get_max_res_without_distortion([800, 600], target_size = [450, 1300])
87
+ (450, 338)
88
+ """
89
+
90
+ original_height, original_width = image_size
91
+ target_height, target_width = target_size
92
+
93
+ scale_w = target_width / original_width
94
+ scale_h = target_height / original_height
95
+
96
+ if scale_w < scale_h:
97
+ new_width = target_width
98
+ new_height = min(math.floor(original_height * scale_w), target_height)
99
+ else:
100
+ new_height = target_height
101
+ new_width = min(math.floor(original_width * scale_h), target_width)
102
+
103
+ return new_height, new_width
104
+
105
+
106
+ def split_to_tiles(images: torch.Tensor, num_tiles_height: int, num_tiles_width: int) -> torch.Tensor:
107
+ # Split image into number of required tiles (width x height)
108
+ batch_size, num_channels, height, width = images.size()
109
+ images = images.view(
110
+ batch_size,
111
+ num_channels,
112
+ num_tiles_height,
113
+ height // num_tiles_height,
114
+ num_tiles_width,
115
+ width // num_tiles_width,
116
+ )
117
+ # Permute dimensions to reorder the axes
118
+ image = images.permute(0, 2, 4, 1, 3, 5).contiguous()
119
+ # Reshape into the desired output shape (batch_size * 4, num_channels, width/2, height/2)
120
+ image = image.view(
121
+ batch_size,
122
+ num_tiles_width * num_tiles_height,
123
+ num_channels,
124
+ height // num_tiles_height,
125
+ width // num_tiles_width,
126
+ )
127
+ return image
128
+
129
+
130
+ @lru_cache(maxsize=1)
131
+ def find_supported_resolutions(max_num_chunks: int, patch_size: SizeDict) -> torch.Tensor:
132
+ """
133
+ Computes all of the allowed resolutions for a fixed number of chunks
134
+ and patch_size. Useful for when dividing an image into chunks.
135
+
136
+ Args:
137
+ max_num_chunks (int): Maximum number of chunks for processing.
138
+ patch_size (int): Size of the side of the patch.
139
+
140
+ Returns:
141
+ torch.Tensor: List of possible resolutions as tuples (height, width).
142
+
143
+ Example:
144
+ >>> max_num_chunks = 5
145
+ >>> patch_size = 224
146
+ >>> find_supported_resolutions(max_num_chunks, patch_size)
147
+ tensor([(224, 896), (448, 448), (224, 224), (896, 224), (224, 672),
148
+ (672, 224), (224, 448), (448, 224)])
149
+
150
+ Given max_num_chunks=4, patch_size=224, it will create a dictionary:
151
+ {
152
+ 0.25: [(1, 4)],
153
+ 1.0: [(2, 2), (1, 1)],
154
+ 4.0: [(4, 1)],
155
+ 0.33: [(1, 3)],
156
+ 3.0: [(3, 1)],
157
+ 0.5: [(1, 2)],
158
+ 2.0: [(2, 1)]
159
+ }
160
+
161
+ and return the resolutions multiplied by the patch_size:
162
+ [(1*224, 4*224), (2*224, 2*224), ..., (2*224, 1*224)]
163
+ """
164
+ height, width = patch_size.height, patch_size.width
165
+ if height != width:
166
+ raise ValueError("`size` must be square.")
167
+
168
+ patch_size = height
169
+
170
+ asp_dict = defaultdict(list)
171
+ for chunk_size in range(max_num_chunks, 0, -1):
172
+ _factors = sorted(get_factors(chunk_size))
173
+ _asp_ratios = [(factor, chunk_size // factor) for factor in _factors]
174
+ for height, width in _asp_ratios:
175
+ ratio_float = height / width
176
+ asp_dict[ratio_float].append((height, width))
177
+
178
+ # get the resolutions multiplied by the patch_size
179
+ possible_resolutions = []
180
+ for value in asp_dict.values():
181
+ for height, depth in value:
182
+ possible_resolutions.append((height * patch_size, depth * patch_size))
183
+
184
+ return possible_resolutions
185
+
186
+
187
+ def pad_to_best_fit(
188
+ images: "torch.Tensor",
189
+ target_size: tuple[int, int],
190
+ background_color: Union[int, tuple[int, int, int]] = 0,
191
+ ) -> "torch.Tensor":
192
+ """
193
+ Pads an image to fit the target size.
194
+
195
+ Args:
196
+ images (`np.ndarray`):
197
+ The images to pad.
198
+ background_color (`int` or `tuple[int, int, int]`, *optional*, defaults to 0):
199
+ The color to use for the padding. Can be an integer for single channel or a
200
+ tuple of integers representing for multi-channel images. If passed as integer
201
+ in mutli-channel mode, it will default to `0` in subsequent channels.
202
+ Returns:
203
+ `torch.Tensor`: The padded images.
204
+ """
205
+
206
+ num_channels = images.shape[1] if len(images.shape) == 4 else images.shape[0]
207
+ if isinstance(background_color, int):
208
+ background_color = [background_color] + [0] * (num_channels - 1)
209
+ elif len(background_color) != num_channels:
210
+ raise ValueError(
211
+ f"background_color must have no more than {num_channels} elements to match the number of channels"
212
+ )
213
+
214
+ height, width = images.shape[-2:]
215
+ target_height, target_width = target_size
216
+ paste_x_right = target_width - width
217
+ paste_y_right = target_height - height
218
+ padded_images = F.pad(images, padding=[0, 0, paste_x_right, paste_y_right], fill=background_color)
219
+
220
+ return padded_images
221
+
222
+
223
+ def get_best_fit(
224
+ image_size: tuple[int, int],
225
+ possible_resolutions: torch.Tensor,
226
+ resize_to_max_canvas: bool = False,
227
+ ) -> tuple[int, int]:
228
+ """
229
+ Determines the best canvas possible from a list of possible resolutions to, without distortion,
230
+ resize an image to.
231
+
232
+ For each possible resolution, calculates the scaling factors for
233
+ width and height, and selects the smallest one, which is the limiting side.
234
+ E.g. to match the canvas you can upscale height by 2x, and width by 1.5x,
235
+ therefore, the maximum upscaling you can do is min(2, 1.5) = 1.5.
236
+
237
+ If upscaling is possible (any of the scaling factors is greater than 1),
238
+ then picks the smallest upscaling factor > 1, unless resize_to_max_canvas is True.
239
+
240
+ If upscaling is not possible, then picks the largest scaling factor <= 1, i.e.
241
+ reduce downscaling as much as possible.
242
+
243
+ If there are multiple resolutions with the same max scale, we pick the one with the lowest area,
244
+ to minimize padding. E.g., the same image can be upscaled to 224x224 and 224x448, but the latter
245
+ has more padding.
246
+
247
+ Args:
248
+ image_size (tuple[int, int]): A tuple containing the height and width of the image.
249
+ possible_resolutions (torch.Tensor): A tensor of shape (N, 2) where each
250
+ row represents a possible resolution (height, width).
251
+ resize_to_max_canvas (bool): If True, will return the largest upscaling resolution.
252
+
253
+ Returns:
254
+ list[int]: The best resolution [height, width] for the given image.
255
+
256
+ Example:
257
+ >>> image_size = (200, 300)
258
+ >>> possible_resolutions = torch.tensor([[224, 672],
259
+ ... [672, 224],
260
+ ... [224, 448],
261
+ ... [448, 224],
262
+ ... [224, 224]])
263
+ >>> get_best_fit(image_size, possible_resolutions)
264
+ [224, 448]
265
+
266
+ We have:
267
+ scale_w = tensor([2.2400, 0.7467, 1.4933, 0.7467, 0.7467])
268
+ scale_h = tensor([1.1200, 3.3600, 1.1200, 2.2400, 1.1200])
269
+ scales = tensor([1.1200, 0.7467, 1.1200, 0.7467, 0.7467])
270
+ Only one of the scales > 1:
271
+ upscaling_possible = tensor([1.1200, 1.1200])
272
+ smallest_rescale = tensor(1.1200)
273
+ So we pick the resolution with the smallest smallest area:
274
+ areas = tensor([150528, 100352]) # [672, 224], [224, 448]
275
+ optimal_canvas = tensor([224, 448])
276
+ """
277
+
278
+ original_height, original_width = image_size
279
+
280
+ # get all possible resolutions heights/widths
281
+ target_heights, target_widths = (
282
+ possible_resolutions[:, 0],
283
+ possible_resolutions[:, 1],
284
+ )
285
+
286
+ # get scaling factors to resize the image without distortion
287
+ scale_w = target_widths / original_width
288
+ scale_h = target_heights / original_height
289
+
290
+ # get the min scale between width and height (limiting side -> no distortion)
291
+ scales = torch.where(scale_h > scale_w, scale_w, scale_h)
292
+
293
+ # filter only scales that allow upscaling
294
+ upscaling_options = scales[scales >= 1]
295
+ if len(upscaling_options) > 0:
296
+ if resize_to_max_canvas:
297
+ selected_scale = torch.max(upscaling_options)
298
+ else:
299
+ selected_scale = torch.min(upscaling_options)
300
+ else:
301
+ # no upscaling possible,
302
+ # get the minimum downscaling (max scale for scales<1)
303
+ downscaling_options = scales[scales < 1]
304
+ selected_scale = torch.max(downscaling_options)
305
+
306
+ # get all resolutions that support this scaling factor,
307
+ # e.g. you can upscale to 224x224, 224x448, 224x672 without distortion
308
+ chosen_canvas = possible_resolutions[scales == selected_scale]
309
+
310
+ # if there are multiple resolutions,
311
+ # get the one with minimum area to reduce padding
312
+ if len(chosen_canvas) > 1:
313
+ areas = chosen_canvas[:, 0] * chosen_canvas[:, 1]
314
+ optimal_idx = torch.argmin(areas)
315
+ optimal_canvas = chosen_canvas[optimal_idx]
316
+ else:
317
+ optimal_canvas = chosen_canvas[0]
318
+
319
+ return optimal_canvas
320
+
321
+
322
+ class Llama4ImageProcessorKwargs(DefaultFastImageProcessorKwargs):
323
+ """
324
+ max_patches (`int`, *optional*, defaults to 16):
325
+ The maximum number of patches to be extracted from the image.
326
+ Can be overridden by the `max_patches` parameter in the `preprocess` method.
327
+ resize_to_max_canvas (`bool`, *optional*, defaults to False):
328
+ Whether to resize the image to the maximum canvas size.
329
+ If True, picks the canvas the allows the largest resizing without distortion.
330
+ If False, downsample as little as possible, including no resizing at all,
331
+ but never upsample, unless the image is smaller than the patch size.
332
+ """
333
+
334
+ max_patches: Optional[int]
335
+ resize_to_max_canvas: Optional[bool]
336
+
337
+
338
+ @auto_docstring
339
+ class Llama4ImageProcessorFast(BaseImageProcessorFast):
340
+ resample = PILImageResampling.BILINEAR
341
+ image_mean = [0.5, 0.5, 0.5]
342
+ image_std = [0.5, 0.5, 0.5]
343
+ size = {"height": 336, "width": 336}
344
+ do_resize = True
345
+ do_rescale = True
346
+ do_normalize = True
347
+ do_convert_rgb = True
348
+ max_patches = 16
349
+ resize_to_max_canvas = False
350
+ valid_kwargs = Llama4ImageProcessorKwargs
351
+
352
+ def __init__(self, **kwargs: Unpack[Llama4ImageProcessorKwargs]):
353
+ super().__init__(**kwargs)
354
+
355
+ # Disable compilation here as conversion to bfloat16 causes differences in the output of the compiled and non-compiled versions
356
+ @torch.compiler.disable
357
+ def rescale_and_normalize(
358
+ self,
359
+ images: "torch.Tensor",
360
+ do_rescale: bool,
361
+ rescale_factor: float,
362
+ do_normalize: bool,
363
+ image_mean: Union[float, list[float]],
364
+ image_std: Union[float, list[float]],
365
+ ) -> "torch.Tensor":
366
+ """
367
+ Rescale and normalize images.
368
+ Override to rescale and normalize the images in torch.bfloat16 as in the original implementation
369
+ """
370
+ if do_rescale and do_normalize:
371
+ images = images.to(dtype=torch.bfloat16) * rescale_factor
372
+ images = self.normalize(images, image_mean, image_std)
373
+ elif do_rescale:
374
+ images = images * rescale_factor
375
+ elif do_normalize:
376
+ images = self.normalize(images, image_mean, image_std)
377
+
378
+ return images
379
+
380
+ @auto_docstring
381
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[Llama4ImageProcessorKwargs]) -> BatchFeature:
382
+ return super().preprocess(images, **kwargs)
383
+
384
+ def _preprocess(
385
+ self,
386
+ images: list["torch.Tensor"],
387
+ size: SizeDict,
388
+ max_patches: int,
389
+ resize_to_max_canvas: bool,
390
+ interpolation: Optional["F.InterpolationMode"],
391
+ do_rescale: bool,
392
+ rescale_factor: float,
393
+ do_normalize: bool,
394
+ image_mean: Optional[Union[float, list[float]]],
395
+ image_std: Optional[Union[float, list[float]]],
396
+ disable_grouping: Optional[bool],
397
+ return_tensors: Optional[Union[str, TensorType]],
398
+ **kwargs,
399
+ ) -> BatchFeature:
400
+ possible_resolutions = find_supported_resolutions(max_num_chunks=max_patches, patch_size=size)
401
+ possible_resolutions = torch.tensor(possible_resolutions, device=images[0].device)
402
+ # process images by batch, grouped by shape
403
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
404
+ grouped_processed_images = {}
405
+ grouped_aspect_ratios = {}
406
+ for shape, stacked_images in grouped_images.items():
407
+ image_size = stacked_images.shape[-2:]
408
+ target_size = get_best_fit(image_size, possible_resolutions, resize_to_max_canvas=resize_to_max_canvas)
409
+ # If target_size requires upscaling, we might want to limit the upscaling to max_upscaling_size
410
+ max_upscaling_size = None if resize_to_max_canvas else size.height
411
+ if max_upscaling_size is not None:
412
+ new_target_height = min(max(image_size[0], max_upscaling_size), target_size[0])
413
+ new_target_width = min(max(image_size[1], max_upscaling_size), target_size[1])
414
+ target_size_without_distortion = (new_target_height, new_target_width)
415
+
416
+ # resize to target_size while preserving aspect ratio
417
+ new_size_without_distortion = get_max_res_without_distortion(image_size, target_size_without_distortion)
418
+ new_size_without_distortion = SizeDict(
419
+ height=max(new_size_without_distortion[0], 1), width=max(new_size_without_distortion[1], 1)
420
+ )
421
+ processed_images = self.resize(
422
+ stacked_images,
423
+ new_size_without_distortion,
424
+ interpolation=interpolation,
425
+ )
426
+
427
+ # pad to target_size to be able to split into tiles
428
+ processed_images = pad_to_best_fit(processed_images, target_size)
429
+ processed_images = self.rescale_and_normalize(
430
+ processed_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
431
+ )
432
+
433
+ ratio_h, ratio_w = (
434
+ target_size[0] // size.height,
435
+ target_size[1] // size.width,
436
+ )
437
+ # split into tiles
438
+ processed_images = split_to_tiles(processed_images, ratio_h, ratio_w)
439
+ grouped_processed_images[shape] = processed_images
440
+ grouped_aspect_ratios[shape] = torch.tensor(
441
+ [[ratio_h, ratio_w]] * stacked_images.shape[0], device=images[0].device
442
+ )
443
+
444
+ # add a global tile to the processed tile if there are more than one tile
445
+ if ratio_h * ratio_w > 1:
446
+ global_tiles = self.resize(
447
+ stacked_images,
448
+ size,
449
+ interpolation=interpolation,
450
+ )
451
+ global_tiles = self.rescale_and_normalize(
452
+ global_tiles, do_rescale, rescale_factor, do_normalize, image_mean, image_std
453
+ )
454
+ grouped_processed_images[shape] = torch.cat([processed_images, global_tiles.unsqueeze(1)], dim=1)
455
+ processed_images = reorder_images(grouped_processed_images, grouped_images_index)
456
+ aspect_ratios_list = reorder_images(grouped_aspect_ratios, grouped_images_index)
457
+
458
+ processed_images = torch.cat(processed_images, dim=0) if return_tensors else processed_images
459
+ aspect_ratios = torch.stack(aspect_ratios_list, dim=0) if return_tensors else aspect_ratios_list
460
+ return BatchFeature(
461
+ data={"pixel_values": processed_images, "aspect_ratios": aspect_ratios}, tensor_type=return_tensors
462
+ )
463
+
464
+
465
+ __all__ = ["Llama4ImageProcessorFast"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama4/modeling_llama4.py ADDED
@@ -0,0 +1,1409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The LLAMA4 and HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ import math
17
+ from dataclasses import dataclass
18
+ from typing import Callable, Optional, Union
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ from transformers.models.llama4.configuration_llama4 import Llama4VisionConfig
25
+
26
+ from ...activations import ACT2FN
27
+ from ...cache_utils import Cache, DynamicCache
28
+ from ...generation import GenerationMixin
29
+ from ...integrations import use_kernel_forward_from_hub
30
+ from ...masking_utils import create_causal_mask, create_chunked_causal_mask
31
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
32
+ from ...modeling_layers import GradientCheckpointingLayer
33
+ from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPast, CausalLMOutputWithPast, ModelOutput
34
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
35
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
36
+ from ...processing_utils import Unpack
37
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
38
+ from ...utils.deprecation import deprecate_kwarg
39
+ from ...utils.generic import check_model_inputs
40
+ from .configuration_llama4 import Llama4Config, Llama4TextConfig
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ class Llama4TextExperts(nn.Module):
47
+ def __init__(self, config: Llama4TextConfig):
48
+ super().__init__()
49
+ self.num_experts = config.num_local_experts
50
+ self.intermediate_size = config.intermediate_size
51
+ self.hidden_size = config.hidden_size
52
+ self.expert_dim = self.intermediate_size
53
+ self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_size, 2 * self.expert_dim))
54
+ self.down_proj = nn.Parameter(torch.empty((self.num_experts, self.expert_dim, self.hidden_size)))
55
+ self.act_fn = ACT2FN[config.hidden_act]
56
+
57
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
58
+ """
59
+ This should really not be run on a single machine, as we are reaching compute bound:
60
+ - the inputs are expected to be "sorted" per expert already.
61
+ - the weights are viewed with another dim, to match num_expert, 1, shape * num_tokens, shape
62
+
63
+ Args:
64
+ hidden_states (torch.Tensor): (batch_size * token_num, hidden_size)
65
+ selected_experts (torch.Tensor): (batch_size * token_num, top_k)
66
+ routing_weights (torch.Tensor): (batch_size * token_num, top_k)
67
+ Returns:
68
+ torch.Tensor
69
+ """
70
+ hidden_states = hidden_states.view(self.gate_up_proj.shape[0], -1, self.hidden_size)
71
+ gate_up = torch.bmm(hidden_states, self.gate_up_proj)
72
+ gate, up = gate_up.chunk(2, dim=-1) # not supported for DTensors
73
+ next_states = torch.bmm((up * self.act_fn(gate)), self.down_proj)
74
+ next_states = next_states.view(-1, self.hidden_size)
75
+ return next_states
76
+
77
+
78
+ # Phi3MLP
79
+ class Llama4TextMLP(nn.Module):
80
+ def __init__(self, config, intermediate_size=None):
81
+ super().__init__()
82
+
83
+ if intermediate_size is None:
84
+ intermediate_size = config.intermediate_size
85
+
86
+ self.config = config
87
+ self.gate_proj = nn.Linear(config.hidden_size, intermediate_size, bias=False)
88
+ self.up_proj = nn.Linear(config.hidden_size, intermediate_size, bias=False)
89
+ self.down_proj = nn.Linear(intermediate_size, config.hidden_size, bias=False)
90
+ self.activation_fn = ACT2FN[config.hidden_act]
91
+
92
+ def forward(self, x):
93
+ down_proj = self.activation_fn(self.gate_proj(x)) * self.up_proj(x)
94
+ return self.down_proj(down_proj)
95
+
96
+
97
+ class Llama4TextL2Norm(torch.nn.Module):
98
+ def __init__(self, eps: float = 1e-6):
99
+ super().__init__()
100
+ self.eps = eps
101
+
102
+ def _norm(self, x):
103
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
104
+
105
+ def forward(self, x):
106
+ return self._norm(x.float()).type_as(x)
107
+
108
+ def extra_repr(self):
109
+ return f"eps={self.eps}"
110
+
111
+
112
+ class Llama4TextRMSNorm(nn.Module):
113
+ def __init__(self, hidden_size, eps=1e-5):
114
+ """
115
+ Llama4RMSNorm is equivalent to T5LayerNorm
116
+ """
117
+ super().__init__()
118
+ self.eps = eps
119
+ self.weight = nn.Parameter(torch.ones(hidden_size))
120
+
121
+ def _norm(self, x):
122
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
123
+
124
+ def forward(self, x):
125
+ output = self._norm(x.float()).type_as(x)
126
+ return output * self.weight
127
+
128
+ def extra_repr(self):
129
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
130
+
131
+
132
+ class Llama4Router(nn.Linear):
133
+ def __init__(self, config):
134
+ super().__init__(config.hidden_size, config.num_local_experts, bias=False)
135
+ self.num_experts = config.num_local_experts
136
+ self.top_k = config.num_experts_per_tok
137
+
138
+ def forward(self, hidden_states):
139
+ router_logits = super().forward(hidden_states)
140
+ router_top_value, router_indices = torch.topk(router_logits, self.top_k, dim=1)
141
+ router_scores = torch.full_like(router_logits, float("-inf")).scatter_(1, router_indices, router_top_value)
142
+ router_scores = torch.nn.functional.sigmoid(router_scores.float()).to(router_scores.dtype)
143
+ return router_scores, router_logits
144
+
145
+
146
+ @use_kernel_forward_from_hub("Llama4TextMoe")
147
+ class Llama4TextMoe(nn.Module):
148
+ def __init__(self, config):
149
+ super().__init__()
150
+ self.top_k = config.num_experts_per_tok
151
+ self.hidden_dim = config.hidden_size
152
+ self.num_experts = config.num_local_experts
153
+ self.experts = Llama4TextExperts(config)
154
+ self.router = Llama4Router(config)
155
+ self.shared_expert = Llama4TextMLP(config)
156
+
157
+ def forward(self, hidden_states):
158
+ hidden_states = hidden_states.reshape(-1, self.hidden_dim)
159
+ router_scores, router_logits = self.router(hidden_states)
160
+ routed_in = hidden_states.repeat(router_scores.shape[1], 1)
161
+ routed_in = routed_in * router_scores.reshape(-1, 1)
162
+ routed_out = self.experts(routed_in)
163
+ out = self.shared_expert(hidden_states)
164
+ out.add_(routed_out.reshape(router_scores.shape[1], -1, routed_out.shape[-1]).sum(dim=0))
165
+ return out, router_logits
166
+
167
+
168
+ class Llama4TextRotaryEmbedding(nn.Module):
169
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
170
+
171
+ def __init__(self, config: Llama4TextConfig, device=None):
172
+ super().__init__()
173
+ # BC: "rope_type" was originally "type"
174
+ self.rope_type = "llama3" if config.rope_scaling is not None else "default"
175
+
176
+ self.max_seq_len_cached = config.max_position_embeddings
177
+ self.original_max_seq_len = config.max_position_embeddings
178
+
179
+ self.config = config
180
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
181
+
182
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
183
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
184
+ self.original_inv_freq = self.inv_freq
185
+
186
+ @torch.no_grad()
187
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
188
+ def forward(self, x, position_ids):
189
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
190
+ position_ids_expanded = position_ids[:, None, :].float()
191
+
192
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
193
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
194
+ freqs = (inv_freq_expanded.to(x.device) @ position_ids_expanded).transpose(1, 2)
195
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # Convert to complex representation
196
+ freqs_cis = freqs_cis * self.attention_scaling
197
+
198
+ return freqs_cis
199
+
200
+
201
+ def apply_rotary_emb(
202
+ xq: torch.Tensor,
203
+ xk: torch.Tensor,
204
+ freqs_cis: torch.Tensor,
205
+ ) -> tuple[torch.Tensor, torch.Tensor]:
206
+ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
207
+ xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
208
+ xq_out = torch.view_as_real(xq_ * freqs_cis[:, :, None, :]).flatten(3)
209
+ xk_out = torch.view_as_real(xk_ * freqs_cis[:, :, None, :]).flatten(3)
210
+ return xq_out.type_as(xq), xk_out.type_as(xk)
211
+
212
+
213
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
214
+ """
215
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
216
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
217
+ """
218
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
219
+ if n_rep == 1:
220
+ return hidden_states
221
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
222
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
223
+
224
+
225
+ # Adapted from transformers.models.llama.modeling_llama.eager_attention_forward -> llama4 doesn't cast attn weights to fp32
226
+ def eager_attention_forward(
227
+ module: nn.Module,
228
+ query: torch.Tensor,
229
+ key: torch.Tensor,
230
+ value: torch.Tensor,
231
+ attention_mask: Optional[torch.Tensor],
232
+ scaling: float,
233
+ dropout: float = 0.0,
234
+ **kwargs,
235
+ ):
236
+ key_states = repeat_kv(key, module.num_key_value_groups)
237
+ value_states = repeat_kv(value, module.num_key_value_groups)
238
+
239
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
240
+ if attention_mask is not None:
241
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
242
+ attn_weights = attn_weights + causal_mask
243
+
244
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
245
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
246
+ attn_output = torch.matmul(attn_weights, value_states)
247
+ attn_output = attn_output.transpose(1, 2).contiguous()
248
+
249
+ return attn_output, attn_weights
250
+
251
+
252
+ # Adapted from transformers.models.llama.modeling_llama.eager_attention_forward -> llama4 doesn't cast attn weights to fp32
253
+ def vision_eager_attention_forward(
254
+ module: nn.Module,
255
+ query: torch.Tensor,
256
+ key: torch.Tensor,
257
+ value: torch.Tensor,
258
+ attention_mask: Optional[torch.Tensor],
259
+ scaling: float,
260
+ dropout: float = 0.0,
261
+ **kwargs,
262
+ ):
263
+ key_states = repeat_kv(key, module.num_key_value_groups)
264
+ value_states = repeat_kv(value, module.num_key_value_groups)
265
+
266
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * module.head_dim**-0.5
267
+ if attention_mask is not None:
268
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
269
+ attn_weights = attn_weights + causal_mask
270
+
271
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
272
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
273
+ attn_output = torch.matmul(attn_weights, value_states)
274
+ attn_output = attn_output.transpose(1, 2).contiguous()
275
+
276
+ return attn_output, attn_weights
277
+
278
+
279
+ class Llama4TextAttention(nn.Module):
280
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
281
+
282
+ def __init__(self, config: Llama4TextConfig, layer_idx):
283
+ super().__init__()
284
+ self.config = config
285
+ self.layer_idx = layer_idx
286
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
287
+ self.num_attention_heads = config.num_attention_heads
288
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
289
+ self.num_key_value_heads = config.num_key_value_heads
290
+ self.scaling = self.head_dim**-0.5
291
+ self.attn_scale = config.attn_scale
292
+ self.floor_scale = config.floor_scale
293
+ self.attn_temperature_tuning = config.attn_temperature_tuning
294
+ self.attention_dropout = config.attention_dropout
295
+ self.is_causal = True
296
+ self.use_rope = config.no_rope_layers[layer_idx]
297
+ self.q_proj = nn.Linear(
298
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
299
+ )
300
+ self.k_proj = nn.Linear(
301
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
302
+ )
303
+ self.v_proj = nn.Linear(
304
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
305
+ )
306
+ self.o_proj = nn.Linear(
307
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
308
+ )
309
+ if self.config.use_qk_norm and self.use_rope:
310
+ self.qk_norm = Llama4TextL2Norm(config.rms_norm_eps)
311
+
312
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
313
+ def forward(
314
+ self,
315
+ hidden_states: torch.Tensor,
316
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
317
+ attention_mask: Optional[torch.Tensor],
318
+ past_key_values: Optional[Cache] = None,
319
+ cache_position: Optional[torch.LongTensor] = None,
320
+ **kwargs: Unpack[FlashAttentionKwargs],
321
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
322
+ input_shape = hidden_states.shape[:-1]
323
+ hidden_shape = (*input_shape, -1, self.head_dim)
324
+
325
+ query_states = self.q_proj(hidden_states).view(hidden_shape)
326
+ key_states = self.k_proj(hidden_states).view(*input_shape, -1, self.head_dim)
327
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
328
+
329
+ if self.use_rope: # the 16E model skips rope for long context on certain layers
330
+ query_states, key_states = apply_rotary_emb(
331
+ query_states, key_states, position_embeddings.to(query_states.device)
332
+ )
333
+
334
+ if hasattr(self, "qk_norm"): # the 128E model does not use qk_norm
335
+ query_states = self.qk_norm(query_states)
336
+ key_states = self.qk_norm(key_states)
337
+
338
+ # Use temperature tuning from https://huggingface.co/papers/2501.19399) to NoROPE layers
339
+ if self.attn_temperature_tuning and not self.use_rope:
340
+ attn_scales = (
341
+ torch.log(torch.floor((cache_position.float() + 1.0) / self.floor_scale) + 1.0) * self.attn_scale + 1.0
342
+ )
343
+ attn_scales = attn_scales.view((1, input_shape[-1], 1, 1)).expand((*input_shape, 1, 1)) # batch size > 1
344
+ query_states = (query_states * attn_scales).to(query_states.dtype)
345
+
346
+ query_states = query_states.transpose(1, 2)
347
+ key_states = key_states.transpose(1, 2)
348
+
349
+ if past_key_values is not None:
350
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
351
+ cache_kwargs = {"cache_position": cache_position}
352
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
353
+
354
+ attention_interface: Callable = eager_attention_forward
355
+ if self.config._attn_implementation != "eager":
356
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
357
+ attn_output, attn_weights = attention_interface(
358
+ self,
359
+ query_states,
360
+ key_states,
361
+ value_states,
362
+ attention_mask,
363
+ dropout=0.0 if not self.training else self.attention_dropout,
364
+ scaling=self.scaling,
365
+ **kwargs,
366
+ )
367
+
368
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
369
+ attn_output = self.o_proj(attn_output)
370
+ return attn_output, attn_weights
371
+
372
+
373
+ class Llama4TextDecoderLayer(GradientCheckpointingLayer):
374
+ def __init__(self, config, layer_idx):
375
+ super().__init__()
376
+ self.hidden_size = config.hidden_size
377
+ self.layer_idx = layer_idx
378
+ self.attention_type = config.layer_types[layer_idx]
379
+ self.self_attn = Llama4TextAttention(config, layer_idx)
380
+ self.is_moe_layer = layer_idx in config.moe_layers
381
+ if self.is_moe_layer: # the 128E model interleaves dense / sparse
382
+ self.feed_forward = Llama4TextMoe(config)
383
+ else:
384
+ self.feed_forward = Llama4TextMLP(config, intermediate_size=config.intermediate_size_mlp)
385
+
386
+ self.input_layernorm = Llama4TextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
387
+ self.post_attention_layernorm = Llama4TextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
388
+
389
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
390
+ def forward(
391
+ self,
392
+ hidden_states: torch.Tensor,
393
+ attention_mask: Optional[torch.Tensor] = None,
394
+ position_ids: Optional[torch.LongTensor] = None,
395
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
396
+ use_cache: Optional[bool] = False,
397
+ cache_position: Optional[torch.LongTensor] = None,
398
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
399
+ **kwargs: Unpack[FlashAttentionKwargs],
400
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
401
+ residual = hidden_states
402
+
403
+ hidden_states = self.input_layernorm(hidden_states)
404
+
405
+ # Self Attention
406
+ attention_states, _ = self.self_attn(
407
+ hidden_states=hidden_states,
408
+ position_embeddings=position_embeddings,
409
+ attention_mask=attention_mask,
410
+ past_key_values=past_key_values,
411
+ use_cache=use_cache,
412
+ cache_position=cache_position,
413
+ **kwargs,
414
+ )
415
+ hidden_states = residual + attention_states
416
+
417
+ # Fully Connected
418
+ residual = hidden_states
419
+ hidden_states = self.post_attention_layernorm(hidden_states)
420
+ hidden_states = self.feed_forward(hidden_states)
421
+ if self.is_moe_layer:
422
+ hidden_states, _ = hidden_states
423
+ hidden_states = residual + hidden_states.view(residual.shape)
424
+ return hidden_states
425
+
426
+
427
+ @auto_docstring
428
+ class Llama4PreTrainedModel(PreTrainedModel):
429
+ config: Llama4Config
430
+ supports_gradient_checkpointing = True
431
+ _skip_keys_device_placement = ["past_key_values"]
432
+ _supports_flash_attn = False
433
+ _supports_sdpa = True
434
+ _supports_flex_attn = True
435
+
436
+ _can_compile_fullgraph = True
437
+ _supports_attention_backend = True
438
+
439
+ def _init_weights(self, module):
440
+ std = (
441
+ self.config.initializer_range
442
+ if hasattr(self.config, "initializer_range")
443
+ else self.config.text_config.initializer_range
444
+ )
445
+ if isinstance(module, nn.Linear):
446
+ module.weight.data.normal_(mean=0.0, std=std)
447
+ if module.bias is not None:
448
+ module.bias.data.zero_()
449
+ elif isinstance(module, nn.Embedding):
450
+ module.weight.data.normal_(mean=0.0, std=std)
451
+ if module.padding_idx is not None:
452
+ module.weight.data[module.padding_idx].zero_()
453
+ elif isinstance(module, nn.LayerNorm):
454
+ module.weight.data.fill_(1.0)
455
+ module.bias.data.zero_()
456
+ elif isinstance(module, Llama4TextRMSNorm):
457
+ module.weight.data.fill_(1.0)
458
+ elif isinstance(module, Llama4TextExperts):
459
+ module.gate_up_proj.data.normal_(mean=0.0, std=std)
460
+ module.down_proj.data.normal_(mean=0.0, std=std)
461
+ elif isinstance(module, Llama4VisionModel):
462
+ module.class_embedding.data.normal_(std=module.scale)
463
+ module.positional_embedding_vlm.data.normal_(std=module.scale)
464
+
465
+
466
+ @auto_docstring
467
+ class Llama4TextModel(Llama4PreTrainedModel):
468
+ _no_split_modules = ["Llama4TextDecoderLayer"]
469
+ base_model_prefix = "model"
470
+ config: Llama4TextConfig
471
+ _can_record_outputs = {
472
+ "attentions": Llama4TextAttention,
473
+ "hidden_states": Llama4TextDecoderLayer,
474
+ "router_logits": Llama4TextMoe,
475
+ }
476
+
477
+ def __init__(self, config: Llama4TextConfig):
478
+ super().__init__(config)
479
+ self.padding_idx = config.pad_token_id
480
+ self.vocab_size = config.vocab_size
481
+
482
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
483
+ self.layers = nn.ModuleList(
484
+ [Llama4TextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
485
+ )
486
+ self.norm = Llama4TextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
487
+ self.rotary_emb = Llama4TextRotaryEmbedding(config=config)
488
+ self.gradient_checkpointing = False
489
+
490
+ # Initialize weights and apply final processing
491
+ self.post_init()
492
+
493
+ @check_model_inputs
494
+ @auto_docstring
495
+ def forward(
496
+ self,
497
+ input_ids: torch.LongTensor = None,
498
+ attention_mask: Optional[torch.Tensor] = None,
499
+ position_ids: Optional[torch.LongTensor] = None,
500
+ past_key_values: Optional[Cache] = None,
501
+ inputs_embeds: Optional[torch.FloatTensor] = None,
502
+ use_cache: Optional[bool] = None,
503
+ cache_position: Optional[torch.LongTensor] = None,
504
+ **kwargs: Unpack[TransformersKwargs],
505
+ ) -> Union[tuple, BaseModelOutputWithPast]:
506
+ if (input_ids is None) ^ (inputs_embeds is not None):
507
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
508
+
509
+ if inputs_embeds is None:
510
+ inputs_embeds = self.embed_tokens(input_ids.to(self.embed_tokens.weight.device))
511
+
512
+ if use_cache and past_key_values is None:
513
+ past_key_values = DynamicCache(config=self.config)
514
+
515
+ if cache_position is None:
516
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
517
+ cache_position = torch.arange(
518
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
519
+ )
520
+
521
+ if position_ids is None:
522
+ position_ids = cache_position.unsqueeze(0)
523
+
524
+ # It may already have been prepared by e.g. `generate`
525
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
526
+ # Prepare mask arguments
527
+ mask_kwargs = {
528
+ "config": self.config,
529
+ "input_embeds": inputs_embeds,
530
+ "attention_mask": attention_mask,
531
+ "cache_position": cache_position,
532
+ "past_key_values": past_key_values,
533
+ "position_ids": position_ids,
534
+ }
535
+ # Create the masks
536
+ causal_mask_mapping = {
537
+ "full_attention": create_causal_mask(**mask_kwargs),
538
+ "chunked_attention": create_chunked_causal_mask(**mask_kwargs),
539
+ }
540
+
541
+ hidden_states = inputs_embeds
542
+
543
+ # create position embeddings to be shared across the decoder layers
544
+ freq_cis = self.rotary_emb(hidden_states, position_ids)
545
+
546
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
547
+ hidden_states = decoder_layer(
548
+ hidden_states,
549
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
550
+ position_ids=position_ids,
551
+ past_key_values=past_key_values,
552
+ use_cache=use_cache,
553
+ cache_position=cache_position,
554
+ position_embeddings=freq_cis,
555
+ **kwargs,
556
+ )
557
+ hidden_states = self.norm(hidden_states)
558
+
559
+ return BaseModelOutputWithPast(
560
+ last_hidden_state=hidden_states,
561
+ past_key_values=past_key_values if use_cache else None,
562
+ )
563
+
564
+
565
+ class Llama4ForCausalLM(Llama4PreTrainedModel, GenerationMixin):
566
+ _no_split_modules = ["Llama4TextDecoderLayer"]
567
+ base_model_prefix = "language_model"
568
+ _tied_weights_keys = ["lm_head.weight"]
569
+ _tp_plan = {"lm_head": "colwise_rep"}
570
+ config: Llama4TextConfig
571
+
572
+ def __init__(self, config: Llama4TextConfig):
573
+ super().__init__(config)
574
+ self.model = Llama4TextModel(config)
575
+ self.vocab_size = config.vocab_size
576
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
577
+
578
+ # Initialize weights and apply final processing
579
+ self.post_init()
580
+
581
+ def set_decoder(self, decoder):
582
+ self.model = decoder
583
+
584
+ def get_decoder(self):
585
+ return self.model
586
+
587
+ @can_return_tuple
588
+ @auto_docstring
589
+ def forward(
590
+ self,
591
+ input_ids: torch.LongTensor = None,
592
+ attention_mask: Optional[torch.Tensor] = None,
593
+ position_ids: Optional[torch.LongTensor] = None,
594
+ past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
595
+ inputs_embeds: Optional[torch.FloatTensor] = None,
596
+ labels: Optional[torch.LongTensor] = None,
597
+ use_cache: Optional[bool] = None,
598
+ cache_position: Optional[torch.LongTensor] = None,
599
+ logits_to_keep: Union[int, torch.Tensor] = 0,
600
+ **kwargs: Unpack[TransformersKwargs],
601
+ ) -> Union[tuple, CausalLMOutputWithPast]:
602
+ r"""
603
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
604
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
605
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
606
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
607
+
608
+ Example:
609
+
610
+ ```python
611
+ >>> from transformers import AutoTokenizer, Llama4ForCausalLM
612
+
613
+ >>> model = Llama4ForCausalLM.from_pretrained("meta-llama4/Llama4-2-7b-hf")
614
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama4/Llama4-2-7b-hf")
615
+
616
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
617
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
618
+
619
+ >>> # Generate
620
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
621
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
622
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
623
+ ```"""
624
+ outputs = self.model(
625
+ input_ids=input_ids,
626
+ attention_mask=attention_mask,
627
+ position_ids=position_ids,
628
+ past_key_values=past_key_values,
629
+ inputs_embeds=inputs_embeds,
630
+ use_cache=use_cache,
631
+ cache_position=cache_position,
632
+ **kwargs,
633
+ )
634
+
635
+ hidden_states = outputs[0]
636
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
637
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
638
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
639
+ loss = None
640
+ if labels is not None:
641
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
642
+
643
+ return CausalLMOutputWithPast(
644
+ loss=loss,
645
+ logits=logits,
646
+ past_key_values=outputs.past_key_values,
647
+ hidden_states=outputs.hidden_states,
648
+ attentions=outputs.attentions,
649
+ )
650
+
651
+
652
+ @dataclass
653
+ @auto_docstring(
654
+ custom_intro="""
655
+ Base class for Llava causal language model (or autoregressive) outputs.
656
+ """
657
+ )
658
+ class Llama4CausalLMOutputWithPast(ModelOutput):
659
+ r"""
660
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
661
+ Language modeling loss (for next-token prediction).
662
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
663
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
664
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
665
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
666
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
667
+
668
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
669
+ `past_key_values` input) to speed up sequential decoding.
670
+ image_hidden_states (`torch.FloatTensor`, *optional*):
671
+ A `torch.FloatTensor` of size (batch_size, num_images, sequence_length, hidden_size)`.
672
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
673
+ """
674
+
675
+ loss: Optional[torch.FloatTensor] = None
676
+ logits: torch.FloatTensor = None
677
+ past_key_values: Optional[list[torch.FloatTensor]] = None
678
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
679
+ attentions: Optional[tuple[torch.FloatTensor]] = None
680
+ image_hidden_states: Optional[torch.FloatTensor] = None
681
+
682
+
683
+ class Llama4VisionMLP2(torch.nn.Module):
684
+ def __init__(self, config):
685
+ super().__init__()
686
+ self.hidden_size = config.hidden_size
687
+ self.intermediate_size = config.intermediate_size
688
+ self.fc1 = nn.Linear(self.intermediate_size, config.projector_input_dim, bias=False)
689
+ self.fc2 = nn.Linear(config.projector_output_dim, config.projector_output_dim, bias=False)
690
+ self.activation_fn = nn.GELU() # ACT2FN[config.hidden_act]
691
+ self.dropout = config.projector_dropout
692
+
693
+ def forward(self, hidden_states):
694
+ hidden_states = self.fc1(hidden_states)
695
+ hidden_states = self.activation_fn(hidden_states)
696
+ hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training)
697
+ return self.activation_fn(self.fc2(hidden_states))
698
+
699
+
700
+ class Llama4MultiModalProjector(nn.Module):
701
+ def __init__(self, config):
702
+ super().__init__()
703
+ self.linear_1 = nn.Linear(
704
+ config.vision_config.vision_output_dim,
705
+ config.text_config.hidden_size,
706
+ bias=False,
707
+ )
708
+
709
+ def forward(self, image_features):
710
+ hidden_states = self.linear_1(image_features)
711
+ return hidden_states
712
+
713
+
714
+ def pixel_shuffle(input_tensor, shuffle_ratio):
715
+ # input_tensor: [batch_size, num_patches, channels]
716
+ batch_size, num_patches, channels = input_tensor.shape
717
+ patch_size = int(math.sqrt(num_patches))
718
+
719
+ input_tensor = input_tensor.view(batch_size, patch_size, patch_size, -1)
720
+ batch_size, height, width, channels = input_tensor.size()
721
+
722
+ reshaped_tensor = input_tensor.view(batch_size, height, int(width * shuffle_ratio), int(channels / shuffle_ratio))
723
+ reshaped_tensor = reshaped_tensor.permute(0, 2, 1, 3).contiguous()
724
+
725
+ reshaped_tensor = reshaped_tensor.view(
726
+ batch_size, int(height * shuffle_ratio), int(width * shuffle_ratio), int(channels / (shuffle_ratio**2))
727
+ )
728
+ reshaped_tensor = reshaped_tensor.permute(0, 2, 1, 3).contiguous()
729
+
730
+ output_tensor = reshaped_tensor.view(batch_size, -1, reshaped_tensor.shape[-1])
731
+ return output_tensor
732
+
733
+
734
+ class Llama4VisionPixelShuffleMLP(nn.Module):
735
+ def __init__(self, config):
736
+ super().__init__()
737
+ self.pixel_shuffle_ratio = config.pixel_shuffle_ratio
738
+ self.inner_dim = int(config.projector_input_dim // (self.pixel_shuffle_ratio**2))
739
+ self.output_dim = config.projector_output_dim
740
+ self.mlp = Llama4VisionMLP2(config)
741
+
742
+ def forward(self, encoded_patches: torch.Tensor) -> torch.Tensor:
743
+ encoded_patches = pixel_shuffle(encoded_patches, self.pixel_shuffle_ratio)
744
+ return self.mlp(encoded_patches)
745
+
746
+
747
+ # TODO there is a different RoPE for vision encoder, defined as below
748
+ def reshape_for_broadcast(freqs_ci: torch.Tensor, query: torch.Tensor):
749
+ ndim = query.ndim
750
+ shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(query.shape)]
751
+ return freqs_ci.view(*shape)
752
+
753
+
754
+ def vision_apply_rotary_emb(
755
+ query: torch.Tensor,
756
+ key: torch.Tensor,
757
+ freqs_ci: torch.Tensor,
758
+ ) -> tuple[torch.Tensor, torch.Tensor]:
759
+ query_ = torch.view_as_complex(query.float().reshape(*query.shape[:-1], -1, 2))
760
+ key_ = torch.view_as_complex(key.float().reshape(*key.shape[:-1], -1, 2))
761
+ freqs_ci = reshape_for_broadcast(freqs_ci=freqs_ci, query=query_) # freqs_ci[:,:,None,:]
762
+ freqs_ci = freqs_ci.to(query_.device)
763
+ query_out = torch.view_as_real(query_ * freqs_ci).flatten(3)
764
+ key_out = torch.view_as_real(key_ * freqs_ci).flatten(3)
765
+ return query_out.type_as(query), key_out.type_as(key) # but this drops to 8e-3
766
+
767
+
768
+ class Llama4VisionAttention(nn.Module):
769
+ def __init__(self, config: Llama4VisionConfig):
770
+ super().__init__()
771
+ self.config = config
772
+ self.embed_dim = config.hidden_size
773
+ self.num_heads = config.num_attention_heads
774
+ self.head_dim = config.hidden_size // config.num_attention_heads
775
+ self.num_key_value_groups = 1
776
+ self.attention_dropout = config.attention_dropout
777
+ self.scaling = self.head_dim**-0.5
778
+
779
+ self.q_proj = nn.Linear(self.embed_dim, self.num_heads * self.head_dim, bias=True)
780
+ self.k_proj = nn.Linear(self.embed_dim, self.num_heads * self.head_dim, bias=True)
781
+ self.v_proj = nn.Linear(self.embed_dim, self.num_heads * self.head_dim, bias=True)
782
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.embed_dim, bias=True)
783
+
784
+ def forward(
785
+ self,
786
+ hidden_states: torch.Tensor,
787
+ freqs_ci: torch.Tensor,
788
+ attention_mask: Optional[torch.Tensor] = None,
789
+ past_key_values: Optional[Cache] = None,
790
+ **kwargs: Unpack[FlashAttentionKwargs],
791
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
792
+ input_shape = hidden_states.shape[:-1]
793
+ hidden_shape = (*input_shape, -1, self.head_dim)
794
+
795
+ query_states = self.q_proj(hidden_states).view(hidden_shape)
796
+ key_states = self.k_proj(hidden_states).view(hidden_shape)
797
+ value_states = self.v_proj(hidden_states).view(hidden_shape)
798
+
799
+ query_states, key_states = vision_apply_rotary_emb(query_states, key_states, freqs_ci=freqs_ci)
800
+
801
+ query_states = query_states.transpose(1, 2)
802
+ key_states = key_states.transpose(1, 2)
803
+ value_states = value_states.transpose(1, 2)
804
+
805
+ attention_interface: Callable = vision_eager_attention_forward
806
+ # flex disable because breaks on TP 8, embed is 88 not power of 2
807
+ if self.config._attn_implementation not in ["eager", "flex_attention"]:
808
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
809
+
810
+ attn_output, attn_weights = attention_interface(
811
+ self,
812
+ query_states,
813
+ key_states,
814
+ value_states,
815
+ None,
816
+ dropout=0.0 if not self.training else self.attention_dropout,
817
+ scaling=None, # TODO Might be enforced here for TP compatibility as scaling is not just sqrt(head_dim)
818
+ is_causal=False, # HAS TO BE ENFORCED
819
+ **kwargs,
820
+ )
821
+
822
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
823
+ attn_output = self.o_proj(attn_output)
824
+ return attn_output, attn_weights
825
+
826
+
827
+ class Llama4VisionMLP(nn.Module):
828
+ def __init__(self, config):
829
+ super().__init__()
830
+ self.config = config
831
+ self.activation_fn = nn.GELU() # ACT2FN[config.hidden_act]
832
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=True)
833
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=True)
834
+
835
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
836
+ hidden_states = self.fc1(hidden_states)
837
+ hidden_states = self.activation_fn(hidden_states)
838
+ hidden_states = self.fc2(hidden_states)
839
+ return hidden_states
840
+
841
+
842
+ class Llama4VisionEncoderLayer(GradientCheckpointingLayer):
843
+ def __init__(self, config: Llama4VisionConfig):
844
+ super().__init__()
845
+ self.hidden_size = config.hidden_size
846
+
847
+ self.self_attn = Llama4VisionAttention(config)
848
+ self.mlp = Llama4VisionMLP(config)
849
+
850
+ self.input_layernorm = nn.LayerNorm(config.hidden_size)
851
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size)
852
+
853
+ def forward(
854
+ self,
855
+ hidden_state: torch.Tensor,
856
+ freqs_ci: torch.Tensor,
857
+ attention_mask: Optional[torch.Tensor] = None,
858
+ output_attentions: Optional[bool] = None,
859
+ ):
860
+ # Self Attention
861
+ residual = hidden_state
862
+
863
+ hidden_state = self.input_layernorm(hidden_state)
864
+
865
+ hidden_state, attn_weights = self.self_attn(
866
+ hidden_state,
867
+ freqs_ci=freqs_ci,
868
+ attention_mask=attention_mask,
869
+ )
870
+ hidden_state = residual + hidden_state
871
+
872
+ # Feed forward
873
+ residual = hidden_state
874
+ hidden_state = self.post_attention_layernorm(hidden_state)
875
+ hidden_state = self.mlp(hidden_state)
876
+ hidden_state = residual + hidden_state
877
+
878
+ outputs = (hidden_state,)
879
+
880
+ if output_attentions:
881
+ outputs += (attn_weights,)
882
+
883
+ return outputs
884
+
885
+
886
+ class Llama4VisionEncoder(nn.Module):
887
+ """
888
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
889
+ [`Llama4VisionEncoderLayer`].
890
+
891
+ Args:
892
+ config: Llama4VisionConfig
893
+ """
894
+
895
+ def __init__(self, config: Llama4VisionConfig):
896
+ super().__init__()
897
+ self.config = config
898
+ self.layers = nn.ModuleList([Llama4VisionEncoderLayer(config) for _ in range(config.num_hidden_layers)])
899
+ self.gradient_checkpointing = False
900
+ self.config = config
901
+
902
+ def forward(
903
+ self,
904
+ hidden_states: torch.Tensor,
905
+ freqs_ci: torch.Tensor, # TODO move this to an attribute instead of keeping it around
906
+ attention_mask: Optional[torch.Tensor] = None,
907
+ output_attentions: Optional[bool] = None,
908
+ output_hidden_states: Optional[bool] = None,
909
+ return_dict: Optional[bool] = None,
910
+ ) -> Union[tuple, BaseModelOutput]:
911
+ r"""
912
+ Args:
913
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
914
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
915
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
916
+ than the model's internal embedding lookup matrix.
917
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
918
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
919
+
920
+ - 1 for tokens that are **not masked**,
921
+ - 0 for tokens that are **masked**.
922
+
923
+ [What are attention masks?](../glossary#attention-mask)
924
+ output_attentions (`bool`, *optional*):
925
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
926
+ returned tensors for more detail.
927
+ output_hidden_states (`bool`, *optional*):
928
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
929
+ for more detail.
930
+ return_dict (`bool`, *optional*):
931
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
932
+ """
933
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
934
+ output_hidden_states = (
935
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
936
+ )
937
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
938
+
939
+ encoder_states = () if output_hidden_states else None
940
+ all_attentions = () if output_attentions else None
941
+
942
+ for encoder_layer in self.layers:
943
+ if output_hidden_states:
944
+ encoder_states = encoder_states + (hidden_states,)
945
+
946
+ layer_outputs = encoder_layer(
947
+ hidden_state=hidden_states,
948
+ attention_mask=attention_mask,
949
+ output_attentions=output_attentions,
950
+ freqs_ci=freqs_ci,
951
+ )
952
+
953
+ if output_attentions:
954
+ all_attentions = all_attentions + (layer_outputs[1],)
955
+
956
+ hidden_states = layer_outputs[0]
957
+
958
+ if output_hidden_states:
959
+ encoder_states = encoder_states + (hidden_states,)
960
+
961
+ if not return_dict:
962
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
963
+ return BaseModelOutput(
964
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
965
+ )
966
+
967
+
968
+ class Llama4UnfoldConvolution(nn.Module):
969
+ def __init__(self, config):
970
+ super().__init__()
971
+ kernel_size = config.patch_size
972
+ if isinstance(kernel_size, int):
973
+ kernel_size = (kernel_size, kernel_size)
974
+ self.unfold = torch.nn.Unfold(kernel_size=kernel_size, stride=config.patch_size)
975
+ self.linear = nn.Linear(
976
+ config.num_channels * kernel_size[0] * kernel_size[1],
977
+ config.hidden_size,
978
+ bias=False,
979
+ )
980
+
981
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
982
+ hidden_states = self.unfold(hidden_states)
983
+ hidden_states = hidden_states.permute(0, 2, 1)
984
+ hidden_states = self.linear(hidden_states)
985
+ return hidden_states
986
+
987
+
988
+ class Llama4VisionRotaryEmbedding(nn.Module):
989
+ def __init__(self, config):
990
+ super().__init__()
991
+ idx = config.image_size // config.patch_size
992
+ img_idx = torch.arange(idx**2, dtype=torch.int32).reshape(idx**2, 1)
993
+ img_idx = torch.cat([img_idx, img_idx[:1]], dim=0)
994
+ img_idx[-1, -1] = -2 # ID_CLS_TOKEN
995
+ frequencies_x = img_idx % idx # get the coordinates of the 2d matrix along x
996
+ frequencies_y = img_idx // idx # get the coordinates of the 2d matrix along y
997
+ freq_dim = config.hidden_size // config.num_attention_heads // 2
998
+ rope_freq = 1.0 / (config.rope_theta ** (torch.arange(0, freq_dim, 2)[: (freq_dim // 2)].float() / freq_dim))
999
+ freqs_x = ((frequencies_x + 1)[..., None] * rope_freq[None, None, :]).repeat_interleave(2, dim=-1)
1000
+ freqs_y = ((frequencies_y + 1)[..., None] * rope_freq[None, None, :]).repeat_interleave(2, dim=-1)
1001
+ freqs = torch.cat([freqs_x, freqs_y], dim=-1).float().contiguous()[..., ::2]
1002
+ freqs = freqs.masked_fill(img_idx.reshape(-1, 1, 1) < 0, 0)
1003
+ freq_cis = torch.view_as_complex(torch.stack([torch.cos(freqs), torch.sin(freqs)], dim=-1))
1004
+ self.freqs_ci = freq_cis # idx**2, idx**2, idx * 2
1005
+
1006
+ def forward(self, hidden_states):
1007
+ return self.freqs_ci.to(hidden_states.device)
1008
+
1009
+
1010
+ class Llama4VisionModel(Llama4PreTrainedModel):
1011
+ base_model_prefix = "vision_model"
1012
+ _no_split_modules = ["Llama4VisionEncoderLayer"]
1013
+ config: Llama4VisionConfig
1014
+
1015
+ def __init__(self, config: Llama4VisionConfig):
1016
+ super().__init__(config)
1017
+ self.image_size = config.image_size
1018
+ self.patch_size = config.patch_size
1019
+ self.hidden_size = config.hidden_size
1020
+ self.num_channels = config.num_channels
1021
+
1022
+ self.num_patches = (self.image_size // self.patch_size) ** 2 + 1
1023
+ self.scale = config.hidden_size**-0.5
1024
+
1025
+ self.patch_embedding = Llama4UnfoldConvolution(config)
1026
+
1027
+ self.class_embedding = nn.Parameter(self.scale * torch.randn(self.hidden_size))
1028
+ self.positional_embedding_vlm = nn.Parameter(self.scale * torch.randn(self.num_patches, self.hidden_size))
1029
+ self.rotary_embedding = Llama4VisionRotaryEmbedding(config)
1030
+
1031
+ # layer norms
1032
+ self.layernorm_pre = nn.LayerNorm(self.hidden_size)
1033
+ self.layernorm_post = nn.LayerNorm(self.hidden_size)
1034
+
1035
+ # encoders
1036
+ self.model = Llama4VisionEncoder(config)
1037
+ self.vision_adapter = Llama4VisionPixelShuffleMLP(config)
1038
+ self.post_init()
1039
+
1040
+ def get_input_embeddings(self):
1041
+ """
1042
+ This function is used to fetch the first embedding layer to activate grads on inputs.
1043
+ """
1044
+ return self.patch_embedding
1045
+
1046
+ def forward(
1047
+ self,
1048
+ pixel_values: torch.Tensor,
1049
+ attention_mask: Optional[torch.Tensor] = None,
1050
+ output_attentions: Optional[bool] = None,
1051
+ output_hidden_states: Optional[bool] = None,
1052
+ return_dict: Optional[bool] = None,
1053
+ ) -> Union[BaseModelOutput, tuple[torch.Tensor, ...]]:
1054
+ r"""
1055
+
1056
+ Example:
1057
+
1058
+ ```python
1059
+ >>> from PIL import Image
1060
+ >>> import requests
1061
+ >>> from transformers import AutoProcessor, MllamaVisionModel
1062
+
1063
+ >>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
1064
+ >>> model = MllamaVisionModel.from_pretrained(checkpoint)
1065
+ >>> processor = AutoProcessor.from_pretrained(checkpoint)
1066
+
1067
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
1068
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1069
+ >>> inputs = processor(images=image, return_tensors="pt")
1070
+
1071
+ >>> output = model(**inputs)
1072
+
1073
+ >>> print(output.last_hidden_state.shape)
1074
+ torch.Size([1, 1, 4, 1025, 7680])
1075
+ ```
1076
+ """
1077
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1078
+ output_hidden_states = (
1079
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1080
+ )
1081
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1082
+
1083
+ # num_concurrent_media and num_chunks are both currently 1
1084
+ batch_size_times_num_tiles, num_channels, height, width = pixel_values.shape
1085
+ num_concurrent_media = 1
1086
+ num_chunks = 1
1087
+ hidden_state = self.patch_embedding(pixel_values)
1088
+ _, num_patches, hidden_dim = hidden_state.shape
1089
+
1090
+ # Add cls token
1091
+ hidden_state = hidden_state.reshape(
1092
+ batch_size_times_num_tiles * num_concurrent_media * num_chunks, num_patches, hidden_dim
1093
+ )
1094
+ class_embedding = self.class_embedding.expand(hidden_state.shape[0], 1, hidden_state.shape[-1])
1095
+ hidden_state = torch.cat([hidden_state, class_embedding], dim=1)
1096
+ num_patches += 1
1097
+
1098
+ # Position embeddings
1099
+ hidden_state = hidden_state.reshape(
1100
+ batch_size_times_num_tiles * num_concurrent_media, num_chunks, num_patches, hidden_dim
1101
+ )
1102
+ positional_embedding = self.positional_embedding_vlm.to(dtype=hidden_state.dtype, device=hidden_state.device)
1103
+ hidden_state = hidden_state + positional_embedding
1104
+
1105
+ hidden_state = self.layernorm_pre(hidden_state)
1106
+
1107
+ hidden_state = hidden_state.view(batch_size_times_num_tiles, -1, hidden_dim)
1108
+ freqs_ci = self.rotary_embedding(pixel_values)
1109
+
1110
+ output = self.model(
1111
+ hidden_state,
1112
+ attention_mask=None,
1113
+ output_hidden_states=output_hidden_states,
1114
+ output_attentions=output_attentions,
1115
+ freqs_ci=freqs_ci,
1116
+ )
1117
+
1118
+ hidden_state = output.last_hidden_state
1119
+
1120
+ hidden_state = self.layernorm_post(hidden_state)
1121
+
1122
+ hidden_state = hidden_state[:, :-1, :]
1123
+
1124
+ # now, we use Llama4VisionPixelShuffle + mlp to project embeddings
1125
+ hidden_state = self.vision_adapter(hidden_state)
1126
+
1127
+ hidden_states = output.hidden_states if output_hidden_states else None
1128
+
1129
+ if output_attentions:
1130
+ attentions = output[2]
1131
+ else:
1132
+ attentions = None
1133
+
1134
+ if not return_dict:
1135
+ return tuple(v for v in [hidden_state, hidden_states, attentions] if v is not None)
1136
+
1137
+ return BaseModelOutput(
1138
+ last_hidden_state=hidden_state,
1139
+ hidden_states=hidden_states,
1140
+ attentions=attentions,
1141
+ )
1142
+
1143
+
1144
+ class Llama4ForConditionalGeneration(Llama4PreTrainedModel, GenerationMixin):
1145
+ _no_split_modules = ["Llama4TextDecoderLayer", "Llama4VisionEncoderLayer"]
1146
+ _tp_plan = {}
1147
+ base_model_prefix = ""
1148
+ config: Llama4Config
1149
+
1150
+ def __init__(self, config: Llama4Config):
1151
+ super().__init__(config)
1152
+ self.vision_model = Llama4VisionModel(config.vision_config)
1153
+
1154
+ self.multi_modal_projector = Llama4MultiModalProjector(config)
1155
+ self.language_model = Llama4ForCausalLM(config.text_config)
1156
+ self.vocab_size = config.text_config.vocab_size
1157
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
1158
+
1159
+ self.post_init()
1160
+
1161
+ def get_input_embeddings(self):
1162
+ return self.language_model.get_input_embeddings()
1163
+
1164
+ def set_input_embeddings(self, value):
1165
+ self.language_model.set_input_embeddings(value)
1166
+
1167
+ def get_output_embeddings(self):
1168
+ return self.language_model.get_output_embeddings()
1169
+
1170
+ def set_output_embeddings(self, new_embeddings):
1171
+ self.language_model.set_output_embeddings(new_embeddings)
1172
+
1173
+ def set_decoder(self, decoder):
1174
+ self.language_model.set_decoder(decoder)
1175
+
1176
+ def get_decoder(self):
1177
+ return self.language_model.get_decoder()
1178
+
1179
+ def get_image_features(
1180
+ self,
1181
+ pixel_values: torch.FloatTensor,
1182
+ vision_feature_layer: Union[int, list[int]],
1183
+ vision_feature_select_strategy: str,
1184
+ **kwargs,
1185
+ ):
1186
+ """
1187
+ Obtains image last hidden states from the vision tower and apply al projection.
1188
+
1189
+ Args:
1190
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
1191
+ The tensors corresponding to the input images.
1192
+ vision_feature_layer (`Union[int, list[int]]`):
1193
+ The index of the layer to select the vision feature. If multiple indices are provided,
1194
+ the vision feature of the corresponding indices will be concatenated to form the
1195
+ vision features.
1196
+ vision_feature_select_strategy (`str`):
1197
+ The feature selection strategy used to select the vision feature from the vision backbone.
1198
+ Can be one of `"default"` or `"full"`
1199
+ Returns:
1200
+ image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
1201
+ """
1202
+ if vision_feature_select_strategy not in ["default", "full"]:
1203
+ raise ValueError(f"Unexpected select feature strategy: {self.vision_feature_select_strategy}")
1204
+ kwargs = {k: v for k, v in kwargs.items() if v is not None}
1205
+ image_outputs = self.vision_model(pixel_values, output_hidden_states=False, **kwargs)
1206
+ hidden_state = image_outputs.last_hidden_state
1207
+ return hidden_state
1208
+
1209
+ def get_placeholder_mask(
1210
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
1211
+ ):
1212
+ """
1213
+ Obtains multimodal placeholdr mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
1214
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
1215
+ """
1216
+ if input_ids is None:
1217
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
1218
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
1219
+ )
1220
+ special_image_mask = special_image_mask.all(-1)
1221
+ else:
1222
+ special_image_mask = input_ids == self.config.image_token_id
1223
+
1224
+ n_image_tokens = special_image_mask.sum()
1225
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
1226
+ if inputs_embeds[special_image_mask].numel() != image_features.numel():
1227
+ raise ValueError(
1228
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.shape[0]}"
1229
+ )
1230
+ return special_image_mask
1231
+
1232
+ @auto_docstring
1233
+ def forward(
1234
+ self,
1235
+ input_ids: torch.LongTensor = None,
1236
+ pixel_values: torch.FloatTensor = None,
1237
+ attention_mask: Optional[torch.Tensor] = None,
1238
+ position_ids: Optional[torch.LongTensor] = None,
1239
+ past_key_values: Optional[Cache] = None,
1240
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1241
+ vision_feature_layer: Optional[Union[int, list[int]]] = None,
1242
+ vision_feature_select_strategy: Optional[str] = None,
1243
+ labels: Optional[torch.LongTensor] = None,
1244
+ use_cache: Optional[bool] = None,
1245
+ output_attentions: Optional[bool] = None,
1246
+ output_hidden_states: Optional[bool] = None,
1247
+ return_dict: Optional[bool] = None,
1248
+ cache_position: Optional[torch.LongTensor] = None,
1249
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1250
+ image_sizes: torch.Tensor = None,
1251
+ **kwargs: Unpack[TransformersKwargs],
1252
+ ) -> Union[tuple, Llama4CausalLMOutputWithPast]:
1253
+ r"""
1254
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1255
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1256
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1257
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1258
+
1259
+ Example:
1260
+
1261
+ ```python
1262
+ >>> from PIL import Image
1263
+ >>> import requests
1264
+ >>> from transformers import AutoProcessor, LlavaForConditionalGeneration
1265
+
1266
+ >>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
1267
+ >>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
1268
+
1269
+ >>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
1270
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
1271
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1272
+
1273
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
1274
+
1275
+ >>> # Generate
1276
+ >>> generate_ids = model.generate(**inputs, max_new_tokens=15)
1277
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1278
+ "USER: \nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed"
1279
+ ```"""
1280
+
1281
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1282
+ output_hidden_states = (
1283
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1284
+ )
1285
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1286
+ vision_feature_layer = (
1287
+ vision_feature_layer
1288
+ if vision_feature_layer is not None
1289
+ else self.config.vision_config.vision_feature_layer
1290
+ )
1291
+ vision_feature_select_strategy = (
1292
+ vision_feature_select_strategy
1293
+ if vision_feature_select_strategy is not None
1294
+ else self.config.vision_config.vision_feature_select_strategy
1295
+ )
1296
+
1297
+ if (input_ids is None) ^ (inputs_embeds is not None):
1298
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1299
+
1300
+ if pixel_values is not None and inputs_embeds is not None:
1301
+ raise ValueError(
1302
+ "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
1303
+ )
1304
+
1305
+ if inputs_embeds is None:
1306
+ inputs_embeds = self.get_input_embeddings()(input_ids)
1307
+
1308
+ if pixel_values is not None:
1309
+ image_features = self.get_image_features(
1310
+ pixel_values=pixel_values,
1311
+ vision_feature_layer=vision_feature_layer,
1312
+ vision_feature_select_strategy=vision_feature_select_strategy,
1313
+ image_sizes=image_sizes,
1314
+ )
1315
+
1316
+ vision_flat = image_features.view(-1, image_features.size(-1))
1317
+ projected_vision_flat = self.multi_modal_projector(vision_flat).to(
1318
+ inputs_embeds.device, inputs_embeds.dtype
1319
+ )
1320
+ special_image_mask = self.get_placeholder_mask(
1321
+ input_ids, inputs_embeds=inputs_embeds, image_features=projected_vision_flat
1322
+ )
1323
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, projected_vision_flat)
1324
+
1325
+ outputs = self.language_model(
1326
+ attention_mask=attention_mask,
1327
+ position_ids=position_ids,
1328
+ past_key_values=past_key_values,
1329
+ inputs_embeds=inputs_embeds,
1330
+ use_cache=use_cache,
1331
+ output_attentions=output_attentions,
1332
+ output_hidden_states=output_hidden_states,
1333
+ return_dict=return_dict,
1334
+ cache_position=cache_position,
1335
+ logits_to_keep=logits_to_keep,
1336
+ **kwargs,
1337
+ )
1338
+
1339
+ logits = outputs[0]
1340
+
1341
+ loss = None
1342
+ if labels is not None:
1343
+ # Shift so that tokens < n predict n
1344
+ if attention_mask is not None:
1345
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
1346
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
1347
+ shift_attention_mask = attention_mask[:, -(logits.shape[1] - 1) :].to(logits.device)
1348
+ shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous()
1349
+ shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
1350
+ else:
1351
+ shift_logits = logits[..., :-1, :].contiguous()
1352
+ shift_labels = labels[..., 1:].contiguous()
1353
+ # Flatten the tokens
1354
+ loss_fct = nn.CrossEntropyLoss()
1355
+ loss = loss_fct(
1356
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)
1357
+ )
1358
+
1359
+ if not return_dict:
1360
+ output = (logits,) + outputs[1:]
1361
+ return (loss,) + output if loss is not None else output
1362
+
1363
+ return Llama4CausalLMOutputWithPast(
1364
+ loss=loss,
1365
+ logits=logits,
1366
+ past_key_values=outputs.past_key_values,
1367
+ hidden_states=outputs.hidden_states,
1368
+ attentions=outputs.attentions,
1369
+ image_hidden_states=image_features if pixel_values is not None else None,
1370
+ )
1371
+
1372
+ def prepare_inputs_for_generation(
1373
+ self,
1374
+ input_ids,
1375
+ past_key_values=None,
1376
+ inputs_embeds=None,
1377
+ pixel_values=None,
1378
+ attention_mask=None,
1379
+ cache_position=None,
1380
+ logits_to_keep=None,
1381
+ **kwargs,
1382
+ ):
1383
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
1384
+
1385
+ model_inputs = self.language_model.prepare_inputs_for_generation(
1386
+ input_ids,
1387
+ past_key_values=past_key_values,
1388
+ inputs_embeds=inputs_embeds,
1389
+ attention_mask=attention_mask,
1390
+ cache_position=cache_position,
1391
+ logits_to_keep=logits_to_keep,
1392
+ **kwargs,
1393
+ )
1394
+
1395
+ if cache_position[0] == 0:
1396
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
1397
+ # Otherwise we need pixel values to be passed to model
1398
+ model_inputs["pixel_values"] = pixel_values
1399
+
1400
+ return model_inputs
1401
+
1402
+
1403
+ __all__ = [
1404
+ "Llama4PreTrainedModel",
1405
+ "Llama4TextModel",
1406
+ "Llama4VisionModel",
1407
+ "Llama4ForCausalLM",
1408
+ "Llama4ForConditionalGeneration",
1409
+ ]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llama4/processing_llama4.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 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
+
16
+
17
+ from typing import Optional, Union
18
+
19
+ from transformers.processing_utils import ImagesKwargs, ProcessingKwargs, ProcessorMixin, Unpack
20
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
21
+
22
+ from ...image_processing_utils import BatchFeature
23
+ from ...image_utils import ImageInput, make_flat_list_of_images
24
+
25
+
26
+ class Llama4ImagesKwargs(ImagesKwargs, total=False):
27
+ max_patches: Optional[int]
28
+ resize_to_max_canvas: Optional[bool]
29
+
30
+
31
+ class Llama4ProcessorKwargs(ProcessingKwargs, total=False):
32
+ images_kwargs: Llama4ImagesKwargs
33
+ _defaults = {
34
+ "text_kwargs": {
35
+ "padding_side": "left",
36
+ },
37
+ }
38
+
39
+
40
+ chat_template = "{{- bos_token }}\n{%- if custom_tools is defined %}\n {%- set tools = custom_tools %}\n{%- endif %}\n{%- if not tools_in_user_message is defined %}\n {%- set tools_in_user_message = true %}\n{%- endif %}\n{%- if not date_string is defined %}\n {%- if strftime_now is defined %}\n {%- set date_string = strftime_now(\"%d %b %Y\") %}\n {%- else %}\n {%- set date_string = \"26 Jul 2024\" %}\n {%- endif %}\n{%- endif %}\n{%- if not tools is defined %}\n {%- set tools = none %}\n{%- endif %}\n\n{#- This block extracts the system message, so we can slot it into the right place. #}\n{%- if messages[0]['role'] == 'system' %} \n {%- if messages[0]['content'] is string %}\n {%- set system_message = messages[0]['content']|trim %}\n {%- else %}\n {#- FIXME: The processor requires an array, always. #}\n {%- set system_message = messages[0]['content'][0]['text']|trim %}\n {%- endif %}\n {%- set messages = messages[1:] %}\n {%- set user_supplied_system_message = true %}\n{%- else %}\n {%- set system_message = \"\" %}\n {%- set user_supplied_system_message = false %}\n{%- endif %}\n\n{#- System message if the user supplied one #}\n{%- if user_supplied_system_message %}\n {{- \"<|header_start|>system<|header_end|>\n\n\" }}\n {%- if tools is not none %}\n {{- \"Environment: ipython\n\" }}\n {%- endif %}\n {%- if tools is not none and not tools_in_user_message %}\n {{- \"You have access to the following functions. To call a function, please respond with JSON for a function call.\" }}\n {{- 'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.' }}\n {{- \"Do not use variables.\n\n\" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- \"\n\n\" }}\n {%- endfor %}\n {%- endif %}\n {{- system_message }}\n {{- \"<|eot|>\" }}\n{%- endif %}\n\n{#- Custom tools are passed in a user message with some extra guidance #}\n{%- if tools_in_user_message and not tools is none %}\n {#- Extract the first user message so we can plug it in here #}\n {%- if messages | length != 0 %}\n {%- set first_user_message = messages[0]['content']|trim %}\n {%- set messages = messages[1:] %}\n {%- else %}\n {{- raise_exception(\"Cannot put tools in the first user message when there's no first user message!\") }}\n{%- endif %}\n {{- '<|header_start|>user<|header_end|>\n\n' -}}\n {{- \"Given the following functions, please respond with a JSON for a function call \" }}\n {{- \"with its proper arguments that best answers the given prompt.\n\n\" }}\n {{- 'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.' }}\n {{- \"Do not use variables.\n\n\" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- \"\n\n\" }}\n {%- endfor %}\n {{- first_user_message + \"<|eot|>\"}}\n{%- endif %}\n\n{%- for message in messages %}\n {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %}\n {{- '<|header_start|>' + message['role'] + '<|header_end|>\n\n' }}\n {%- if message['content'] is string %}\n {{- message['content'] }}\n {%- else %}\n {%- for content in message['content'] %}\n {%- if content['type'] == 'image' %}\n {{- '<|image|>' }}\n {%- elif content['type'] == 'text' %}\n {{- content['text'] }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- \"<|eot|>\" }}\n {%- elif 'tool_calls' in message and message.tool_calls|length > 0 %}\n {{- '<|header_start|>assistant<|header_end|>\n\n' -}}\n {{- '<|python_start|>' }}\n {%- if message['content'] is string %}\n {{- message['content'] }}\n {%- else %}\n {%- for content in message['content'] %}\n {%- if content['type'] == 'image' %}\n {{- '<|image|>' }}\n {%- elif content['type'] == 'text' %}\n {{- content['text'] }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '<|python_end|>' }}\n {%- for tool_call in message.tool_calls %}\n {{- '{\"name\": \"' + tool_call.function.name + '\", ' }}\n {{- '\"parameters\": ' }}\n {{- tool_call.function.arguments | tojson }}\n {{- \"}\" }}\n {%- endfor %}\n {{- \"<|eot|>\" }}\n {%- elif message.role == \"tool\" or message.role == \"ipython\" %}\n {{- \"<|header_start|>ipython<|header_end|>\n\n\" }}\n {%- if message.content is mapping or message.content is iterable %}\n {{- message.content | tojson }}\n {%- else %}\n {{- message.content }}\n {%- endif %}\n {{- \"<|eot|>\" }}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|header_start|>assistant<|header_end|>\n\n' }}\n{%- endif %}\n"
41
+
42
+
43
+ class Llama4Processor(ProcessorMixin):
44
+ r"""
45
+ Constructs a Llama4 processor which wraps a [`AutoImageProcessor`] and
46
+ [`PretrainedTokenizerFast`] tokenizer into a single processor that inherits both the image processor and
47
+ tokenizer functionalities. See the [`~Llama4Processor.__call__`] and [`~Llama4Processor.decode`] for more information.
48
+ Args:
49
+ image_processor ([`AutoImageProcessor`], *optional*):
50
+ The image processor is a required input.
51
+ tokenizer ([`PreTrainedTokenizer`, `PreTrainedTokenizerFast`], *optional*):
52
+ The tokenizer is a required input.
53
+ patch_size (`int`, *optional*, defaults to 28):
54
+ The size of image patches for tokenization.
55
+ img_size (`int`, *optional*, defaults to 364):
56
+ The size of the image to be tokenized. This should correspond to the size given to the image processor.
57
+ image_token (`str`, *optional*, defaults to `"<|image|>"`):
58
+ The token to be used to represent an image in the text.
59
+ downsample_factor (`int`, *optional*, defaults to 1):
60
+ The factor by which to scale the patch size.
61
+ start_of_img_token (`str`, *optional*, defaults to `"<|START_OF_IMG|>"`):
62
+ The token to be used to represent the start of an image in the text.
63
+ end_of_img_token (`str`, *optional*, defaults to `"<|END_OF_IMG|>"`):
64
+ The token to be used to represent the end of an image in the text.
65
+ img_patch_token (`str`, *optional*, defaults to `"<|IMG_PATCH|>"`):
66
+ The token to be used to represent an image patch in the text.
67
+ img_line_break_token (`str`, *optional*, defaults to `"<|IMG_LINE_BREAK|>"`):
68
+ The token to be used to represent a line break in the text.
69
+ tile_token (`str`, *optional*, defaults to `"TILE"`):
70
+ The token to be used to represent an image patch in the text.
71
+ tile_global_token (`str`, *optional*, defaults to `"TILE_GLOBAL"`):
72
+ The token to be used to represent the cover image in the text.
73
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
74
+ in a chat into a tokenizable string.
75
+ """
76
+
77
+ attributes = ["image_processor", "tokenizer"]
78
+ image_processor_class = "AutoImageProcessor"
79
+ tokenizer_class = "AutoTokenizer"
80
+
81
+ def __init__(
82
+ self,
83
+ image_processor=None,
84
+ tokenizer=None,
85
+ patch_size: int = 14,
86
+ pixel_shuffle_ratio: float = 0.5,
87
+ fake_image_token="<|image|>",
88
+ image_token="<|image|>",
89
+ start_of_image_token="<|image_start|>",
90
+ end_of_image_token="<|image_end|>",
91
+ patch_token="<|patch|>",
92
+ tile_x_separator_token="<|tile_x_separator|>",
93
+ tile_y_separator_token="<|tile_y_separator|>",
94
+ chat_template=chat_template,
95
+ **kwargs,
96
+ ):
97
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
98
+
99
+ self.downsample_ratio = int(round(1.0 / (pixel_shuffle_ratio**2)))
100
+ self.patch_size = patch_size
101
+
102
+ self.fake_image_token = fake_image_token
103
+ self.image_token = image_token
104
+ self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
105
+ self.start_of_img_token = start_of_image_token
106
+ self.end_of_img_token = end_of_image_token
107
+ self.img_patch_token = patch_token
108
+ self.tile_token = tile_x_separator_token
109
+ self.tile_global_token = tile_y_separator_token
110
+
111
+ def _prompt_split_image(self, aspect_ratio, num_patches_per_chunk):
112
+ """
113
+ Create a structured string representation of image tokens
114
+
115
+ Args:
116
+ num_patches: Number of patches in the image
117
+
118
+ Returns:
119
+ String with appropriate image tokens
120
+ """
121
+ img_string = "<|image_start|>"
122
+ ratio_h, ratio_w = aspect_ratio
123
+ if ratio_h * ratio_w > 1:
124
+ for yy in range(ratio_h):
125
+ for xx in range(ratio_w):
126
+ img_string += "<|patch|>" * num_patches_per_chunk
127
+ if xx < ratio_w - 1:
128
+ img_string += "<|tile_x_separator|>"
129
+
130
+ img_string += "<|tile_y_separator|>"
131
+
132
+ img_string += "<|image|>"
133
+ img_string += "<|patch|>" * num_patches_per_chunk
134
+ img_string += "<|image_end|>"
135
+
136
+ return img_string
137
+
138
+ def __call__(
139
+ self,
140
+ images: Optional[ImageInput] = None,
141
+ text: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]] = None,
142
+ audio=None,
143
+ videos=None,
144
+ **kwargs: Unpack[Llama4ProcessorKwargs],
145
+ ) -> BatchFeature:
146
+ """
147
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
148
+ and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] to encode the text.
149
+ To prepare the vision inputs, this method forwards the `images` and `kwargs` arguments to
150
+ Llama4ImageProcessor's [`~Llama4ImageProcessor.__call__`] if `images` is not `None`.
151
+
152
+ Args:
153
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
154
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
155
+ tensor. Both channels-first and channels-last formats are supported.
156
+ text (`str`, `list[str]`, `list[list[str]]`):
157
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
158
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
159
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
160
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
161
+ If set, will return tensors of a particular framework. Acceptable values are:
162
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
163
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
164
+ - `'np'`: Return NumPy `np.ndarray` objects.
165
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
166
+
167
+ Returns:
168
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
169
+
170
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
171
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
172
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
173
+ `None`).
174
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
175
+ """
176
+ if text is None:
177
+ raise ValueError("You have to specify text.")
178
+
179
+ output_kwargs = self._merge_kwargs(
180
+ Llama4ProcessorKwargs,
181
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
182
+ **kwargs,
183
+ )
184
+
185
+ if not isinstance(text, (list, tuple)):
186
+ text = [text]
187
+
188
+ # Process images
189
+ image_inputs = {}
190
+ if images is not None:
191
+ images = make_flat_list_of_images(images)
192
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
193
+ image_height, image_width = image_inputs["pixel_values"][0].shape[-2:]
194
+ num_patches_per_chunk = int(
195
+ (image_height // self.patch_size) * (image_width // self.patch_size) // self.downsample_ratio
196
+ )
197
+ aspect_ratios = image_inputs.pop("aspect_ratios")
198
+
199
+ total_placeholders = sum(prompt.count(self.fake_image_token) for prompt in text)
200
+ if total_placeholders != len(images):
201
+ raise ValueError(
202
+ f"Found {total_placeholders} placeholders across the batch, "
203
+ f"but have {len(images)} flattened images."
204
+ )
205
+
206
+ image_index = 0
207
+ processed_text = []
208
+ for prompt in text:
209
+ placeholder_count = prompt.count(self.fake_image_token)
210
+ if placeholder_count == 0:
211
+ # do nothing if there is no image
212
+ processed_text.append(prompt)
213
+ continue
214
+ prompt_splits = prompt.split(self.fake_image_token)
215
+ new_prompt = []
216
+ for local_image_index, split_part in enumerate(prompt_splits):
217
+ new_prompt.append(split_part)
218
+ if local_image_index < placeholder_count:
219
+ tokens_for_this_image = self._prompt_split_image(
220
+ aspect_ratios[image_index], num_patches_per_chunk
221
+ )
222
+ image_index += 1
223
+ new_prompt.append(tokens_for_this_image)
224
+ processed_text.append("".join(new_prompt))
225
+
226
+ if image_index != len(images):
227
+ raise ValueError("Number of image placeholders in the prompt does not match the number of images.")
228
+
229
+ text = processed_text
230
+
231
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
232
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
233
+ self._check_special_mm_tokens(text, text_inputs, modalities=["image"])
234
+
235
+ return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
236
+
237
+ def batch_decode(self, *args, **kwargs):
238
+ """
239
+ This method forwards all its arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
240
+ refer to the docstring of this method for more information.
241
+ """
242
+ return self.tokenizer.batch_decode(*args, **kwargs)
243
+
244
+ def decode(self, *args, **kwargs):
245
+ """
246
+ This method forwards all its arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
247
+ the docstring of this method for more information.
248
+ """
249
+ return self.tokenizer.decode(*args, **kwargs)
250
+
251
+ @property
252
+ def model_input_names(self):
253
+ tokenizer_input_names = self.tokenizer.model_input_names
254
+ image_processor_input_names = self.image_processor.model_input_names
255
+ return list(tokenizer_input_names) + list(image_processor_input_names)
256
+
257
+
258
+ __all__ = ["Llama4Processor"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_llava import *
22
+ from .image_processing_llava_fast import *
23
+ from .modeling_llava import *
24
+ from .processing_llava import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava/configuration_llava.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft Research & University of Wisconsin-Madison and the HuggingFace Inc. team. All rights reserved.
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
+ """Llava model configuration"""
15
+
16
+ from ...configuration_utils import PretrainedConfig
17
+ from ...utils import logging
18
+ from ..auto import CONFIG_MAPPING, AutoConfig
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class LlavaConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`LlavaForConditionalGeneration`]. It is used to instantiate an
27
+ Llava 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 Llava-9B.
29
+
30
+ e.g. [llava-hf/llava-9b](https://huggingface.co/llava-hf/llava-9b)
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+ Args:
36
+ vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `CLIPVisionConfig`):
37
+ The config object or dictionary of the vision backbone.
38
+ text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `LlamaConfig`):
39
+ The config object or dictionary of the text backbone.
40
+ image_token_index (`int`, *optional*, defaults to 32000):
41
+ The image token index to encode the image prompt.
42
+ projector_hidden_act (`str`, *optional*, defaults to `"gelu"`):
43
+ The activation function used by the multimodal projector.
44
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
45
+ The feature selection strategy used to select the vision feature from the vision backbone.
46
+ Can be one of `"default"` or `"full"`.
47
+ vision_feature_layer (`Union[int, list[int]]`, *optional*, defaults to -2):
48
+ The index of the layer to select the vision feature. If multiple indices are provided,
49
+ the vision feature of the corresponding indices will be concatenated to form the
50
+ vision features.
51
+ image_seq_length (`int`, *optional*, defaults to 576):
52
+ Sequence length of one image embedding.
53
+ multimodal_projector_bias (`bool`, *optional*, defaults to `True`):
54
+ Whether to use bias in the multimodal projector.
55
+
56
+ Example:
57
+
58
+ ```python
59
+ >>> from transformers import LlavaForConditionalGeneration, LlavaConfig, CLIPVisionConfig, LlamaConfig
60
+
61
+ >>> # Initializing a CLIP-vision config
62
+ >>> vision_config = CLIPVisionConfig()
63
+
64
+ >>> # Initializing a Llama config
65
+ >>> text_config = LlamaConfig()
66
+
67
+ >>> # Initializing a Llava llava-1.5-7b style configuration
68
+ >>> configuration = LlavaConfig(vision_config, text_config)
69
+
70
+ >>> # Initializing a model from the llava-1.5-7b style configuration
71
+ >>> model = LlavaForConditionalGeneration(configuration)
72
+
73
+ >>> # Accessing the model configuration
74
+ >>> configuration = model.config
75
+ ```"""
76
+
77
+ model_type = "llava"
78
+ attribute_map = {
79
+ "image_token_id": "image_token_index",
80
+ }
81
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
82
+
83
+ def __init__(
84
+ self,
85
+ vision_config=None,
86
+ text_config=None,
87
+ image_token_index=32000,
88
+ projector_hidden_act="gelu",
89
+ vision_feature_select_strategy="default",
90
+ vision_feature_layer=-2,
91
+ image_seq_length=576,
92
+ multimodal_projector_bias=True,
93
+ **kwargs,
94
+ ):
95
+ self.image_token_index = image_token_index
96
+ self.projector_hidden_act = projector_hidden_act
97
+ self.image_seq_length = image_seq_length
98
+
99
+ if vision_feature_select_strategy not in ["default", "full"]:
100
+ raise ValueError(
101
+ "vision_feature_select_strategy should be one of 'default', 'full'."
102
+ f"Got: {vision_feature_select_strategy}"
103
+ )
104
+
105
+ self.vision_feature_select_strategy = vision_feature_select_strategy
106
+ self.vision_feature_layer = vision_feature_layer
107
+
108
+ if isinstance(vision_config, dict):
109
+ vision_config["model_type"] = vision_config.get("model_type", "clip_vision_model")
110
+ vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
111
+ elif vision_config is None:
112
+ vision_config = CONFIG_MAPPING["clip_vision_model"](
113
+ intermediate_size=4096,
114
+ hidden_size=1024,
115
+ patch_size=14,
116
+ image_size=336,
117
+ num_hidden_layers=24,
118
+ num_attention_heads=16,
119
+ vocab_size=32000,
120
+ projection_dim=768,
121
+ )
122
+
123
+ self.vision_config = vision_config
124
+
125
+ if isinstance(text_config, dict):
126
+ text_config["model_type"] = text_config.get("model_type", "llama")
127
+ text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
128
+ elif text_config is None:
129
+ text_config = CONFIG_MAPPING["llama"]()
130
+
131
+ self.text_config = text_config
132
+ self.multimodal_projector_bias = multimodal_projector_bias
133
+
134
+ super().__init__(**kwargs)
135
+
136
+
137
+ __all__ = ["LlavaConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava/convert_llava_weights_to_hf.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+ import argparse
15
+ import glob
16
+
17
+ import torch
18
+ from huggingface_hub import file_exists, hf_hub_download, snapshot_download
19
+ from safetensors import safe_open
20
+
21
+ from transformers import (
22
+ AddedToken,
23
+ AutoConfig,
24
+ AutoImageProcessor,
25
+ AutoTokenizer,
26
+ LlavaConfig,
27
+ LlavaForConditionalGeneration,
28
+ LlavaProcessor,
29
+ SiglipVisionConfig,
30
+ )
31
+
32
+
33
+ EPILOG_TXT = """Example:
34
+ python transformers/src/transformers/models/llava/convert_llava_weights_to_hf.py --text_model_id lmsys/vicuna-7b-v1.5 --vision_model_id openai/clip-vit-large-patch14-336 --output_hub_path org/llava-v1.5-7b-conv --old_state_dict_id liuhaotian/llava-v1.5-7b
35
+
36
+ Example for creating the old state dict file with Python:
37
+
38
+ import torch
39
+ from llava.model.language_model.llava_llama import LlavaLlamaForCausalLM
40
+
41
+ # load model
42
+ kwargs = {"device_map": "auto", "torch_dtype": torch.float16}
43
+ model = LlavaLlamaForCausalLM.from_pretrained("liuhaotian/llava-v1.5-7b", **kwargs)
44
+
45
+ # load vision tower
46
+ model.get_vision_tower().load_model()
47
+
48
+ # Save state dict
49
+ torch.save(model.state_dict(), "tmp/hf_models/llava-v1.5-7b/model_state_dict.bin")
50
+ """
51
+
52
+ KEYS_TO_MODIFY_MAPPING = {
53
+ "model.vision_tower.": "",
54
+ ".vision_resampler": "", # all lmms-lab models do avg pooling, so no vision_resampler
55
+ "model.mm_projector": "multi_modal_projector",
56
+ "model": "model.model",
57
+ "vision_model.model": "vision_model",
58
+ "lm_head": "language_model.lm_head",
59
+ "model.model": "language_model.model",
60
+ "multi_modal_projector.0": "multi_modal_projector.linear_1",
61
+ "multi_modal_projector.2": "multi_modal_projector.linear_2",
62
+ }
63
+
64
+
65
+ def load_original_state_dict(model_id):
66
+ directory_path = snapshot_download(repo_id=model_id, allow_patterns=["*.safetensors"])
67
+
68
+ original_state_dict = {}
69
+ for path in glob.glob(f"{directory_path}/*"):
70
+ if path.endswith(".safetensors"):
71
+ with safe_open(path, framework="pt", device="cpu") as f:
72
+ for key in f.keys():
73
+ original_state_dict[key] = f.get_tensor(key)
74
+
75
+ # tied weights so lm.head is not saved. Let's clone to load state dict
76
+ if "lm_head.weight" not in original_state_dict:
77
+ original_state_dict["lm_head.weight"] = original_state_dict["model.embed_tokens.weight"].clone()
78
+
79
+ if "model.image_newline" in original_state_dict:
80
+ # not used in the original implementation because "merge_type=flat"
81
+ del original_state_dict["model.image_newline"]
82
+ return original_state_dict
83
+
84
+
85
+ # used only for llava-interlave
86
+ # for ex: Qwen/Qwen1.5-0.5B-Chat google/siglip-so400m-patch14-384 lmms-lab/llava-next-interleave-qwen-0.5b
87
+ def convert_state_dict_to_hf(state_dict):
88
+ new_state_dict = {}
89
+ for key, value in state_dict.items():
90
+ if key.endswith(".inv_freq"):
91
+ continue
92
+ for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
93
+ if key_to_modify in key:
94
+ key = key.replace(key_to_modify, new_key)
95
+
96
+ new_state_dict[key] = value
97
+ return new_state_dict
98
+
99
+
100
+ def convert_llava_llama_to_hf(text_model_id, vision_model_id, output_hub_path, old_state_dict_id):
101
+ torch.set_default_dtype(torch.float16)
102
+ text_config = AutoConfig.from_pretrained(text_model_id)
103
+
104
+ tokenizer = AutoTokenizer.from_pretrained(text_model_id)
105
+ tokenizer.add_tokens(AddedToken("<image>", special=True, normalized=False), special_tokens=True)
106
+ if "Qwen" not in text_model_id: # qwen already has a pad token
107
+ tokenizer.add_special_tokens({"pad_token": "<pad>"})
108
+
109
+ image_processor = AutoImageProcessor.from_pretrained(vision_model_id)
110
+ processor = LlavaProcessor(tokenizer=tokenizer, image_processor=image_processor)
111
+
112
+ if "siglip" in vision_model_id:
113
+ vision_config = SiglipVisionConfig(
114
+ hidden_size=1152,
115
+ image_size=384,
116
+ intermediate_size=4304,
117
+ num_attention_heads=16,
118
+ num_hidden_layers=26,
119
+ patch_size=14,
120
+ vision_use_head=False,
121
+ ).to_dict()
122
+ else:
123
+ vision_config = None
124
+
125
+ config = LlavaConfig(
126
+ text_config=text_config,
127
+ vision_config=vision_config,
128
+ )
129
+
130
+ # llms-lab interleave models do not use any selection strategy except for last hidden state
131
+ if "Qwen" in text_model_id:
132
+ config.image_token_id = 151646
133
+ if "siglip" in vision_model_id:
134
+ config.vision_feature_select_strategy = "full"
135
+ config.vision_feature_layer = -1
136
+ else:
137
+ config.pad_token_id = 32001
138
+ config.image_token_id = 32000
139
+
140
+ with torch.device("meta"):
141
+ model = LlavaForConditionalGeneration(config)
142
+
143
+ # Some llava variants like microsoft/llava-med-v1.5-mistral-7b use safetensors to store weights
144
+ if file_exists(old_state_dict_id, "model_state_dict.bin"):
145
+ state_dict_path = hf_hub_download(old_state_dict_id, "model_state_dict.bin")
146
+ state_dict = torch.load(state_dict_path, map_location="cpu", weights_only=True)
147
+ else:
148
+ state_dict = load_original_state_dict(old_state_dict_id)
149
+
150
+ state_dict = convert_state_dict_to_hf(state_dict)
151
+ model.load_state_dict(state_dict, strict=True, assign=True)
152
+
153
+ pre_expansion_embeddings = model.language_model.model.embed_tokens.weight.data
154
+ mu = torch.mean(pre_expansion_embeddings, dim=0).float()
155
+ n = pre_expansion_embeddings.size()[0]
156
+ sigma = ((pre_expansion_embeddings - mu).T @ (pre_expansion_embeddings - mu)) / n
157
+ dist = torch.distributions.multivariate_normal.MultivariateNormal(mu, covariance_matrix=1e-5 * sigma)
158
+
159
+ # We add an image token so we resize the model and pad to 64 for performance reasons
160
+ pad_shape = 64
161
+ vocab_size = config.text_config.vocab_size
162
+ model.resize_token_embeddings(config.text_config.vocab_size + 2, pad_shape)
163
+ model.language_model.model.embed_tokens.weight.data[vocab_size:] = torch.stack(
164
+ tuple(dist.sample() for _ in range(model.language_model.model.embed_tokens.weight.data[vocab_size:].shape[0])),
165
+ dim=0,
166
+ )
167
+ model.language_model.lm_head.weight.data[vocab_size:] = torch.stack(
168
+ tuple(dist.sample() for _ in range(model.language_model.lm_head.weight.data[vocab_size:].shape[0])),
169
+ dim=0,
170
+ )
171
+
172
+ model.push_to_hub(output_hub_path)
173
+ processor.push_to_hub(output_hub_path)
174
+
175
+
176
+ def main():
177
+ parser = argparse.ArgumentParser(
178
+ epilog=EPILOG_TXT,
179
+ formatter_class=argparse.RawDescriptionHelpFormatter,
180
+ )
181
+ parser.add_argument(
182
+ "--text_model_id",
183
+ help="Hub location of the text model",
184
+ )
185
+ parser.add_argument(
186
+ "--vision_model_id",
187
+ help="Hub location of the vision model",
188
+ )
189
+ parser.add_argument(
190
+ "--output_hub_path",
191
+ help="Location on the hub of the converted model",
192
+ )
193
+ parser.add_argument(
194
+ "--old_state_dict_id",
195
+ help="Location on the hub of the raw state dict of the original model. The filename needs to be `model_state_dict.bin`",
196
+ )
197
+ args = parser.parse_args()
198
+ convert_llava_llama_to_hf(args.text_model_id, args.vision_model_id, args.output_hub_path, args.old_state_dict_id)
199
+
200
+
201
+ if __name__ == "__main__":
202
+ main()
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava/image_processing_llava.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Image processor class for LLaVa."""
16
+
17
+ from typing import Optional, Union
18
+
19
+ import numpy as np
20
+
21
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
22
+ from ...image_transforms import (
23
+ convert_to_rgb,
24
+ get_resize_output_image_size,
25
+ resize,
26
+ to_channel_dimension_format,
27
+ )
28
+ from ...image_utils import (
29
+ OPENAI_CLIP_MEAN,
30
+ OPENAI_CLIP_STD,
31
+ ChannelDimension,
32
+ ImageInput,
33
+ PILImageResampling,
34
+ get_image_size,
35
+ infer_channel_dimension_format,
36
+ is_scaled_image,
37
+ make_list_of_images,
38
+ to_numpy_array,
39
+ valid_images,
40
+ validate_kwargs,
41
+ validate_preprocess_arguments,
42
+ )
43
+ from ...utils import TensorType, is_vision_available, logging
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ if is_vision_available():
50
+ import PIL
51
+
52
+
53
+ class LlavaImageProcessor(BaseImageProcessor):
54
+ r"""
55
+ Constructs a LLaVa image processor.
56
+
57
+ Args:
58
+ do_pad (`bool`, *optional*, defaults to `False`):
59
+ Whether to pad the image to a square based on the longest edge.
60
+ The padding value is determined by the `image_mean` parameter.
61
+ Can be overridden by `do_pad` in the `preprocess` method.
62
+ do_resize (`bool`, *optional*, defaults to `True`):
63
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
64
+ `do_resize` in the `preprocess` method.
65
+ size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
66
+ Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
67
+ the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
68
+ method.
69
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
70
+ Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
71
+ do_center_crop (`bool`, *optional*, defaults to `True`):
72
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
73
+ `preprocess` method.
74
+ crop_size (`dict[str, int]` *optional*, defaults to 224):
75
+ Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
76
+ method.
77
+ do_rescale (`bool`, *optional*, defaults to `True`):
78
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
79
+ the `preprocess` method.
80
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
81
+ Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
82
+ method.
83
+ do_normalize (`bool`, *optional*, defaults to `True`):
84
+ Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
85
+ image_mean (`float` or `list[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
86
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
87
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
88
+ image_std (`float` or `list[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
89
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
90
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
91
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
92
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
93
+ Whether to convert the image to RGB.
94
+ """
95
+
96
+ model_input_names = ["pixel_values"]
97
+
98
+ def __init__(
99
+ self,
100
+ do_pad: bool = False,
101
+ do_resize: bool = True,
102
+ size: Optional[dict[str, int]] = None,
103
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
104
+ do_center_crop: bool = True,
105
+ crop_size: Optional[dict[str, int]] = None,
106
+ do_rescale: bool = True,
107
+ rescale_factor: Union[int, float] = 1 / 255,
108
+ do_normalize: bool = True,
109
+ image_mean: Optional[Union[float, list[float]]] = None,
110
+ image_std: Optional[Union[float, list[float]]] = None,
111
+ do_convert_rgb: bool = True,
112
+ **kwargs,
113
+ ) -> None:
114
+ super().__init__(**kwargs)
115
+ size = size if size is not None else {"shortest_edge": 224}
116
+ size = get_size_dict(size, default_to_square=False)
117
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
118
+ crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
119
+
120
+ self.do_pad = do_pad
121
+ self.do_resize = do_resize
122
+ self.size = size
123
+ self.resample = resample
124
+ self.do_center_crop = do_center_crop
125
+ self.crop_size = crop_size
126
+ self.do_rescale = do_rescale
127
+ self.rescale_factor = rescale_factor
128
+ self.do_normalize = do_normalize
129
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
130
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
131
+ self.do_convert_rgb = do_convert_rgb
132
+ self._valid_processor_keys = [
133
+ "images",
134
+ "do_pad",
135
+ "do_resize",
136
+ "size",
137
+ "resample",
138
+ "do_center_crop",
139
+ "crop_size",
140
+ "do_rescale",
141
+ "rescale_factor",
142
+ "do_normalize",
143
+ "image_mean",
144
+ "image_std",
145
+ "do_convert_rgb",
146
+ "return_tensors",
147
+ "data_format",
148
+ "input_data_format",
149
+ ]
150
+
151
+ def pad_to_square(
152
+ self,
153
+ image: np.ndarray,
154
+ background_color: Union[int, tuple[int, int, int]] = 0,
155
+ data_format: Optional[Union[str, ChannelDimension]] = None,
156
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
157
+ ) -> np.array:
158
+ """
159
+ Pads an image to a square based on the longest edge.
160
+
161
+ Args:
162
+ image (`np.ndarray`):
163
+ The image to pad.
164
+ background_color (`int` or `tuple[int, int, int]`, *optional*, defaults to 0):
165
+ The color to use for the padding. Can be an integer for single channel or a
166
+ tuple of integers representing for multi-channel images. If passed as integer
167
+ in mutli-channel mode, it will default to `0` in subsequent channels.
168
+ data_format (`str` or `ChannelDimension`, *optional*):
169
+ The channel dimension format for the output image. Can be one of:
170
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
171
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
172
+ If unset, will use same as the input image.
173
+ input_data_format (`str` or `ChannelDimension`, *optional*):
174
+ The channel dimension format for the input image. Can be one of:
175
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
176
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
177
+ If unset, will use the inferred format of the input image.
178
+
179
+ Returns:
180
+ `np.ndarray`: The padded image.
181
+ """
182
+ height, width = get_image_size(image, input_data_format)
183
+ num_channels = image.shape[0] if input_data_format == ChannelDimension.FIRST else image.shape[-1]
184
+
185
+ if height == width:
186
+ image = (
187
+ to_channel_dimension_format(image, data_format, input_data_format)
188
+ if data_format is not None
189
+ else image
190
+ )
191
+ return image
192
+
193
+ max_dim = max(height, width)
194
+
195
+ # Ensure background_color is the correct shape
196
+ if isinstance(background_color, int):
197
+ background_color = [background_color]
198
+ elif len(background_color) != num_channels:
199
+ raise ValueError(
200
+ f"background_color must have no more than {num_channels} elements to match the number of channels"
201
+ )
202
+
203
+ if input_data_format == ChannelDimension.FIRST:
204
+ result = np.zeros((num_channels, max_dim, max_dim), dtype=image.dtype)
205
+ for i, color in enumerate(background_color):
206
+ result[i, :, :] = color
207
+ if width > height:
208
+ start = (max_dim - height) // 2
209
+ result[:, start : start + height, :] = image
210
+ else:
211
+ start = (max_dim - width) // 2
212
+ result[:, :, start : start + width] = image
213
+ else:
214
+ result = np.zeros((max_dim, max_dim, num_channels), dtype=image.dtype)
215
+ for i, color in enumerate(background_color):
216
+ result[:, :, i] = color
217
+ if width > height:
218
+ start = (max_dim - height) // 2
219
+ result[start : start + height, :, :] = image
220
+ else:
221
+ start = (max_dim - width) // 2
222
+ result[:, start : start + width, :] = image
223
+
224
+ image = (
225
+ to_channel_dimension_format(result, data_format, input_data_format) if data_format is not None else result
226
+ )
227
+ return image
228
+
229
+ # Copied from transformers.models.clip.image_processing_clip.CLIPImageProcessor.resize
230
+ def resize(
231
+ self,
232
+ image: np.ndarray,
233
+ size: dict[str, int],
234
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
235
+ data_format: Optional[Union[str, ChannelDimension]] = None,
236
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
237
+ **kwargs,
238
+ ) -> np.ndarray:
239
+ """
240
+ Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
241
+ resized to keep the input aspect ratio.
242
+
243
+ Args:
244
+ image (`np.ndarray`):
245
+ Image to resize.
246
+ size (`dict[str, int]`):
247
+ Size of the output image.
248
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
249
+ Resampling filter to use when resiizing the image.
250
+ data_format (`str` or `ChannelDimension`, *optional*):
251
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
252
+ input_data_format (`ChannelDimension` or `str`, *optional*):
253
+ The channel dimension format of the input image. If not provided, it will be inferred.
254
+ """
255
+ default_to_square = True
256
+ if "shortest_edge" in size:
257
+ size = size["shortest_edge"]
258
+ default_to_square = False
259
+ elif "height" in size and "width" in size:
260
+ size = (size["height"], size["width"])
261
+ else:
262
+ raise ValueError("Size must contain either 'shortest_edge' or 'height' and 'width'.")
263
+
264
+ output_size = get_resize_output_image_size(
265
+ image,
266
+ size=size,
267
+ default_to_square=default_to_square,
268
+ input_data_format=input_data_format,
269
+ )
270
+ return resize(
271
+ image,
272
+ size=output_size,
273
+ resample=resample,
274
+ data_format=data_format,
275
+ input_data_format=input_data_format,
276
+ **kwargs,
277
+ )
278
+
279
+ def preprocess(
280
+ self,
281
+ images: ImageInput,
282
+ do_pad: Optional[bool] = None,
283
+ do_resize: Optional[bool] = None,
284
+ size: Optional[dict[str, int]] = None,
285
+ resample: Optional[PILImageResampling] = None,
286
+ do_center_crop: Optional[bool] = None,
287
+ crop_size: Optional[int] = None,
288
+ do_rescale: Optional[bool] = None,
289
+ rescale_factor: Optional[float] = None,
290
+ do_normalize: Optional[bool] = None,
291
+ image_mean: Optional[Union[float, list[float]]] = None,
292
+ image_std: Optional[Union[float, list[float]]] = None,
293
+ do_convert_rgb: Optional[bool] = None,
294
+ return_tensors: Optional[Union[str, TensorType]] = None,
295
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
296
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
297
+ **kwargs,
298
+ ) -> PIL.Image.Image:
299
+ """
300
+ Preprocess an image or batch of images.
301
+
302
+ Args:
303
+ images (`ImageInput`):
304
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
305
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
306
+ do_pad (`bool`, *optional*, defaults to `self.do_pad`):
307
+ Whether to pad the image to a square based on the longest edge.
308
+ The padding value is determined by the `image_mean` parameter.
309
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
310
+ Whether to resize the image.
311
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
312
+ Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
313
+ the longest edge resized to keep the input aspect ratio.
314
+ resample (`int`, *optional*, defaults to `self.resample`):
315
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
316
+ has an effect if `do_resize` is set to `True`.
317
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
318
+ Whether to center crop the image.
319
+ crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`):
320
+ Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
321
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
322
+ Whether to rescale the image.
323
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
324
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
325
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
326
+ Whether to normalize the image.
327
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
328
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
329
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
330
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
331
+ `True`.
332
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
333
+ Whether to convert the image to RGB.
334
+ return_tensors (`str` or `TensorType`, *optional*):
335
+ The type of tensors to return. Can be one of:
336
+ - Unset: Return a list of `np.ndarray`.
337
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
338
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
339
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
340
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
341
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
342
+ The channel dimension format for the output image. Can be one of:
343
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
344
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
345
+ - Unset: Use the channel dimension format of the input image.
346
+ input_data_format (`ChannelDimension` or `str`, *optional*):
347
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
348
+ from the input image. Can be one of:
349
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
350
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
351
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
352
+ """
353
+ do_pad = do_pad if do_pad is not None else self.do_pad
354
+ do_resize = do_resize if do_resize is not None else self.do_resize
355
+ size = size if size is not None else self.size
356
+ size = get_size_dict(size, param_name="size", default_to_square=False)
357
+ resample = resample if resample is not None else self.resample
358
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
359
+ crop_size = crop_size if crop_size is not None else self.crop_size
360
+ crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
361
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
362
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
363
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
364
+ image_mean = image_mean if image_mean is not None else self.image_mean
365
+ image_std = image_std if image_std is not None else self.image_std
366
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
367
+
368
+ validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
369
+
370
+ images = make_list_of_images(images)
371
+
372
+ if not valid_images(images):
373
+ raise ValueError(
374
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
375
+ "torch.Tensor, tf.Tensor or jax.ndarray."
376
+ )
377
+ # we don't pass `do_pad` here since LLaVa uses a custom padding to a square
378
+ validate_preprocess_arguments(
379
+ do_rescale=do_rescale,
380
+ rescale_factor=rescale_factor,
381
+ do_normalize=do_normalize,
382
+ image_mean=image_mean,
383
+ image_std=image_std,
384
+ do_center_crop=do_center_crop,
385
+ crop_size=crop_size,
386
+ do_resize=do_resize,
387
+ size=size,
388
+ resample=resample,
389
+ )
390
+
391
+ if do_convert_rgb:
392
+ images = [convert_to_rgb(image) for image in images]
393
+
394
+ # All transformations expect numpy arrays.
395
+ images = [to_numpy_array(image) for image in images]
396
+
397
+ if is_scaled_image(images[0]) and do_rescale:
398
+ logger.warning_once(
399
+ "It looks like you are trying to rescale already rescaled images. If the input"
400
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
401
+ )
402
+
403
+ if input_data_format is None:
404
+ # We assume that all images have the same channel dimension format.
405
+ input_data_format = infer_channel_dimension_format(images[0])
406
+
407
+ processed_images = []
408
+ for image in images:
409
+ if do_pad:
410
+ image = self.pad_to_square(
411
+ image=image,
412
+ background_color=tuple(int(x * 255) for x in self.image_mean),
413
+ input_data_format=input_data_format,
414
+ )
415
+
416
+ if do_resize:
417
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
418
+
419
+ if do_center_crop:
420
+ image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
421
+
422
+ if do_rescale:
423
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
424
+
425
+ if do_normalize:
426
+ image = self.normalize(
427
+ image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
428
+ )
429
+
430
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
431
+ processed_images.append(image)
432
+
433
+ return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
434
+
435
+
436
+ __all__ = ["LlavaImageProcessor"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava/image_processing_llava_fast.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Fast Image processor class for LLaVa."""
16
+
17
+ from typing import Optional, Union
18
+
19
+ from ...image_processing_utils import BatchFeature
20
+ from ...image_processing_utils_fast import (
21
+ BaseImageProcessorFast,
22
+ DefaultFastImageProcessorKwargs,
23
+ group_images_by_shape,
24
+ reorder_images,
25
+ )
26
+ from ...image_utils import (
27
+ OPENAI_CLIP_MEAN,
28
+ OPENAI_CLIP_STD,
29
+ ChannelDimension,
30
+ ImageInput,
31
+ PILImageResampling,
32
+ SizeDict,
33
+ get_image_size,
34
+ )
35
+ from ...processing_utils import Unpack
36
+ from ...utils import (
37
+ TensorType,
38
+ auto_docstring,
39
+ is_torch_available,
40
+ is_torchvision_available,
41
+ is_torchvision_v2_available,
42
+ is_vision_available,
43
+ )
44
+
45
+
46
+ if is_vision_available():
47
+ from ...image_utils import PILImageResampling
48
+
49
+ if is_torch_available():
50
+ import torch
51
+
52
+ if is_torchvision_available():
53
+ if is_torchvision_v2_available():
54
+ from torchvision.transforms.v2 import functional as F
55
+ else:
56
+ from torchvision.transforms import functional as F
57
+
58
+
59
+ class LlavaFastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
60
+ """
61
+ Args:
62
+ do_pad (`bool`, *optional*):
63
+ Whether to pad the image to a square based on the longest edge.
64
+ """
65
+
66
+ do_pad: Optional[bool]
67
+
68
+
69
+ @auto_docstring
70
+ class LlavaImageProcessorFast(BaseImageProcessorFast):
71
+ resample = PILImageResampling.BICUBIC
72
+ image_mean = OPENAI_CLIP_MEAN
73
+ image_std = OPENAI_CLIP_STD
74
+ size = {"shortest_edge": 224}
75
+ default_to_square = False
76
+ crop_size = {"height": 224, "width": 224}
77
+ do_pad = False
78
+ do_resize = True
79
+ do_center_crop = True
80
+ do_rescale = True
81
+ do_normalize = True
82
+ do_convert_rgb = True
83
+ valid_kwargs = LlavaFastImageProcessorKwargs
84
+
85
+ def __init__(self, **kwargs: Unpack[LlavaFastImageProcessorKwargs]) -> None:
86
+ super().__init__(**kwargs)
87
+
88
+ @auto_docstring
89
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[LlavaFastImageProcessorKwargs]) -> BatchFeature:
90
+ return super().preprocess(images, **kwargs)
91
+
92
+ def pad_to_square(
93
+ self,
94
+ images: "torch.Tensor",
95
+ background_color: Union[int, tuple[int, int, int]] = 0,
96
+ ) -> "torch.Tensor":
97
+ """
98
+ Pads an image to a square based on the longest edge.
99
+
100
+ Args:
101
+ images (`np.ndarray`):
102
+ The images to pad.
103
+ background_color (`int` or `tuple[int, int, int]`, *optional*, defaults to 0):
104
+ The color to use for the padding. Can be an integer for single channel or a
105
+ tuple of integers representing for multi-channel images. If passed as integer
106
+ in mutli-channel mode, it will default to `0` in subsequent channels.
107
+ Returns:
108
+ `torch.Tensor`: The padded images.
109
+ """
110
+ height, width = get_image_size(images, ChannelDimension.FIRST)
111
+
112
+ if height == width:
113
+ return images
114
+
115
+ num_channels = images.shape[1] if len(images.shape) == 4 else images.shape[0]
116
+ if isinstance(background_color, int):
117
+ background_color = [background_color] + [0] * (num_channels - 1)
118
+ elif len(background_color) != num_channels:
119
+ raise ValueError(
120
+ f"background_color must have no more than {num_channels} elements to match the number of channels"
121
+ )
122
+
123
+ max_dim = max(height, width)
124
+ paste_x_left = (max_dim - width) // 2
125
+ paste_y_left = (max_dim - height) // 2
126
+ paste_x_right = max_dim - width - paste_x_left
127
+ paste_y_right = max_dim - height - paste_y_left
128
+ padded_images = F.pad(
129
+ images, padding=[paste_x_left, paste_y_left, paste_x_right, paste_y_right], fill=background_color
130
+ )
131
+
132
+ return padded_images
133
+
134
+ def _preprocess(
135
+ self,
136
+ images: list["torch.Tensor"],
137
+ do_resize: bool,
138
+ size: SizeDict,
139
+ interpolation: Optional["F.InterpolationMode"],
140
+ do_pad: bool,
141
+ do_center_crop: bool,
142
+ crop_size: SizeDict,
143
+ do_rescale: bool,
144
+ rescale_factor: float,
145
+ do_normalize: bool,
146
+ image_mean: Optional[Union[float, list[float]]],
147
+ image_std: Optional[Union[float, list[float]]],
148
+ disable_grouping: Optional[bool],
149
+ return_tensors: Optional[Union[str, TensorType]],
150
+ ) -> BatchFeature:
151
+ # Group images by size for batched resizing
152
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
153
+ resized_images_grouped = {}
154
+ for shape, stacked_images in grouped_images.items():
155
+ if do_pad:
156
+ stacked_images = self.pad_to_square(
157
+ images=stacked_images, background_color=tuple(int(x * 255) for x in self.image_mean)
158
+ )
159
+ resized_images_grouped[shape] = stacked_images
160
+ padded_images = reorder_images(resized_images_grouped, grouped_images_index)
161
+
162
+ # Group images by size for batched resizing
163
+ # Needed in case do_pad is False, or padding returns images with different sizes
164
+ grouped_images, grouped_images_index = group_images_by_shape(padded_images, disable_grouping=disable_grouping)
165
+ resized_images_grouped = {}
166
+ for shape, stacked_images in grouped_images.items():
167
+ if do_resize:
168
+ stacked_images = self.resize(image=stacked_images, size=size, interpolation=interpolation)
169
+ resized_images_grouped[shape] = stacked_images
170
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
171
+
172
+ # Group images by size for further processing
173
+ # Needed in case do_resize is False, or resize returns images with different sizes
174
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
175
+ processed_images_grouped = {}
176
+ for shape, stacked_images in grouped_images.items():
177
+ if do_center_crop:
178
+ stacked_images = self.center_crop(stacked_images, crop_size)
179
+ # Fused rescale and normalize
180
+ stacked_images = self.rescale_and_normalize(
181
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
182
+ )
183
+ processed_images_grouped[shape] = stacked_images
184
+
185
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
186
+ processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images
187
+
188
+ return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
189
+
190
+
191
+ __all__ = ["LlavaImageProcessorFast"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava/modeling_llava.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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 Llava model."""
16
+
17
+ from dataclasses import dataclass
18
+ from typing import Optional, Union
19
+
20
+ import torch
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+
24
+ from ...activations import ACT2FN
25
+ from ...cache_utils import Cache
26
+ from ...generation import GenerationMixin
27
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
28
+ from ...modeling_outputs import BaseModelOutputWithPast, ModelOutput
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...processing_utils import Unpack
31
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
32
+ from ..auto import AutoModel
33
+ from .configuration_llava import LlavaConfig
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ @dataclass
40
+ @auto_docstring(
41
+ custom_intro="""
42
+ Base class for Llava outputs, with hidden states and attentions.
43
+ """
44
+ )
45
+ class LlavaModelOutputWithPast(BaseModelOutputWithPast):
46
+ r"""
47
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
48
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
49
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
50
+
51
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
52
+ `past_key_values` input) to speed up sequential decoding.
53
+ image_hidden_states (`torch.FloatTensor`, *optional*):
54
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
55
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
56
+ """
57
+
58
+ image_hidden_states: Optional[torch.FloatTensor] = None
59
+
60
+
61
+ @dataclass
62
+ @auto_docstring(
63
+ custom_intro="""
64
+ Base class for Llava causal language model (or autoregressive) outputs.
65
+ """
66
+ )
67
+ class LlavaCausalLMOutputWithPast(ModelOutput):
68
+ r"""
69
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
70
+ Language modeling loss (for next-token prediction).
71
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
72
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
73
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
74
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
75
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
76
+
77
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
78
+ `past_key_values` input) to speed up sequential decoding.
79
+ image_hidden_states (`torch.FloatTensor`, *optional*):
80
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
81
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
82
+ """
83
+
84
+ loss: Optional[torch.FloatTensor] = None
85
+ logits: Optional[torch.FloatTensor] = None
86
+ past_key_values: Optional[list[torch.FloatTensor]] = None
87
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
88
+ attentions: Optional[tuple[torch.FloatTensor]] = None
89
+ image_hidden_states: Optional[torch.FloatTensor] = None
90
+
91
+
92
+ class LlavaMultiModalProjector(nn.Module):
93
+ def __init__(self, config: LlavaConfig):
94
+ super().__init__()
95
+ # We have hidden_size * the number of vision feature layers
96
+ num_feature_layers = 1 if isinstance(config.vision_feature_layer, int) else len(config.vision_feature_layer)
97
+ self.linear_1 = nn.Linear(
98
+ config.vision_config.hidden_size * num_feature_layers,
99
+ config.text_config.hidden_size,
100
+ bias=config.multimodal_projector_bias,
101
+ )
102
+ self.act = ACT2FN[config.projector_hidden_act]
103
+ self.linear_2 = nn.Linear(
104
+ config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias
105
+ )
106
+
107
+ def forward(self, image_features):
108
+ hidden_states = self.linear_1(image_features)
109
+ hidden_states = self.act(hidden_states)
110
+ hidden_states = self.linear_2(hidden_states)
111
+ return hidden_states
112
+
113
+
114
+ @auto_docstring
115
+ class LlavaPreTrainedModel(PreTrainedModel):
116
+ config: LlavaConfig
117
+ base_model_prefix = ""
118
+ supports_gradient_checkpointing = True
119
+ _skip_keys_device_placement = "past_key_values"
120
+
121
+ _supports_flash_attn = True
122
+ _supports_sdpa = True
123
+
124
+ _can_compile_fullgraph = True
125
+ _supports_flex_attn = True
126
+ _supports_attention_backend = True
127
+
128
+
129
+ @auto_docstring(
130
+ custom_intro="""
131
+ The Llava model which consists of a vision backbone and a language model, without a language modeling head.
132
+ """
133
+ )
134
+ class LlavaModel(LlavaPreTrainedModel):
135
+ _checkpoint_conversion_mapping = {"language_model.model": "language_model"}
136
+
137
+ def __init__(self, config: LlavaConfig):
138
+ super().__init__(config)
139
+ self.vision_tower = AutoModel.from_config(config.vision_config)
140
+
141
+ self.multi_modal_projector = LlavaMultiModalProjector(config)
142
+ self.language_model = AutoModel.from_config(config.text_config)
143
+ self.post_init()
144
+
145
+ def get_input_embeddings(self):
146
+ return self.language_model.get_input_embeddings()
147
+
148
+ def set_input_embeddings(self, value):
149
+ self.language_model.set_input_embeddings(value)
150
+
151
+ def set_decoder(self, decoder):
152
+ self.language_model = decoder
153
+
154
+ def get_decoder(self):
155
+ return self.language_model
156
+
157
+ def get_image_features(
158
+ self,
159
+ pixel_values: torch.FloatTensor,
160
+ vision_feature_layer: Optional[Union[int, list[int]]] = None,
161
+ vision_feature_select_strategy: Optional[str] = None,
162
+ **kwargs,
163
+ ):
164
+ """
165
+ Obtains image last hidden states from the vision tower and apply multimodal projection.
166
+
167
+ Args:
168
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`):
169
+ The tensors corresponding to the input images.
170
+ vision_feature_layer (`Union[int, list[int]]`, *optional*):
171
+ The index of the layer to select the vision feature. If multiple indices are provided,
172
+ the vision feature of the corresponding indices will be concatenated to form the
173
+ vision features.
174
+ vision_feature_select_strategy (`str`, *optional*):
175
+ The feature selection strategy used to select the vision feature from the vision backbone.
176
+ Can be one of `"default"` or `"full"`
177
+ Returns:
178
+ image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
179
+ """
180
+ vision_feature_layer = (
181
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
182
+ )
183
+ vision_feature_select_strategy = (
184
+ vision_feature_select_strategy
185
+ if vision_feature_select_strategy is not None
186
+ else self.config.vision_feature_select_strategy
187
+ )
188
+
189
+ if vision_feature_select_strategy not in ["default", "full"]:
190
+ raise ValueError(f"Unexpected select feature strategy: {self.config.vision_feature_select_strategy}")
191
+
192
+ kwargs = {k: v for k, v in kwargs.items() if v is not None}
193
+ # this is not memory efficient at all (output_hidden_states=True) will save all the hidden states.
194
+ image_outputs = self.vision_tower(pixel_values, output_hidden_states=True, **kwargs)
195
+
196
+ # If we have one vision feature layer, return the corresponding hidden states,
197
+ # otherwise, select the hidden states of each feature layer and concatenate them
198
+ if isinstance(vision_feature_layer, int):
199
+ selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
200
+ if vision_feature_select_strategy == "default":
201
+ selected_image_feature = selected_image_feature[:, 1:]
202
+ else:
203
+ hs_pool = [image_outputs.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
204
+ # For default; crop CLS from each hidden state in the hidden state pool
205
+ if vision_feature_select_strategy == "default":
206
+ hs_pool = [hs[:, 1:] for hs in hs_pool]
207
+ selected_image_feature = torch.cat(hs_pool, dim=-1)
208
+
209
+ image_features = self.multi_modal_projector(selected_image_feature)
210
+
211
+ if "image_sizes" in kwargs:
212
+ split_sizes = [
213
+ (height // self.vision_tower.patch_size) * (width // self.vision_tower.patch_size)
214
+ for height, width in kwargs["image_sizes"]
215
+ ]
216
+ image_features = torch.split(image_features.squeeze(0), split_sizes)
217
+ else:
218
+ image_features = list(image_features)
219
+ return image_features
220
+
221
+ def get_placeholder_mask(
222
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
223
+ ):
224
+ """
225
+ Obtains multimodal placeholdr mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
226
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
227
+ """
228
+ if input_ids is None:
229
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
230
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
231
+ )
232
+ special_image_mask = special_image_mask.all(-1)
233
+ else:
234
+ special_image_mask = input_ids == self.config.image_token_id
235
+
236
+ n_image_tokens = special_image_mask.sum()
237
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
238
+ n_image_features = image_features.shape[0] * image_features.shape[1]
239
+ if inputs_embeds[special_image_mask].numel() != image_features.numel():
240
+ raise ValueError(
241
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
242
+ )
243
+ return special_image_mask
244
+
245
+ @can_return_tuple
246
+ @auto_docstring
247
+ def forward(
248
+ self,
249
+ input_ids: torch.LongTensor = None,
250
+ pixel_values: torch.FloatTensor = None,
251
+ attention_mask: Optional[torch.Tensor] = None,
252
+ position_ids: Optional[torch.LongTensor] = None,
253
+ past_key_values: Optional[Cache] = None,
254
+ inputs_embeds: Optional[torch.FloatTensor] = None,
255
+ vision_feature_layer: Optional[Union[int, list[int]]] = None,
256
+ vision_feature_select_strategy: Optional[str] = None,
257
+ use_cache: Optional[bool] = None,
258
+ output_attentions: Optional[bool] = None,
259
+ output_hidden_states: Optional[bool] = None,
260
+ return_dict: Optional[bool] = None,
261
+ cache_position: Optional[torch.LongTensor] = None,
262
+ image_sizes: torch.Tensor = None,
263
+ **kwargs: Unpack[FlashAttentionKwargs],
264
+ ) -> Union[tuple, LlavaModelOutputWithPast]:
265
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
266
+ output_hidden_states = (
267
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
268
+ )
269
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
270
+ vision_feature_layer = (
271
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
272
+ )
273
+ vision_feature_select_strategy = (
274
+ vision_feature_select_strategy
275
+ if vision_feature_select_strategy is not None
276
+ else self.config.vision_feature_select_strategy
277
+ )
278
+
279
+ if (input_ids is None) ^ (inputs_embeds is not None):
280
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
281
+
282
+ if inputs_embeds is None:
283
+ inputs_embeds = self.get_input_embeddings()(input_ids)
284
+
285
+ if pixel_values is not None:
286
+ image_features = self.get_image_features(
287
+ pixel_values=pixel_values,
288
+ vision_feature_layer=vision_feature_layer,
289
+ vision_feature_select_strategy=vision_feature_select_strategy,
290
+ image_sizes=image_sizes,
291
+ )
292
+ image_features = torch.cat(image_features, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
293
+ special_image_mask = self.get_placeholder_mask(
294
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
295
+ )
296
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
297
+
298
+ outputs = self.language_model(
299
+ attention_mask=attention_mask,
300
+ position_ids=position_ids,
301
+ past_key_values=past_key_values,
302
+ inputs_embeds=inputs_embeds,
303
+ use_cache=use_cache,
304
+ output_attentions=output_attentions,
305
+ output_hidden_states=output_hidden_states,
306
+ return_dict=True,
307
+ cache_position=cache_position,
308
+ **kwargs,
309
+ )
310
+
311
+ return LlavaModelOutputWithPast(
312
+ last_hidden_state=outputs.last_hidden_state,
313
+ past_key_values=outputs.past_key_values,
314
+ hidden_states=outputs.hidden_states,
315
+ attentions=outputs.attentions,
316
+ image_hidden_states=image_features if pixel_values is not None else None,
317
+ )
318
+
319
+
320
+ @auto_docstring(
321
+ custom_intro="""
322
+ The LLAVA model which consists of a vision backbone and a language model.
323
+ """
324
+ )
325
+ class LlavaForConditionalGeneration(LlavaPreTrainedModel, GenerationMixin):
326
+ _checkpoint_conversion_mapping = {
327
+ "^language_model.model": "model.language_model",
328
+ "^vision_tower": "model.vision_tower",
329
+ "^multi_modal_projector": "model.multi_modal_projector",
330
+ "^language_model.lm_head": "lm_head",
331
+ }
332
+ _tied_weights_keys = ["lm_head.weight"]
333
+
334
+ def __init__(self, config: LlavaConfig):
335
+ super().__init__(config)
336
+ self.model = LlavaModel(config)
337
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
338
+ self.post_init()
339
+
340
+ def get_input_embeddings(self):
341
+ return self.model.get_input_embeddings()
342
+
343
+ def set_input_embeddings(self, value):
344
+ self.model.set_input_embeddings(value)
345
+
346
+ def get_output_embeddings(self) -> nn.Module:
347
+ return self.lm_head
348
+
349
+ def set_decoder(self, decoder):
350
+ self.model.set_decoder(decoder)
351
+
352
+ def get_decoder(self):
353
+ return self.model.get_decoder()
354
+
355
+ def get_image_features(
356
+ self,
357
+ pixel_values: torch.FloatTensor,
358
+ vision_feature_layer: Optional[Union[int, list[int]]] = None,
359
+ vision_feature_select_strategy: Optional[str] = None,
360
+ **kwargs,
361
+ ):
362
+ return self.model.get_image_features(
363
+ pixel_values=pixel_values,
364
+ vision_feature_layer=vision_feature_layer,
365
+ vision_feature_select_strategy=vision_feature_select_strategy,
366
+ **kwargs,
367
+ )
368
+
369
+ # Make modules available through conditional class for BC
370
+ @property
371
+ def language_model(self):
372
+ return self.model.language_model
373
+
374
+ @property
375
+ def vision_tower(self):
376
+ return self.model.vision_tower
377
+
378
+ @property
379
+ def multi_modal_projector(self):
380
+ return self.model.multi_modal_projector
381
+
382
+ @can_return_tuple
383
+ @auto_docstring
384
+ def forward(
385
+ self,
386
+ input_ids: torch.LongTensor = None,
387
+ pixel_values: torch.FloatTensor = None,
388
+ attention_mask: Optional[torch.Tensor] = None,
389
+ position_ids: Optional[torch.LongTensor] = None,
390
+ past_key_values: Optional[Cache] = None,
391
+ inputs_embeds: Optional[torch.FloatTensor] = None,
392
+ vision_feature_layer: Optional[Union[int, list[int]]] = None,
393
+ vision_feature_select_strategy: Optional[str] = None,
394
+ labels: Optional[torch.LongTensor] = None,
395
+ use_cache: Optional[bool] = None,
396
+ output_attentions: Optional[bool] = None,
397
+ output_hidden_states: Optional[bool] = None,
398
+ return_dict: Optional[bool] = None,
399
+ cache_position: Optional[torch.LongTensor] = None,
400
+ logits_to_keep: Union[int, torch.Tensor] = 0,
401
+ image_sizes: Optional[torch.Tensor] = None,
402
+ **kwargs: Unpack[TransformersKwargs],
403
+ ) -> Union[tuple, LlavaCausalLMOutputWithPast]:
404
+ r"""
405
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
406
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
407
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
408
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
409
+
410
+ Example:
411
+
412
+ ```python
413
+ >>> from PIL import Image
414
+ >>> import requests
415
+ >>> from transformers import AutoProcessor, LlavaForConditionalGeneration
416
+
417
+ >>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
418
+ >>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
419
+
420
+ >>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
421
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
422
+ >>> image = Image.open(requests.get(url, stream=True).raw)
423
+
424
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
425
+
426
+ >>> # Generate
427
+ >>> generate_ids = model.generate(**inputs, max_new_tokens=15)
428
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
429
+ "USER: \nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed"
430
+ ```"""
431
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
432
+ output_hidden_states = (
433
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
434
+ )
435
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
436
+ vision_feature_layer = (
437
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
438
+ )
439
+ vision_feature_select_strategy = (
440
+ vision_feature_select_strategy
441
+ if vision_feature_select_strategy is not None
442
+ else self.config.vision_feature_select_strategy
443
+ )
444
+
445
+ outputs = self.model(
446
+ input_ids=input_ids,
447
+ pixel_values=pixel_values,
448
+ attention_mask=attention_mask,
449
+ position_ids=position_ids,
450
+ past_key_values=past_key_values,
451
+ inputs_embeds=inputs_embeds,
452
+ vision_feature_layer=vision_feature_layer,
453
+ vision_feature_select_strategy=vision_feature_select_strategy,
454
+ use_cache=use_cache,
455
+ output_attentions=output_attentions,
456
+ output_hidden_states=output_hidden_states,
457
+ return_dict=True,
458
+ cache_position=cache_position,
459
+ image_sizes=image_sizes,
460
+ **kwargs,
461
+ )
462
+
463
+ hidden_states = outputs[0]
464
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
465
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
466
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
467
+
468
+ loss = None
469
+ if labels is not None:
470
+ loss = self.loss_function(
471
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
472
+ )
473
+
474
+ return LlavaCausalLMOutputWithPast(
475
+ loss=loss,
476
+ logits=logits,
477
+ past_key_values=outputs.past_key_values,
478
+ hidden_states=outputs.hidden_states,
479
+ attentions=outputs.attentions,
480
+ image_hidden_states=outputs.image_hidden_states,
481
+ )
482
+
483
+ def prepare_inputs_for_generation(
484
+ self,
485
+ input_ids,
486
+ past_key_values=None,
487
+ inputs_embeds=None,
488
+ pixel_values=None,
489
+ attention_mask=None,
490
+ cache_position=None,
491
+ logits_to_keep=None,
492
+ **kwargs,
493
+ ):
494
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
495
+
496
+ model_inputs = super().prepare_inputs_for_generation(
497
+ input_ids,
498
+ past_key_values=past_key_values,
499
+ inputs_embeds=inputs_embeds,
500
+ attention_mask=attention_mask,
501
+ cache_position=cache_position,
502
+ logits_to_keep=logits_to_keep,
503
+ **kwargs,
504
+ )
505
+
506
+ if cache_position[0] == 0:
507
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
508
+ # Otherwise we need pixel values to be passed to model
509
+ model_inputs["pixel_values"] = pixel_values
510
+
511
+ return model_inputs
512
+
513
+
514
+ __all__ = ["LlavaForConditionalGeneration", "LlavaPreTrainedModel", "LlavaModel"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava/processing_llava.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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 Llava.
17
+ """
18
+
19
+ from typing import Union
20
+
21
+ import numpy as np
22
+
23
+ from ...feature_extraction_utils import BatchFeature
24
+ from ...image_utils import ImageInput, get_image_size, to_numpy_array
25
+ from ...processing_utils import (
26
+ MultiModalData,
27
+ ProcessingKwargs,
28
+ ProcessorMixin,
29
+ Unpack,
30
+ )
31
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
32
+ from ...utils import logging
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ class LlavaProcessorKwargs(ProcessingKwargs, total=False):
39
+ _defaults = {
40
+ "text_kwargs": {"padding": False, "return_mm_token_type_ids": False},
41
+ "images_kwargs": {},
42
+ }
43
+
44
+
45
+ class LlavaProcessor(ProcessorMixin):
46
+ r"""
47
+ Constructs a LLaVa processor which wraps a LLaVa image processor and a LLaMa tokenizer into a single processor.
48
+
49
+ [`LlavaProcessor`] offers all the functionalities of [`LlavaImageProcessor`] and [`LlamaTokenizerFast`]. See the
50
+ [`~LlavaProcessor.__call__`] and [`~LlavaProcessor.decode`] for more information.
51
+
52
+ Args:
53
+ image_processor ([`LlavaImageProcessor`], *optional*):
54
+ The image processor is a required input.
55
+ tokenizer ([`LlamaTokenizerFast`], *optional*):
56
+ The tokenizer is a required input.
57
+ patch_size (`int`, *optional*):
58
+ Patch size from the vision tower.
59
+ vision_feature_select_strategy (`str`, *optional*):
60
+ The feature selection strategy used to select the vision feature from the vision backbone.
61
+ Should be same as in model's config
62
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
63
+ in a chat into a tokenizable string.
64
+ image_token (`str`, *optional*, defaults to `"<image>"`):
65
+ Special token used to denote image location.
66
+ num_additional_image_tokens (`int`, *optional*, defaults to 0):
67
+ Number of additional tokens added to the image embeddings, such as CLS (+1). If the backbone has no CLS or other
68
+ extra tokens appended, no need to set this arg.
69
+ """
70
+
71
+ attributes = ["image_processor", "tokenizer"]
72
+ image_processor_class = "AutoImageProcessor"
73
+ tokenizer_class = "AutoTokenizer"
74
+
75
+ def __init__(
76
+ self,
77
+ image_processor=None,
78
+ tokenizer=None,
79
+ patch_size=None,
80
+ vision_feature_select_strategy=None,
81
+ chat_template=None,
82
+ image_token="<image>", # set the default and let users change if they have peculiar special tokens in rare cases
83
+ num_additional_image_tokens=0,
84
+ **kwargs,
85
+ ):
86
+ self.patch_size = patch_size
87
+ self.num_additional_image_tokens = num_additional_image_tokens
88
+ self.vision_feature_select_strategy = vision_feature_select_strategy
89
+ self.image_token = tokenizer.image_token if hasattr(tokenizer, "image_token") else image_token
90
+ self.image_token_id = tokenizer.encode(self.image_token, add_special_tokens=False)[0]
91
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
92
+
93
+ def __call__(
94
+ self,
95
+ images: ImageInput = None,
96
+ text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
97
+ audio=None,
98
+ videos=None,
99
+ **kwargs: Unpack[LlavaProcessorKwargs],
100
+ ) -> BatchFeature:
101
+ """
102
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
103
+ and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
104
+ the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
105
+ CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
106
+ of the above two methods for more information.
107
+
108
+ Args:
109
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
110
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
111
+ tensor. Both channels-first and channels-last formats are supported.
112
+ text (`str`, `list[str]`, `list[list[str]]`):
113
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
114
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
115
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
116
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
117
+ If set, will return tensors of a particular framework. Acceptable values are:
118
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
119
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
120
+ - `'np'`: Return NumPy `np.ndarray` objects.
121
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
122
+
123
+ Returns:
124
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
125
+
126
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
127
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
128
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
129
+ `None`).
130
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
131
+ """
132
+ if images is None and text is None:
133
+ raise ValueError("You have to specify at least one of `images` or `text`.")
134
+
135
+ output_kwargs = self._merge_kwargs(
136
+ LlavaProcessorKwargs,
137
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
138
+ **kwargs,
139
+ )
140
+ if images is not None:
141
+ image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
142
+ else:
143
+ image_inputs = {}
144
+
145
+ if isinstance(text, str):
146
+ text = [text]
147
+ elif not isinstance(text, list) and not isinstance(text[0], str):
148
+ raise TypeError("Invalid input text. Please provide a string, or a list of strings")
149
+
150
+ # try to expand inputs in processing if we have the necessary parts
151
+ prompt_strings = text
152
+ if image_inputs.get("pixel_values") is not None:
153
+ # Replace the image token with the expanded image token sequence
154
+ pixel_values = image_inputs["pixel_values"]
155
+ height, width = get_image_size(to_numpy_array(pixel_values[0]))
156
+ num_image_tokens = (height // self.patch_size) * (
157
+ width // self.patch_size
158
+ ) + self.num_additional_image_tokens
159
+ if self.vision_feature_select_strategy == "default":
160
+ num_image_tokens -= 1
161
+
162
+ prompt_strings = []
163
+ for sample in text:
164
+ sample = sample.replace(self.image_token, self.image_token * num_image_tokens)
165
+ prompt_strings.append(sample)
166
+
167
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
168
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
169
+ text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"], return_tensors=None)
170
+ self._check_special_mm_tokens(prompt_strings, text_inputs, modalities=["image"])
171
+
172
+ if return_mm_token_type_ids:
173
+ array_ids = np.array(text_inputs["input_ids"])
174
+ mm_token_type_ids = np.zeros_like(text_inputs["input_ids"])
175
+ mm_token_type_ids[array_ids == self.image_token_id] = 1
176
+ text_inputs["mm_token_type_ids"] = mm_token_type_ids.tolist()
177
+
178
+ return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
179
+
180
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
181
+ """
182
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
183
+
184
+ Args:
185
+ image_sizes (`list[list[int]]`, *optional*):
186
+ The input sizes formatted as (height, width) per each image.
187
+
188
+ Returns:
189
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
190
+ input modalities, along with other useful data.
191
+ """
192
+
193
+ vision_data = {}
194
+ if image_sizes is not None:
195
+ images_kwargs = LlavaProcessorKwargs._defaults.get("images_kwargs", {})
196
+ images_kwargs.update(kwargs)
197
+ crop_size = images_kwargs.get("crop_size", None) or self.image_processor.crop_size
198
+ resized_height, resized_width = crop_size["height"], crop_size["width"]
199
+
200
+ num_image_tokens = (resized_height // self.patch_size) * (resized_width // self.patch_size)
201
+ num_image_tokens += self.num_additional_image_tokens
202
+ if self.vision_feature_select_strategy == "default":
203
+ num_image_tokens -= 1
204
+
205
+ num_image_tokens = [num_image_tokens] * len(image_sizes)
206
+ num_image_patches = [1] * len(image_sizes)
207
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
208
+
209
+ return MultiModalData(**vision_data)
210
+
211
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
212
+ def batch_decode(self, *args, **kwargs):
213
+ """
214
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
215
+ refer to the docstring of this method for more information.
216
+ """
217
+ return self.tokenizer.batch_decode(*args, **kwargs)
218
+
219
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
220
+ def decode(self, *args, **kwargs):
221
+ """
222
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
223
+ the docstring of this method for more information.
224
+ """
225
+ return self.tokenizer.decode(*args, **kwargs)
226
+
227
+ @property
228
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
229
+ def model_input_names(self):
230
+ tokenizer_input_names = self.tokenizer.model_input_names
231
+ image_processor_input_names = self.image_processor.model_input_names
232
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
233
+
234
+
235
+ __all__ = ["LlavaProcessor"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava_next/__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_llava_next import *
22
+ from .image_processing_llava_next import *
23
+ from .image_processing_llava_next_fast import *
24
+ from .modeling_llava_next import *
25
+ from .processing_llava_next 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-5cbfd9f64dbc/environment/source/src/transformers/models/llava_next/configuration_llava_next.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
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
+ """Llava-NeXT model configuration"""
15
+
16
+ from ...configuration_utils import PretrainedConfig
17
+ from ...utils import logging
18
+ from ..auto import CONFIG_MAPPING, AutoConfig
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class LlavaNextConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`LlavaNextForConditionalGeneration`]. It is used to instantiate an
27
+ Llava-NeXT 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 [llava-hf/llava-v1.6-mistral-7b-hf](https://huggingface.co/llava-hf/llava-v1.6-mistral-7b-hf)
29
+ model.
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
+ Args:
35
+ vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `CLIPVisionConfig`):
36
+ The config object or dictionary of the vision backbone.
37
+ text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `LlamaConfig`):
38
+ The config object or dictionary of the text backbone.
39
+ image_token_index (`int`, *optional*, defaults to 32000):
40
+ The image token index to encode the image prompt.
41
+ projector_hidden_act (`str`, *optional*, defaults to `"gelu"`):
42
+ The activation function used by the multimodal projector.
43
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
44
+ The feature selection strategy used to select the vision feature from the vision backbone.
45
+ Can be one of `"default"` or `"full"`. If `"default"`, the CLS token is removed from the vision features.
46
+ If `"full"`, the full vision features are used.
47
+ vision_feature_layer (`Union[int, list[int]]`, *optional*, defaults to -2):
48
+ The index of the layer to select the vision feature. If multiple indices are provided,
49
+ the vision feature of the corresponding indices will be concatenated to form the
50
+ vision features.
51
+ image_grid_pinpoints (`List`, *optional*, defaults to `[[336, 672], [672, 336], [672, 672], [1008, 336], [336, 1008]]`):
52
+ A list of possible resolutions to use for processing high resolution images. Each item in the list should be a tuple or list
53
+ of the form `(height, width)`.
54
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
55
+ Whether the model's input and output word embeddings should be tied.
56
+ image_seq_length (`int`, *optional*, defaults to 576):
57
+ Sequence length of one image embedding.
58
+ multimodal_projector_bias (`bool`, *optional*, defaults to `True`):
59
+ Whether to use bias in the multimodal projector.
60
+
61
+ Example:
62
+
63
+ ```python
64
+ >>> from transformers import LlavaNextForConditionalGeneration, LlavaNextConfig, CLIPVisionConfig, LlamaConfig
65
+
66
+ >>> # Initializing a CLIP-vision config
67
+ >>> vision_config = CLIPVisionConfig()
68
+
69
+ >>> # Initializing a Llama config
70
+ >>> text_config = LlamaConfig()
71
+
72
+ >>> # Initializing a Llava-Next llava-hf/llava-v1.6-mistral-7b-hf style configuration
73
+ >>> configuration = LlavaNextConfig(vision_config, text_config)
74
+
75
+ >>> # Initializing a model from the llava-hf/llava-v1.6-mistral-7b-hf style configuration
76
+ >>> model = LlavaNextForConditionalGeneration(configuration)
77
+
78
+ >>> # Accessing the model configuration
79
+ >>> configuration = model.config
80
+ ```"""
81
+
82
+ model_type = "llava_next"
83
+ attribute_map = {
84
+ "image_token_id": "image_token_index",
85
+ }
86
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
87
+
88
+ def __init__(
89
+ self,
90
+ vision_config=None,
91
+ text_config=None,
92
+ image_token_index=32000,
93
+ projector_hidden_act="gelu",
94
+ vision_feature_select_strategy="default",
95
+ vision_feature_layer=-2,
96
+ image_grid_pinpoints=None,
97
+ tie_word_embeddings=False,
98
+ image_seq_length=576,
99
+ multimodal_projector_bias=True,
100
+ **kwargs,
101
+ ):
102
+ self.image_token_index = image_token_index
103
+ self.projector_hidden_act = projector_hidden_act
104
+ self.image_seq_length = image_seq_length
105
+ self.multimodal_projector_bias = multimodal_projector_bias
106
+
107
+ if vision_feature_select_strategy not in ["default", "full"]:
108
+ raise ValueError(
109
+ "vision_feature_select_strategy should be one of 'default', 'full'."
110
+ f"Got: {vision_feature_select_strategy}"
111
+ )
112
+
113
+ self.vision_feature_select_strategy = vision_feature_select_strategy
114
+ self.vision_feature_layer = vision_feature_layer
115
+ image_grid_pinpoints = (
116
+ image_grid_pinpoints
117
+ if image_grid_pinpoints is not None
118
+ else [[336, 672], [672, 336], [672, 672], [1008, 336], [336, 1008]]
119
+ )
120
+ self.image_grid_pinpoints = image_grid_pinpoints
121
+
122
+ if isinstance(vision_config, dict):
123
+ vision_config["model_type"] = vision_config.get("model_type", "clip_vision_model")
124
+ vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
125
+ elif vision_config is None:
126
+ vision_config = CONFIG_MAPPING["clip_vision_model"](
127
+ intermediate_size=4096,
128
+ hidden_size=1024,
129
+ patch_size=14,
130
+ image_size=336,
131
+ num_hidden_layers=24,
132
+ num_attention_heads=16,
133
+ vocab_size=32000,
134
+ projection_dim=768,
135
+ )
136
+
137
+ self.vision_config = vision_config
138
+
139
+ if isinstance(text_config, dict):
140
+ text_config["model_type"] = text_config.get("model_type", "llama")
141
+ text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
142
+ elif text_config is None:
143
+ text_config = CONFIG_MAPPING["llama"]()
144
+
145
+ self.text_config = text_config
146
+
147
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
148
+
149
+
150
+ __all__ = ["LlavaNextConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava_next/convert_llava_next_weights_to_hf.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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
+ """Convert LLaVa-NeXT (LLaVa-1.6) checkpoints from the original repository.
16
+
17
+ URL: https://github.com/haotian-liu/LLaVA/tree/main.
18
+
19
+
20
+ The command used to obtain original logits is the following:
21
+ python llava/eval/run_llava.py --model-path "liuhaotian/llava-v1.6-mistral-7b" --image-file "images/llava_v1_5_radar.jpg" --query "What is shown in this image?" --max_new_tokens 100 --temperature 0
22
+
23
+ Note: logits are tested with torch==2.1.2.
24
+ """
25
+
26
+ import argparse
27
+ import gc
28
+ import glob
29
+ import json
30
+ from pathlib import Path
31
+
32
+ import requests
33
+ import torch
34
+ from accelerate import init_empty_weights
35
+ from huggingface_hub import hf_hub_download, snapshot_download
36
+ from PIL import Image
37
+ from safetensors import safe_open
38
+
39
+ from transformers import (
40
+ AddedToken,
41
+ AutoConfig,
42
+ AutoTokenizer,
43
+ LlavaNextConfig,
44
+ LlavaNextForConditionalGeneration,
45
+ LlavaNextImageProcessor,
46
+ LlavaNextProcessor,
47
+ )
48
+
49
+
50
+ KEYS_TO_MODIFY_MAPPING = {
51
+ "model.vision_tower.": "",
52
+ "model.mm_projector": "multi_modal_projector",
53
+ "model": "model.model",
54
+ "vision_model.model": "vision_model",
55
+ "lm_head": "language_model.lm_head",
56
+ "model.model": "language_model.model",
57
+ "multi_modal_projector.0": "multi_modal_projector.linear_1",
58
+ "multi_modal_projector.2": "multi_modal_projector.linear_2",
59
+ "language_model.model.image_newline": "image_newline",
60
+ }
61
+
62
+
63
+ def load_original_state_dict(model_id):
64
+ directory_path = snapshot_download(repo_id=model_id, allow_patterns=["*.safetensors"])
65
+
66
+ original_state_dict = {}
67
+ for path in glob.glob(f"{directory_path}/*"):
68
+ if path.endswith(".safetensors"):
69
+ with safe_open(path, framework="pt", device="cpu") as f:
70
+ for key in f.keys():
71
+ original_state_dict[key] = f.get_tensor(key)
72
+
73
+ return original_state_dict
74
+
75
+
76
+ def convert_state_dict_to_hf(state_dict):
77
+ new_state_dict = {}
78
+ for key, value in state_dict.items():
79
+ if key.endswith(".inv_freq"):
80
+ continue
81
+ for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
82
+ if key_to_modify in key:
83
+ key = key.replace(key_to_modify, new_key)
84
+
85
+ new_state_dict[key] = value.to(torch.float16)
86
+ return new_state_dict
87
+
88
+
89
+ def load_image():
90
+ url = "https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true"
91
+ image = Image.open(requests.get(url, stream=True).raw)
92
+ return image
93
+
94
+
95
+ def convert_llava_to_hf(model_id, pytorch_dump_folder_path, push_to_hub=False):
96
+ # load original config
97
+ filepath = hf_hub_download(repo_id=model_id, filename="config.json", repo_type="model")
98
+ # read json
99
+ with open(filepath) as f:
100
+ data = json.load(f)
101
+ print(data)
102
+
103
+ if model_id == "liuhaotian/llava-v1.6-mistral-7b":
104
+ text_model_id = "mistralai/Mistral-7B-Instruct-v0.2"
105
+ image_token_id = 32000
106
+ elif model_id == "liuhaotian/llava-v1.6-vicuna-7b":
107
+ text_model_id = "lmsys/vicuna-7b-v1.5"
108
+ image_token_id = 32000
109
+ elif model_id == "liuhaotian/llava-v1.6-vicuna-13b":
110
+ text_model_id = "lmsys/vicuna-13b-v1.5"
111
+ image_token_id = 32000
112
+ elif model_id == "liuhaotian/llava-v1.6-34b":
113
+ text_model_id = "NousResearch/Nous-Hermes-2-Yi-34B"
114
+ image_token_id = 64000
115
+ elif model_id == "lmms-lab/llama3-llava-next-8b":
116
+ text_model_id = "meta-llama/Meta-Llama-3-8B-Instruct"
117
+ image_token_id = 128256
118
+ elif model_id == "lmms-lab/llava-next-72b":
119
+ text_model_id = "Qwen/Qwen1.5-72B-Chat"
120
+ image_token_id = 151646
121
+ elif model_id == "lmms-lab/llava-next-110b":
122
+ text_model_id = "Qwen/Qwen1.5-110B-Chat"
123
+ image_token_id = 151646
124
+
125
+ vision_model_id = data["mm_vision_tower"]
126
+
127
+ torch.set_default_dtype(torch.float16)
128
+ text_config = AutoConfig.from_pretrained(text_model_id)
129
+
130
+ use_fast = model_id != "liuhaotian/llava-v1.6-34b"
131
+ tokenizer = AutoTokenizer.from_pretrained(text_model_id, use_fast=use_fast)
132
+ tokenizer.add_tokens(AddedToken("<image>", special=True, normalized=False), special_tokens=True)
133
+
134
+ if model_id in ("liuhaotian/llava-v1.6-mistral-7b", "lmms-lab/llama3-llava-next-8b"):
135
+ # Mistral-7B doesn't have a padding token set yet
136
+ tokenizer.add_special_tokens({"pad_token": "<pad>"})
137
+
138
+ image_processor = LlavaNextImageProcessor.from_pretrained(vision_model_id)
139
+ processor = LlavaNextProcessor(tokenizer=tokenizer, image_processor=image_processor)
140
+
141
+ config = LlavaNextConfig(
142
+ text_config=text_config.to_dict(),
143
+ image_grid_pinpoints=image_processor.image_grid_pinpoints,
144
+ use_image_newline_parameter=True,
145
+ image_token_id=image_token_id,
146
+ )
147
+
148
+ with init_empty_weights():
149
+ model = LlavaNextForConditionalGeneration(config)
150
+
151
+ # load original state dict
152
+ state_dict = load_original_state_dict(model_id)
153
+ state_dict = convert_state_dict_to_hf(state_dict)
154
+ model.load_state_dict(state_dict, assign=True)
155
+ model.eval()
156
+
157
+ pre_expansion_embeddings = model.language_model.model.embed_tokens.weight.data
158
+ mu = torch.mean(pre_expansion_embeddings, dim=0).float()
159
+ n = pre_expansion_embeddings.size()[0]
160
+ sigma = ((pre_expansion_embeddings - mu).T @ (pre_expansion_embeddings - mu)) / n
161
+ dist = torch.distributions.multivariate_normal.MultivariateNormal(mu, covariance_matrix=1e-5 * sigma)
162
+
163
+ # We add an image token so we resize the model
164
+ # Pad to 64 for performance reasons
165
+ # Qwen-based models have extra unused space in the vocab size already, so no need to resize
166
+ if model_id not in ["lmms-lab/llava-next-72b", "lmms-lab/llava-next-110b"]:
167
+ pad_shape = 64
168
+ vocab_size = config.text_config.vocab_size
169
+ if model_id == "liuhaotian/llava-v1.6-34b":
170
+ # this one has 3 additional tokens, namely <|startoftext|>, <|endoftext|> and <image>
171
+ num_tokens = vocab_size + 3
172
+ else:
173
+ # this one has 2 additional tokens, namely <image> and <pad>
174
+ num_tokens = vocab_size + 2
175
+ model.resize_token_embeddings(num_tokens, pad_to_multiple_of=pad_shape)
176
+ model.language_model.model.embed_tokens.weight.data[vocab_size:] = torch.stack(
177
+ tuple(
178
+ dist.sample() for _ in range(model.language_model.model.embed_tokens.weight.data[vocab_size:].shape[0])
179
+ ),
180
+ dim=0,
181
+ )
182
+ model.language_model.lm_head.weight.data[vocab_size:] = torch.stack(
183
+ tuple(dist.sample() for _ in range(model.language_model.lm_head.weight.data[vocab_size:].shape[0])),
184
+ dim=0,
185
+ )
186
+
187
+ print(f"Saving model and processor for {model_id} to {pytorch_dump_folder_path}")
188
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
189
+ model.save_pretrained(pytorch_dump_folder_path)
190
+ processor.save_pretrained(pytorch_dump_folder_path)
191
+
192
+ # Make space so we can load the model properly now.
193
+ del state_dict
194
+ gc.collect()
195
+
196
+ # Load everything back for inference tests in float32 because prev script was written as that
197
+ # Though it's mostly loaded in fp16 as original weights are in fp16
198
+ model = LlavaNextForConditionalGeneration.from_pretrained(pytorch_dump_folder_path, device_map="auto")
199
+ processor = LlavaNextProcessor.from_pretrained(pytorch_dump_folder_path)
200
+ device = model.device
201
+
202
+ # prepare inputs
203
+ image = load_image()
204
+ if model_id == "liuhaotian/llava-v1.6-mistral-7b":
205
+ prompt = "[INST] <image>\nWhat is shown in this image? [/INST]"
206
+ elif model_id in ["liuhaotian/llava-v1.6-vicuna-7b", "liuhaotian/llava-v1.6-vicuna-13b"]:
207
+ prompt = "A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions. USER: <image>\nWhat is shown in this image? ASSISTANT:"
208
+ elif model_id == "liuhaotian/llava-v1.6-34b":
209
+ prompt = "<|im_start|>system\nAnswer the questions.<|im_end|><|im_start|>user\n<image>\nWhat is shown in this image?<|im_end|><|im_start|>assistant\n"
210
+ elif model_id == "lmms-lab/llama3-llava-next-8b":
211
+ prompt = "<|start_header_id|>system<|end_header_id|>\n\nYou are a helpful language and vision assistant. You are able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language.<|eot_id|><|start_header_id|><|start_header_id|>user<|end_header_id|>\n\n<image>\nWhat is shown in this image?<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
212
+ elif model_id in ["lmms-lab/llava-next-72b", "lmms-lab/llava-next-110b"]:
213
+ prompt = "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<image>\nWhat is shown in this image?<|im_end|>\n<|im_start|>assistant\n"
214
+
215
+ inputs = processor(images=image, text=prompt, return_tensors="pt")
216
+
217
+ # verify inputs
218
+ filepath = hf_hub_download(repo_id="nielsr/test-image", filename="llava_1_6_pixel_values.pt", repo_type="dataset")
219
+ original_pixel_values = torch.load(filepath, map_location="cpu", weights_only=True)
220
+ assert torch.allclose(original_pixel_values, inputs.pixel_values.half())
221
+
222
+ if model_id == "liuhaotian/llava-v1.6-mistral-7b":
223
+ filepath = hf_hub_download(repo_id="nielsr/test-image", filename="llava_1_6_input_ids.pt", repo_type="dataset")
224
+ original_input_ids = torch.load(filepath, map_location="cpu", weights_only=True)
225
+ # replace -200 by image_token_id (since we use token ID = 32000 for the image token)
226
+ original_input_ids[original_input_ids == -200] = image_token_id
227
+ assert original_input_ids[0].tolist() == inputs.input_ids[0].tolist()
228
+
229
+ elif model_id == "liuhaotian/llava-v1.6-34b":
230
+ filepath = hf_hub_download(
231
+ repo_id="nielsr/test-image", filename="llava_1_6_34b_input_ids.pt", repo_type="dataset"
232
+ )
233
+ original_input_ids = torch.load(filepath, map_location="cpu", weights_only=True)
234
+ # replace -200 by image_token_id
235
+ original_input_ids[original_input_ids == -200] = image_token_id
236
+
237
+ assert original_input_ids[0].tolist() == inputs.input_ids[0].tolist()
238
+
239
+ image_sizes = torch.tensor([[899, 1024]])
240
+ assert image_sizes[0].tolist() == inputs.image_sizes[0].tolist()
241
+
242
+ # verify single forward pass
243
+ print("Single forward pass")
244
+ with torch.inference_mode():
245
+ inputs = inputs.to(device)
246
+ outputs = model(**inputs)
247
+ print("Shape of logits:", outputs.logits.shape)
248
+ print("First values of logits:", outputs.logits[0, :3, :3])
249
+
250
+ if model_id == "liuhaotian/llava-v1.6-mistral-7b":
251
+ expected_slice = torch.tensor(
252
+ [[-4.8555, -4.6992, -0.1996], [-10.5703, -10.7344, -2.7246], [-7.0391, -7.3672, -0.2634]],
253
+ dtype=torch.float32,
254
+ device=device,
255
+ )
256
+ elif model_id == "liuhaotian/llava-v1.6-vicuna-7b":
257
+ expected_slice = torch.tensor(
258
+ [[1.4883, 0.9976, -0.6992], [-9.7031, -5.7031, -1.5557], [-5.1328, -5.5586, 8.8281]],
259
+ dtype=torch.float32,
260
+ device=device,
261
+ )
262
+ elif model_id == "liuhaotian/llava-v1.6-vicuna-13b":
263
+ expected_slice = torch.tensor(
264
+ [[-0.9614, 7.3125, 0.2106], [-7.2695, -8.5469, 3.6211], [-6.3750, -8.1875, 5.4688]],
265
+ dtype=torch.float32,
266
+ device=device,
267
+ )
268
+ elif model_id == "liuhaotian/llava-v1.6-34b":
269
+ expected_slice = torch.tensor(
270
+ [[-9.0859, -9.1406, 5.9453], [-5.9570, -5.9766, 2.2754], [-5.7305, -5.7539, 4.0000]],
271
+ dtype=torch.float32,
272
+ device=device,
273
+ )
274
+ elif model_id == "lmms-lab/llama3-llava-next-8b":
275
+ expected_slice = torch.tensor(
276
+ [[-3.9648, 1.1396, 3.3145], [-5.3594, -1.5654, -1.9619], [-12.3750, -10.6797, -9.3125]],
277
+ dtype=torch.float32,
278
+ device=device,
279
+ )
280
+ elif model_id == "lmms-lab/llava-next-72b":
281
+ # Not yet checked against reference
282
+ expected_slice = torch.tensor(
283
+ [[3.7148, 3.9277, 3.4395], [-0.4341, 1.1387, 6.5117], [3.2324, 3.4688, 4.1133]],
284
+ dtype=torch.float32,
285
+ device=device,
286
+ )
287
+ elif model_id == "lmms-lab/llava-next-110b":
288
+ # Not yet checked against reference
289
+ expected_slice = torch.tensor(
290
+ [[-2.5449, -1.6738, -2.0371], [1.0811, 3.4961, 5.0312], [1.7803, 2.5137, 2.4277]],
291
+ dtype=torch.float32,
292
+ device=device,
293
+ )
294
+ else:
295
+ raise ValueError(f"Model {model_id} not supported")
296
+
297
+ assert torch.allclose(outputs.logits[0, :3, :3], expected_slice, atol=1e-4)
298
+ print("Logits are ok!")
299
+
300
+ # verify generation
301
+ output_ids = model.generate(
302
+ **inputs,
303
+ max_new_tokens=100,
304
+ use_cache=True,
305
+ )
306
+
307
+ generated_text = processor.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
308
+
309
+ print("Generated text:", repr(generated_text))
310
+
311
+ if model_id == "liuhaotian/llava-v1.6-mistral-7b":
312
+ expected_text = '[INST] \nWhat is shown in this image? [/INST] The image appears to be a radar chart, which is a type of multi-dimensional plot that displays data in the form of a two-dimensional chart of three or more quantitative variables represented on axes starting from the same point.\n\nIn this particular radar chart, there are several axes labeled with different metrics or benchmarks, such as "MMM-Vet," "MMM-Bench," "LLaVA-Bench," "SLED-Bench," "'
313
+ elif model_id == "liuhaotian/llava-v1.6-vicuna-7b":
314
+ expected_text = """A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human\'s questions. USER: \nWhat is shown in this image? ASSISTANT: The image appears to be a graphical representation of a benchmarking study comparing the performance of various models or systems. It\'s a scatter plot with a circular layout, where each point represents a different model or system, and the axes represent different metrics or dimensions of comparison.\n\nThe metrics are likely related to machine learning or artificial intelligence performance, as indicated by the terms like "BLIP-2," "Instruct BLIP," "POE," "QWA," "V"""
315
+ elif model_id == "liuhaotian/llava-v1.6-vicuna-13b":
316
+ expected_text = "A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions. USER: \nWhat is shown in this image? ASSISTANT: The image appears to be a radar chart, also known as a spider chart or star chart, which is a graphical method of displaying multivariate data in the form of a two-dimensional chart of three or more quantitative variables represented on axes starting from the same point.\n\nIn this particular radar chart, there are several variables represented:\n\n- MM-Vet\n- LLa-Va-Bench\n- SEED-Bench\n- MM"
317
+ elif model_id == "liuhaotian/llava-v1.6-34b":
318
+ expected_text = "<|im_start|> system\nAnswer the questions. <|im_start|> user\n\nWhat is shown in this image? <|im_start|> assistant\nThe image appears to be a radar chart, also known as a spider chart, which is a graphical method of displaying multivariate data in the form of a two-dimensional chart of three or more quantitative variables represented on axes starting from the same point.\n\nIn this particular chart, there are several datasets represented by different colors and labeled with various acronyms such as MM-Vet, LLaVA-Bench, SEED-Bench, MM-Bench-CN, MM-"
319
+ elif model_id == "lmms-lab/llama3-llava-next-8b":
320
+ expected_text = 'system\n\nYou are a helpful language and vision assistant. You are able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language.user\n\n\nWhat is shown in this image?assistant\n\n\nThe image shows a radar chart, also known as a spider chart or a web chart, which is a type of graph used to display multivariate data in the form of a two-dimensional chart of three or more quantitative variables represented on axes starting from the same point. Each axis represents a different variable, and the values are plotted along each axis and connected to form a polygon.\n\nIn this particular radar chart, there are several axes labeled with different variables, such as "MM-Vet," "LL'
321
+ elif model_id == "lmms-lab/llava-next-72b":
322
+ expected_text = "system\nYou are a helpful assistant.\nuser\n\nWhat is shown in this image?\nassistant\nThe image displays a radar chart, also known as a spider chart or a star chart, which is a graphical method of displaying multivariate data in the form of a two-dimensional chart of three or more quantitative variables represented on axes starting from the same point. Each axis represents a different variable, and the value of each variable is represented by the distance from the center of the chart to the point where the axis intersects with the line representing that variable's value.\n\nIn this particular chart, there are several axes"
323
+ elif model_id == "lmms-lab/llava-next-110b":
324
+ expected_text = "system\nYou are a helpful assistant.\nuser\n\nWhat is shown in this image?\nassistant\nThe image shows a radar chart comparing the performance of different models on various visual question answering (VQA) benchmarks. Each colored line represents a different model, and the distance from the center of the chart indicates the score or performance level of the model on a particular benchmark. The benchmarks are labeled around the edges of the chart, and include VQA v2, GQA, VizWiz, TextVQA, MMBench-CN, MME, and others. The chart allows for a"
325
+ else:
326
+ raise ValueError(f"Model {model_id} not supported")
327
+
328
+ assert generated_text == expected_text
329
+ print("Generated text is ok!")
330
+
331
+ # verify batched generation
332
+ print("Batched generation...")
333
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
334
+ cats_image = Image.open(requests.get(url, stream=True).raw)
335
+
336
+ inputs = processor(
337
+ images=[image, cats_image],
338
+ text=[prompt, prompt],
339
+ padding=True,
340
+ return_tensors="pt",
341
+ ).to(device)
342
+
343
+ for k, v in inputs.items():
344
+ print(k, v.shape)
345
+
346
+ print("Image sizes:", inputs.image_sizes)
347
+
348
+ # make sure image_sizes are the same
349
+ # as otherwise batched generation doesn't work
350
+ inputs.image_sizes[1] = inputs.image_sizes[0]
351
+
352
+ print("Batched generation...")
353
+ output_ids = model.generate(
354
+ **inputs,
355
+ max_new_tokens=20,
356
+ use_cache=True,
357
+ )
358
+
359
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
360
+ print(outputs)
361
+
362
+ if push_to_hub:
363
+ checkpoint_name = model_id.split("/")[-1]
364
+ print(f"Pushing to repo llava-hf/{checkpoint_name}-hf")
365
+ model.push_to_hub(f"llava-hf/{checkpoint_name}-hf")
366
+ processor.push_to_hub(f"llava-hf/{checkpoint_name}-hf")
367
+
368
+
369
+ if __name__ == "__main__":
370
+ parser = argparse.ArgumentParser()
371
+ parser.add_argument(
372
+ "--model_id",
373
+ help="Hub location of the model to convert",
374
+ default="liuhaotian/llava-v1.6-mistral-7b",
375
+ choices=[
376
+ "liuhaotian/llava-v1.6-mistral-7b",
377
+ "liuhaotian/llava-v1.6-vicuna-7b",
378
+ "liuhaotian/llava-v1.6-vicuna-13b",
379
+ "liuhaotian/llava-v1.6-34b",
380
+ "lmms-lab/llama3-llava-next-8b",
381
+ "lmms-lab/llava-next-72b",
382
+ "lmms-lab/llava-next-110b",
383
+ ],
384
+ required=False,
385
+ )
386
+ parser.add_argument(
387
+ "--pytorch_dump_folder_path", type=str, required=True, help="Path to the output PyTorch model directory."
388
+ )
389
+ parser.add_argument(
390
+ "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
391
+ )
392
+ args = parser.parse_args()
393
+
394
+ convert_llava_to_hf(args.model_id, args.pytorch_dump_folder_path, args.push_to_hub)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava_next/image_processing_llava_next.py ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Image processor class for LLaVa-NeXT."""
16
+
17
+ from collections.abc import Iterable
18
+ from typing import Optional, Union
19
+
20
+ import numpy as np
21
+
22
+ from ...image_processing_utils import (
23
+ BaseImageProcessor,
24
+ BatchFeature,
25
+ get_patch_output_size,
26
+ get_size_dict,
27
+ select_best_resolution,
28
+ )
29
+ from ...image_transforms import (
30
+ PaddingMode,
31
+ convert_to_rgb,
32
+ get_resize_output_image_size,
33
+ pad,
34
+ resize,
35
+ to_channel_dimension_format,
36
+ )
37
+ from ...image_utils import (
38
+ OPENAI_CLIP_MEAN,
39
+ OPENAI_CLIP_STD,
40
+ ChannelDimension,
41
+ ImageInput,
42
+ PILImageResampling,
43
+ get_image_size,
44
+ infer_channel_dimension_format,
45
+ is_scaled_image,
46
+ make_flat_list_of_images,
47
+ make_list_of_images,
48
+ to_numpy_array,
49
+ valid_images,
50
+ validate_preprocess_arguments,
51
+ )
52
+ from ...utils import TensorType, is_vision_available, logging
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+
58
+ if is_vision_available():
59
+ from PIL import Image
60
+
61
+
62
+ def divide_to_patches(image: np.array, patch_size: int, input_data_format) -> list[np.array]:
63
+ """
64
+ Divides an image into patches of a specified size.
65
+
66
+ Args:
67
+ image (`np.array`):
68
+ The input image.
69
+ patch_size (`int`):
70
+ The size of each patch.
71
+ input_data_format (`ChannelDimension` or `str`):
72
+ The channel dimension format of the input image.
73
+
74
+ Returns:
75
+ list: A list of np.array representing the patches.
76
+ """
77
+ patches = []
78
+ height, width = get_image_size(image, channel_dim=input_data_format)
79
+ for i in range(0, height, patch_size):
80
+ for j in range(0, width, patch_size):
81
+ if input_data_format == ChannelDimension.LAST:
82
+ patch = image[i : i + patch_size, j : j + patch_size]
83
+ else:
84
+ patch = image[:, i : i + patch_size, j : j + patch_size]
85
+ patches.append(patch)
86
+
87
+ return patches
88
+
89
+
90
+ def expand_to_square(image: np.array, background_color, input_data_format) -> np.array:
91
+ """
92
+ Expands an image to a square by adding a background color.
93
+ """
94
+
95
+ height, width = get_image_size(image, channel_dim=input_data_format)
96
+ if width == height:
97
+ return image
98
+ elif width > height:
99
+ result = np.ones((width, width, image.shape[2]), dtype=image.dtype) * background_color
100
+ result[(width - height) // 2 : (width - height) // 2 + height, :] = image
101
+ return result
102
+ else:
103
+ result = np.ones((height, height, image.shape[2]), dtype=image.dtype) * background_color
104
+ result[:, (height - width) // 2 : (height - width) // 2 + width] = image
105
+ return result
106
+
107
+
108
+ class LlavaNextImageProcessor(BaseImageProcessor):
109
+ r"""
110
+ Constructs a LLaVa-NeXT image processor. Based on [`CLIPImageProcessor`] with incorporation of additional techniques
111
+ for processing high resolution images as explained in the [LLaVa paper](https://huggingface.co/papers/2310.03744).
112
+
113
+ Args:
114
+ do_resize (`bool`, *optional*, defaults to `True`):
115
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
116
+ `do_resize` in the `preprocess` method.
117
+ size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
118
+ Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
119
+ the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
120
+ method.
121
+ image_grid_pinpoints (`List` *optional*, defaults to `[[672, 336], [336, 672], [672, 672], [336, 1008], [1008, 336]]`):
122
+ A list of possible resolutions to use for processing high resolution images. The best resolution is selected
123
+ based on the original size of the image. Can be overridden by `image_grid_pinpoints` in the `preprocess`
124
+ method.
125
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
126
+ Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
127
+ do_center_crop (`bool`, *optional*, defaults to `True`):
128
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
129
+ `preprocess` method.
130
+ crop_size (`dict[str, int]` *optional*, defaults to 224):
131
+ Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
132
+ method.
133
+ do_rescale (`bool`, *optional*, defaults to `True`):
134
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
135
+ the `preprocess` method.
136
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
137
+ Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
138
+ method.
139
+ do_normalize (`bool`, *optional*, defaults to `True`):
140
+ Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
141
+ image_mean (`float` or `list[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
142
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
143
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
144
+ image_std (`float` or `list[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
145
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
146
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
147
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
148
+ do_pad (`bool`, *optional*, defaults to `True`):
149
+ Whether to pad the image. If `True`, will pad the patch dimension of the images in the batch to the largest
150
+ number of patches in the batch. Padding will be applied to the bottom and right with zeros.
151
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
152
+ Whether to convert the image to RGB.
153
+ """
154
+
155
+ model_input_names = ["pixel_values", "image_sizes"]
156
+
157
+ def __init__(
158
+ self,
159
+ do_resize: bool = True,
160
+ size: Optional[dict[str, int]] = None,
161
+ image_grid_pinpoints: Optional[list] = None,
162
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
163
+ do_center_crop: bool = True,
164
+ crop_size: Optional[dict[str, int]] = None,
165
+ do_rescale: bool = True,
166
+ rescale_factor: Union[int, float] = 1 / 255,
167
+ do_normalize: bool = True,
168
+ image_mean: Optional[Union[float, list[float]]] = None,
169
+ image_std: Optional[Union[float, list[float]]] = None,
170
+ do_pad: Optional[bool] = True,
171
+ do_convert_rgb: bool = True,
172
+ **kwargs,
173
+ ) -> None:
174
+ super().__init__(**kwargs)
175
+ size = size if size is not None else {"shortest_edge": 224}
176
+ size = get_size_dict(size, default_to_square=False)
177
+ image_grid_pinpoints = (
178
+ image_grid_pinpoints
179
+ if image_grid_pinpoints is not None
180
+ else [[336, 672], [672, 336], [672, 672], [1008, 336], [336, 1008]]
181
+ )
182
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
183
+ crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
184
+
185
+ self.do_resize = do_resize
186
+ self.size = size
187
+ self.image_grid_pinpoints = image_grid_pinpoints
188
+ self.resample = resample
189
+ self.do_center_crop = do_center_crop
190
+ self.crop_size = crop_size
191
+ self.do_rescale = do_rescale
192
+ self.rescale_factor = rescale_factor
193
+ self.do_normalize = do_normalize
194
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
195
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
196
+ self.do_pad = do_pad
197
+ self.do_convert_rgb = do_convert_rgb
198
+
199
+ # Copied from transformers.models.clip.image_processing_clip.CLIPImageProcessor.resize with CLIP->LLaVa
200
+ def resize(
201
+ self,
202
+ image: np.ndarray,
203
+ size: dict[str, int],
204
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
205
+ data_format: Optional[Union[str, ChannelDimension]] = None,
206
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
207
+ **kwargs,
208
+ ) -> np.ndarray:
209
+ """
210
+ Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
211
+ resized to keep the input aspect ratio.
212
+
213
+ Args:
214
+ image (`np.ndarray`):
215
+ Image to resize.
216
+ size (`dict[str, int]`):
217
+ Size of the output image.
218
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
219
+ Resampling filter to use when resiizing the image.
220
+ data_format (`str` or `ChannelDimension`, *optional*):
221
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
222
+ input_data_format (`ChannelDimension` or `str`, *optional*):
223
+ The channel dimension format of the input image. If not provided, it will be inferred.
224
+ """
225
+ default_to_square = True
226
+ if "shortest_edge" in size:
227
+ size = size["shortest_edge"]
228
+ default_to_square = False
229
+ elif "height" in size and "width" in size:
230
+ size = (size["height"], size["width"])
231
+ else:
232
+ raise ValueError("Size must contain either 'shortest_edge' or 'height' and 'width'.")
233
+
234
+ output_size = get_resize_output_image_size(
235
+ image,
236
+ size=size,
237
+ default_to_square=default_to_square,
238
+ input_data_format=input_data_format,
239
+ )
240
+
241
+ return resize(
242
+ image,
243
+ size=output_size,
244
+ resample=resample,
245
+ data_format=data_format,
246
+ input_data_format=input_data_format,
247
+ **kwargs,
248
+ )
249
+
250
+ def pad(
251
+ self,
252
+ image: np.ndarray,
253
+ padding: Union[int, tuple[int, int], Iterable[tuple[int, int]]],
254
+ mode: PaddingMode = PaddingMode.CONSTANT,
255
+ constant_values: Union[float, Iterable[float]] = 0.0,
256
+ data_format: Optional[Union[str, ChannelDimension]] = None,
257
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
258
+ ) -> np.ndarray:
259
+ """
260
+ Pads the `image` with the specified `padding` and `mode`. Padding can be in the (`height`, `width`)
261
+ dimension of in the (`num_patches`) dimension. In the second case an iterable if tuples is expected
262
+ as input.
263
+
264
+ Args:
265
+ image (`np.ndarray`):
266
+ The image to pad.
267
+ padding (`int` or `tuple[int, int]` or `Iterable[tuple[int, int]]`):
268
+ Padding to apply to the edges of the height, width axes. Can be one of three formats:
269
+ - `((before_height, after_height), (before_width, after_width))` unique pad widths for each axis.
270
+ - `((before, after),)` yields same before and after pad for height and width.
271
+ - `(pad,)` or int is a shortcut for before = after = pad width for all axes.
272
+ mode (`PaddingMode`):
273
+ The padding mode to use. Can be one of:
274
+ - `"constant"`: pads with a constant value.
275
+ - `"reflect"`: pads with the reflection of the vector mirrored on the first and last values of the
276
+ vector along each axis.
277
+ - `"replicate"`: pads with the replication of the last value on the edge of the array along each axis.
278
+ - `"symmetric"`: pads with the reflection of the vector mirrored along the edge of the array.
279
+ constant_values (`float` or `Iterable[float]`, *optional*):
280
+ The value to use for the padding if `mode` is `"constant"`.
281
+ data_format (`str` or `ChannelDimension`, *optional*):
282
+ The channel dimension format for the output image. Can be one of:
283
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
284
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
285
+ If unset, will use same as the input image.
286
+ input_data_format (`str` or `ChannelDimension`, *optional*):
287
+ The channel dimension format for the input image. Can be one of:
288
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
289
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
290
+ If unset, will use the inferred format of the input image.
291
+
292
+ Returns:
293
+ `np.ndarray`: The padded image.
294
+
295
+ """
296
+
297
+ # call the general `pad` if padding on `height/width`, otherwise it's the `num_patched` dim
298
+ if isinstance(padding, int) or len(padding) != 4:
299
+ return pad(image, padding, mode, constant_values, data_format, input_data_format)
300
+
301
+ if input_data_format is None:
302
+ input_data_format = infer_channel_dimension_format(image)
303
+ if mode == PaddingMode.CONSTANT:
304
+ image = np.pad(image, padding, mode="constant", constant_values=constant_values)
305
+ elif mode == PaddingMode.REFLECT:
306
+ image = np.pad(image, padding, mode="reflect")
307
+ elif mode == PaddingMode.REPLICATE:
308
+ image = np.pad(image, padding, mode="edge")
309
+ elif mode == PaddingMode.SYMMETRIC:
310
+ image = np.pad(image, padding, mode="symmetric")
311
+ else:
312
+ raise ValueError(f"Invalid padding mode: {mode}")
313
+ image = (
314
+ to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image
315
+ )
316
+ return image
317
+
318
+ def _preprocess(
319
+ self,
320
+ images: ImageInput,
321
+ do_resize: Optional[bool] = None,
322
+ size: Optional[dict[str, int]] = None,
323
+ resample: PILImageResampling = None,
324
+ do_center_crop: Optional[bool] = None,
325
+ crop_size: Optional[int] = None,
326
+ do_rescale: Optional[bool] = None,
327
+ rescale_factor: Optional[float] = None,
328
+ do_normalize: Optional[bool] = None,
329
+ image_mean: Optional[Union[float, list[float]]] = None,
330
+ image_std: Optional[Union[float, list[float]]] = None,
331
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
332
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
333
+ ) -> Image.Image:
334
+ """
335
+ Preprocess an image or batch of images. Copy of the `preprocess` method from `CLIPImageProcessor`.
336
+
337
+ Args:
338
+ images (`ImageInput`):
339
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
340
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
341
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
342
+ Whether to resize the image.
343
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
344
+ Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
345
+ the longest edge resized to keep the input aspect ratio.
346
+ resample (`int`, *optional*, defaults to `self.resample`):
347
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
348
+ has an effect if `do_resize` is set to `True`.
349
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
350
+ Whether to center crop the image.
351
+ crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`):
352
+ Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
353
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
354
+ Whether to rescale the image.
355
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
356
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
357
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
358
+ Whether to normalize the image.
359
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
360
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
361
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
362
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
363
+ `True`.
364
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
365
+ The channel dimension format for the output image. Can be one of:
366
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
367
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
368
+ - Unset: Use the channel dimension format of the input image.
369
+ input_data_format (`ChannelDimension` or `str`, *optional*):
370
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
371
+ from the input image. Can be one of:
372
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
373
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
374
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
375
+ """
376
+ images = make_list_of_images(images)
377
+
378
+ all_images = []
379
+ for image in images:
380
+ if do_resize:
381
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
382
+
383
+ if do_center_crop:
384
+ image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
385
+
386
+ if do_rescale:
387
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
388
+
389
+ if do_normalize:
390
+ image = self.normalize(
391
+ image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
392
+ )
393
+
394
+ all_images.append(image)
395
+ images = [
396
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
397
+ for image in all_images
398
+ ]
399
+
400
+ return images
401
+
402
+ def _resize_for_patching(
403
+ self, image: np.array, target_resolution: tuple, resample, input_data_format: ChannelDimension
404
+ ) -> np.array:
405
+ """
406
+ Resizes an image to a target resolution while maintaining aspect ratio.
407
+
408
+ Args:
409
+ image (np.array):
410
+ The input image.
411
+ target_resolution (tuple):
412
+ The target resolution (height, width) of the image.
413
+ resample (`PILImageResampling`):
414
+ Resampling filter to use if resizing the image.
415
+ input_data_format (`ChannelDimension` or `str`):
416
+ The channel dimension format of the input image.
417
+
418
+ Returns:
419
+ np.array: The resized and padded image.
420
+ """
421
+ new_height, new_width = get_patch_output_size(image, target_resolution, input_data_format)
422
+
423
+ # Resize the image
424
+ resized_image = resize(image, (new_height, new_width), resample=resample, input_data_format=input_data_format)
425
+
426
+ return resized_image
427
+
428
+ def _get_padding_size(self, original_resolution: tuple, target_resolution: tuple):
429
+ original_height, original_width = original_resolution
430
+ target_height, target_width = target_resolution
431
+ paste_x, r_x = divmod(target_width - original_width, 2)
432
+ paste_y, r_y = divmod(target_height - original_height, 2)
433
+ return (paste_y, paste_y + r_y), (paste_x, paste_x + r_x)
434
+
435
+ def _pad_for_patching(
436
+ self, image: np.array, target_resolution: tuple, input_data_format: ChannelDimension
437
+ ) -> np.array:
438
+ """
439
+ Pad an image to a target resolution while maintaining aspect ratio.
440
+ """
441
+ new_resolution = get_patch_output_size(image, target_resolution, input_data_format)
442
+ padding = self._get_padding_size(new_resolution, target_resolution)
443
+
444
+ padded_image = self.pad(image, padding=padding)
445
+
446
+ return padded_image
447
+
448
+ def get_image_patches(
449
+ self,
450
+ image: np.array,
451
+ grid_pinpoints,
452
+ size: tuple,
453
+ patch_size: int,
454
+ resample: PILImageResampling,
455
+ data_format: ChannelDimension,
456
+ input_data_format: ChannelDimension,
457
+ ) -> list[np.array]:
458
+ """
459
+ Process an image with variable resolutions by dividing it into patches.
460
+
461
+ Args:
462
+ image (np.array):
463
+ The input image to be processed.
464
+ grid_pinpoints (List):
465
+ A string representation of a list of possible resolutions.
466
+ size (`tuple`):
467
+ Size to resize the original image to.
468
+ patch_size (`int`):
469
+ Size of the patches to divide the image into.
470
+ resample (`PILImageResampling`):
471
+ Resampling filter to use if resizing the image.
472
+ data_format (`ChannelDimension` or `str`):
473
+ The channel dimension format for the output image.
474
+ input_data_format (`ChannelDimension` or `str`):
475
+ The channel dimension format of the input image.
476
+
477
+ Returns:
478
+ list[np.array]: A list of NumPy arrays containing the processed image patches.
479
+ """
480
+ if not isinstance(grid_pinpoints, list):
481
+ raise TypeError("grid_pinpoints must be a list of possible resolutions.")
482
+
483
+ possible_resolutions = grid_pinpoints
484
+
485
+ image_size = get_image_size(image, channel_dim=input_data_format)
486
+ best_resolution = select_best_resolution(image_size, possible_resolutions)
487
+ resized_image = self._resize_for_patching(
488
+ image, best_resolution, resample=resample, input_data_format=input_data_format
489
+ )
490
+ padded_image = self._pad_for_patching(resized_image, best_resolution, input_data_format=input_data_format)
491
+
492
+ patches = divide_to_patches(padded_image, patch_size=patch_size, input_data_format=input_data_format)
493
+
494
+ # make sure that all patches are in the input data format
495
+ patches = [
496
+ to_channel_dimension_format(patch, channel_dim=data_format, input_channel_dim=input_data_format)
497
+ for patch in patches
498
+ ]
499
+
500
+ resized_original_image = resize(
501
+ image,
502
+ size=size,
503
+ resample=resample,
504
+ data_format=data_format,
505
+ input_data_format=input_data_format,
506
+ )
507
+
508
+ image_patches = [resized_original_image] + patches
509
+
510
+ return image_patches
511
+
512
+ def _pad_for_batching(
513
+ self,
514
+ pixel_values: list[np.ndarray],
515
+ data_format: Optional[Union[str, ChannelDimension]] = None,
516
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
517
+ ):
518
+ """
519
+ Pads images on the `num_of_patches` dimension with zeros to form a batch of same number of patches.
520
+
521
+ Args:
522
+ pixel_values (`list[np.ndarray]`):
523
+ An array of pixel values of each images of shape (`batch_size`, `num_patches`, `image_in_3D`)
524
+ data_format (`str` or `ChannelDimension`, *optional*):
525
+ The channel dimension format for the output image. Can be one of:
526
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
527
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
528
+ If unset, will use same as the input image.
529
+ input_data_format (`str` or `ChannelDimension`, *optional*):
530
+ The channel dimension format for the input image. Can be one of:
531
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
532
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
533
+ If unset, will use the inferred format of the input image.
534
+
535
+ Returns:
536
+ list[`np.ndarray`]: The padded images.
537
+ """
538
+ max_patch = max(len(x) for x in pixel_values)
539
+ pixel_values = [
540
+ self.pad(
541
+ image,
542
+ padding=((0, max_patch - image.shape[0]), (0, 0), (0, 0), (0, 0)),
543
+ data_format=data_format,
544
+ input_data_format=input_data_format,
545
+ )
546
+ for image in pixel_values
547
+ ]
548
+
549
+ return pixel_values
550
+
551
+ def preprocess(
552
+ self,
553
+ images: ImageInput,
554
+ do_resize: Optional[bool] = None,
555
+ size: Optional[dict[str, int]] = None,
556
+ image_grid_pinpoints: Optional[list] = None,
557
+ resample: PILImageResampling = None,
558
+ do_center_crop: Optional[bool] = None,
559
+ crop_size: Optional[int] = None,
560
+ do_rescale: Optional[bool] = None,
561
+ rescale_factor: Optional[float] = None,
562
+ do_normalize: Optional[bool] = None,
563
+ image_mean: Optional[Union[float, list[float]]] = None,
564
+ image_std: Optional[Union[float, list[float]]] = None,
565
+ do_pad: Optional[bool] = None,
566
+ do_convert_rgb: Optional[bool] = None,
567
+ return_tensors: Optional[Union[str, TensorType]] = None,
568
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
569
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
570
+ ):
571
+ """
572
+ Args:
573
+ images (`ImageInput`):
574
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
575
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
576
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
577
+ Whether to resize the image.
578
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
579
+ Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
580
+ the longest edge resized to keep the input aspect ratio.
581
+ image_grid_pinpoints (`List` *optional*, defaults to `self.image_grid_pinpoints`):
582
+ A list of possible resolutions to use for processing high resolution images. The best resolution is
583
+ selected based on the original size of the image.
584
+ resample (`int`, *optional*, defaults to `self.resample`):
585
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
586
+ has an effect if `do_resize` is set to `True`.
587
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
588
+ Whether to center crop the image.
589
+ crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`):
590
+ Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
591
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
592
+ Whether to rescale the image.
593
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
594
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
595
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
596
+ Whether to normalize the image.
597
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
598
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
599
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
600
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
601
+ `True`.
602
+ do_pad (`bool`, *optional*, defaults to `self.do_pad`):
603
+ Whether to pad the image. If `True`, will pad the patch dimension of the images in the batch to the largest
604
+ number of patches in the batch. Padding will be applied to the bottom and right with zeros.
605
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
606
+ Whether to convert the image to RGB.
607
+ return_tensors (`str` or `TensorType`, *optional*):
608
+ The type of tensors to return. Can be one of:
609
+ - Unset: Return a list of `np.ndarray`.
610
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
611
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
612
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
613
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
614
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
615
+ The channel dimension format for the output image. Can be one of:
616
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
617
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
618
+ - Unset: Use the channel dimension format of the input image.
619
+ input_data_format (`ChannelDimension` or `str`, *optional*):
620
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
621
+ from the input image. Can be one of:
622
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
623
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
624
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
625
+
626
+ """
627
+ do_resize = do_resize if do_resize is not None else self.do_resize
628
+ size = size if size is not None else self.size
629
+ size = get_size_dict(size, param_name="size", default_to_square=False)
630
+ image_grid_pinpoints = image_grid_pinpoints if image_grid_pinpoints is not None else self.image_grid_pinpoints
631
+ resample = resample if resample is not None else self.resample
632
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
633
+ crop_size = crop_size if crop_size is not None else self.crop_size
634
+ crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
635
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
636
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
637
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
638
+ image_mean = image_mean if image_mean is not None else self.image_mean
639
+ image_std = image_std if image_std is not None else self.image_std
640
+ do_pad = do_pad if do_pad is not None else self.do_pad
641
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
642
+
643
+ images = make_flat_list_of_images(images)
644
+
645
+ if not valid_images(images):
646
+ raise ValueError(
647
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
648
+ "torch.Tensor, tf.Tensor or jax.ndarray."
649
+ )
650
+
651
+ validate_preprocess_arguments(
652
+ do_rescale=do_rescale,
653
+ rescale_factor=rescale_factor,
654
+ do_normalize=do_normalize,
655
+ image_mean=image_mean,
656
+ image_std=image_std,
657
+ do_center_crop=do_center_crop,
658
+ crop_size=crop_size,
659
+ do_resize=do_resize,
660
+ size=size,
661
+ resample=resample,
662
+ )
663
+
664
+ if do_convert_rgb:
665
+ images = [convert_to_rgb(image) for image in images]
666
+
667
+ # All transformations expect numpy arrays.
668
+ images = [to_numpy_array(image) for image in images]
669
+
670
+ if do_rescale and is_scaled_image(images[0]):
671
+ logger.warning_once(
672
+ "It looks like you are trying to rescale already rescaled images. If the input"
673
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
674
+ )
675
+
676
+ if input_data_format is None:
677
+ # We assume that all images have the same channel dimension format.
678
+ input_data_format = infer_channel_dimension_format(images[0])
679
+
680
+ new_images = []
681
+ image_sizes = [get_image_size(image, channel_dim=input_data_format) for image in images]
682
+ for image in images:
683
+ # convert image into a list of patches
684
+ # we intentionally use the same data format as the input data format
685
+ image_patches = self.get_image_patches(
686
+ image,
687
+ image_grid_pinpoints,
688
+ size=(size["shortest_edge"], size["shortest_edge"])
689
+ if "shortest_edge" in size
690
+ else (min(size["height"], size["width"]), min(size["height"], size["width"])),
691
+ patch_size=crop_size["height"],
692
+ resample=resample,
693
+ data_format=input_data_format,
694
+ input_data_format=input_data_format,
695
+ )
696
+
697
+ # preprocess patches
698
+ pixel_values = self._preprocess(
699
+ image_patches,
700
+ do_resize=do_resize,
701
+ size=size,
702
+ resample=resample,
703
+ do_center_crop=do_center_crop,
704
+ crop_size=crop_size,
705
+ do_rescale=do_rescale,
706
+ rescale_factor=rescale_factor,
707
+ do_normalize=do_normalize,
708
+ image_mean=image_mean,
709
+ image_std=image_std,
710
+ data_format=data_format,
711
+ input_data_format=input_data_format,
712
+ )
713
+ pixel_values = np.array(pixel_values)
714
+ new_images.append(pixel_values)
715
+
716
+ if do_pad:
717
+ processed_images = self._pad_for_batching(new_images)
718
+
719
+ return BatchFeature(
720
+ data={"pixel_values": processed_images, "image_sizes": image_sizes}, tensor_type=return_tensors
721
+ )
722
+
723
+
724
+ __all__ = ["LlavaNextImageProcessor"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava_next/image_processing_llava_next_fast.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Fast Image processor class for LLaVa-NeXT."""
16
+
17
+ from typing import Optional, Union
18
+
19
+ from ...image_processing_utils import BatchFeature, get_patch_output_size, select_best_resolution
20
+ from ...image_processing_utils_fast import (
21
+ BaseImageProcessorFast,
22
+ DefaultFastImageProcessorKwargs,
23
+ divide_to_patches,
24
+ group_images_by_shape,
25
+ reorder_images,
26
+ )
27
+ from ...image_utils import (
28
+ OPENAI_CLIP_MEAN,
29
+ OPENAI_CLIP_STD,
30
+ ChannelDimension,
31
+ ImageInput,
32
+ PILImageResampling,
33
+ SizeDict,
34
+ get_image_size,
35
+ )
36
+ from ...processing_utils import Unpack
37
+ from ...utils import (
38
+ TensorType,
39
+ auto_docstring,
40
+ is_torch_available,
41
+ is_torchvision_available,
42
+ is_torchvision_v2_available,
43
+ )
44
+
45
+
46
+ if is_torch_available():
47
+ import torch
48
+
49
+ if is_torchvision_available():
50
+ if is_torchvision_v2_available():
51
+ from torchvision.transforms.v2 import functional as F
52
+ else:
53
+ from torchvision.transforms import functional as F
54
+
55
+
56
+ class LlavaNextFastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
57
+ """
58
+ image_grid_pinpoints (`list[list[int]]`, *optional*):
59
+ A list of possible resolutions to use for processing high resolution images. The best resolution is selected
60
+ based on the original size of the image. Can be overridden by `image_grid_pinpoints` in the `preprocess`
61
+ method.
62
+ do_pad (`bool`, *optional*):
63
+ Whether to pad the image. If `True`, will pad the patch dimension of the images in the batch to the largest
64
+ number of patches in the batch. Padding will be applied to the bottom and right with zeros.
65
+ """
66
+
67
+ image_grid_pinpoints: Optional[list[list[int]]]
68
+ do_pad: Optional[bool]
69
+
70
+
71
+ @auto_docstring
72
+ class LlavaNextImageProcessorFast(BaseImageProcessorFast):
73
+ # To be checked against the slow image processor
74
+ # None values left after checking can be removed
75
+ resample = PILImageResampling.BICUBIC
76
+ image_mean = OPENAI_CLIP_MEAN
77
+ image_std = OPENAI_CLIP_STD
78
+ size = {"shortest_edge": 224}
79
+ default_to_square = False
80
+ crop_size = {"height": 224, "width": 224}
81
+ do_resize = True
82
+ do_center_crop = True
83
+ do_rescale = True
84
+ do_normalize = True
85
+ do_convert_rgb = True
86
+ do_pad = True
87
+ image_grid_pinpoints = [[336, 672], [672, 336], [672, 672], [1008, 336], [336, 1008]]
88
+ valid_kwargs = LlavaNextFastImageProcessorKwargs
89
+
90
+ def __init__(self, **kwargs: Unpack[LlavaNextFastImageProcessorKwargs]):
91
+ super().__init__(**kwargs)
92
+
93
+ @auto_docstring
94
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[LlavaNextFastImageProcessorKwargs]) -> BatchFeature:
95
+ return super().preprocess(images, **kwargs)
96
+
97
+ def _resize_for_patching(
98
+ self,
99
+ image: "torch.Tensor",
100
+ target_resolution: tuple,
101
+ interpolation: "F.InterpolationMode",
102
+ input_data_format: ChannelDimension,
103
+ ) -> "torch.Tensor":
104
+ """
105
+ Resizes an image to a target resolution while maintaining aspect ratio.
106
+
107
+ Args:
108
+ image ("torch.Tensor"):
109
+ The input image.
110
+ target_resolution (tuple):
111
+ The target resolution (height, width) of the image.
112
+ interpolation (`InterpolationMode`):
113
+ Resampling filter to use if resizing the image.
114
+ input_data_format (`ChannelDimension` or `str`):
115
+ The channel dimension format of the input image.
116
+
117
+ Returns:
118
+ "torch.Tensor": The resized and padded image.
119
+ """
120
+ new_height, new_width = get_patch_output_size(image, target_resolution, input_data_format)
121
+
122
+ # Resize the image
123
+ resized_image = self.resize(
124
+ image=image,
125
+ size=SizeDict(height=new_height, width=new_width),
126
+ interpolation=interpolation,
127
+ )
128
+
129
+ return resized_image
130
+
131
+ def _get_padding_size(self, original_resolution: tuple, target_resolution: tuple):
132
+ original_height, original_width = original_resolution
133
+ target_height, target_width = target_resolution
134
+ paste_x, r_x = divmod(target_width - original_width, 2)
135
+ paste_y, r_y = divmod(target_height - original_height, 2)
136
+ return [paste_x, paste_y, paste_x + r_x, paste_y + r_y]
137
+
138
+ def _pad_for_patching(
139
+ self, image: "torch.Tensor", target_resolution: tuple, input_data_format: ChannelDimension
140
+ ) -> "torch.Tensor":
141
+ """
142
+ Pad an image to a target resolution while maintaining aspect ratio.
143
+ """
144
+ new_resolution = get_patch_output_size(image, target_resolution, input_data_format)
145
+ padding = self._get_padding_size(new_resolution, target_resolution)
146
+
147
+ padded_image = F.pad(image, padding=padding)
148
+
149
+ return padded_image
150
+
151
+ def _get_image_patches(
152
+ self,
153
+ image: "torch.Tensor",
154
+ grid_pinpoints,
155
+ size: tuple,
156
+ patch_size: int,
157
+ interpolation: "F.InterpolationMode",
158
+ ) -> list["torch.Tensor"]:
159
+ """
160
+ Process an image with variable resolutions by dividing it into patches.
161
+
162
+ Args:
163
+ image ("torch.Tensor"):
164
+ The input image to be processed.
165
+ grid_pinpoints (List):
166
+ A string representation of a list of possible resolutions.
167
+ size (`tuple`):
168
+ Size to resize the original image to.
169
+ patch_size (`int`):
170
+ Size of the patches to divide the image into.
171
+ interpolation (`"InterpolationMode"`):
172
+ Resampling filter to use if resizing the image.
173
+
174
+ Returns:
175
+ list["torch.Tensor"]: A list of NumPy arrays containing the processed image patches.
176
+ """
177
+ if not isinstance(grid_pinpoints, list):
178
+ raise TypeError("grid_pinpoints must be a list of possible resolutions.")
179
+
180
+ possible_resolutions = grid_pinpoints
181
+
182
+ image_size = get_image_size(image, channel_dim=ChannelDimension.FIRST)
183
+ best_resolution = select_best_resolution(image_size, possible_resolutions)
184
+ resized_image = self._resize_for_patching(
185
+ image, best_resolution, interpolation=interpolation, input_data_format=ChannelDimension.FIRST
186
+ )
187
+ padded_image = self._pad_for_patching(resized_image, best_resolution, input_data_format=ChannelDimension.FIRST)
188
+ patches = divide_to_patches(padded_image, patch_size=patch_size)
189
+ resized_original_image = F.resize(image, size=size, interpolation=interpolation)
190
+
191
+ image_patches = [resized_original_image] + patches
192
+
193
+ return image_patches
194
+
195
+ def _pad_for_batching(
196
+ self,
197
+ pixel_values: list["torch.Tensor"],
198
+ ) -> list["torch.Tensor"]:
199
+ """
200
+ Pads images on the `num_of_patches` dimension with zeros to form a batch of same number of patches.
201
+
202
+ Args:
203
+ pixel_values (`list[torch.Tensor]`):
204
+ An array of pixel values of each images of shape (`batch_size`, `num_patches`, `image_in_3D`)
205
+
206
+ Returns:
207
+ list[`torch.Tensor`]: The padded images.
208
+ """
209
+ max_patch = max(len(x) for x in pixel_values)
210
+ pixel_values = [
211
+ torch.nn.functional.pad(image, pad=[0, 0, 0, 0, 0, 0, 0, max_patch - image.shape[0]])
212
+ for image in pixel_values
213
+ ]
214
+
215
+ return pixel_values
216
+
217
+ def _preprocess(
218
+ self,
219
+ images: list["torch.Tensor"],
220
+ do_resize: bool,
221
+ size: SizeDict,
222
+ image_grid_pinpoints: list[list[int]],
223
+ interpolation: Optional["F.InterpolationMode"],
224
+ do_center_crop: bool,
225
+ crop_size: SizeDict,
226
+ do_rescale: bool,
227
+ rescale_factor: float,
228
+ do_normalize: bool,
229
+ image_mean: Optional[Union[float, list[float]]],
230
+ image_std: Optional[Union[float, list[float]]],
231
+ do_pad: bool,
232
+ disable_grouping: Optional[bool],
233
+ return_tensors: Optional[Union[str, TensorType]],
234
+ **kwargs,
235
+ ) -> BatchFeature:
236
+ processed_images = []
237
+ image_sizes = []
238
+ # Determine the size tuple
239
+ if size and size.height and size.width:
240
+ size_tuple = (size.height, size.width)
241
+ else:
242
+ size_tuple = (size.shortest_edge, size.shortest_edge)
243
+
244
+ # Determine the patch size
245
+ if crop_size and crop_size.height:
246
+ patch_size = crop_size.height
247
+ elif size and size.height:
248
+ patch_size = size.height
249
+ else:
250
+ patch_size = size.shortest_edge
251
+
252
+ for image in images:
253
+ image_patches = self._get_image_patches(
254
+ image,
255
+ image_grid_pinpoints,
256
+ size=size_tuple,
257
+ patch_size=patch_size,
258
+ interpolation=interpolation,
259
+ )
260
+
261
+ # Group images by size for batched processing
262
+ processed_image_patches_grouped = {}
263
+ grouped_image_patches, grouped_image_patches_index = group_images_by_shape(
264
+ image_patches, disable_grouping=disable_grouping
265
+ )
266
+ for shape, stacked_image_patches in grouped_image_patches.items():
267
+ if do_resize:
268
+ stacked_image_patches = self.resize(
269
+ image=stacked_image_patches,
270
+ size=size,
271
+ interpolation=interpolation,
272
+ )
273
+ if do_center_crop:
274
+ stacked_image_patches = self.center_crop(stacked_image_patches, crop_size)
275
+ # Fused rescale and normalize
276
+ stacked_image_patches = self.rescale_and_normalize(
277
+ stacked_image_patches, do_rescale, rescale_factor, do_normalize, image_mean, image_std
278
+ )
279
+ processed_image_patches_grouped[shape] = stacked_image_patches
280
+ processed_image_patches = reorder_images(processed_image_patches_grouped, grouped_image_patches_index)
281
+ processed_image_patches = (
282
+ torch.stack(processed_image_patches, dim=0) if return_tensors else processed_image_patches
283
+ )
284
+ processed_images.append(processed_image_patches)
285
+ image_sizes.append(get_image_size(image, ChannelDimension.FIRST))
286
+
287
+ if do_pad:
288
+ processed_images = self._pad_for_batching(processed_images)
289
+ processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images
290
+ return BatchFeature(
291
+ data={"pixel_values": processed_images, "image_sizes": image_sizes}, tensor_type=return_tensors
292
+ )
293
+
294
+
295
+ __all__ = ["LlavaNextImageProcessorFast"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/llava_next/modeling_llava_next.py ADDED
@@ -0,0 +1,797 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 Llava-NeXT model."""
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Union
20
+
21
+ import numpy as np
22
+ import torch
23
+ from torch import nn
24
+
25
+ from ...activations import ACT2FN
26
+ from ...cache_utils import Cache
27
+ from ...generation import GenerationMixin
28
+ from ...image_processing_utils import select_best_resolution
29
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
30
+ from ...modeling_outputs import BaseModelOutputWithPast, ModelOutput
31
+ from ...modeling_utils import PreTrainedModel
32
+ from ...processing_utils import Unpack
33
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
34
+ from ..auto import AutoModel
35
+ from .configuration_llava_next import LlavaNextConfig
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+
41
+ def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
42
+ """
43
+ Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
44
+
45
+ Args:
46
+ image_size (`tuple`):
47
+ The size of the input image in the format (width, height).
48
+ grid_pinpoints (`List`):
49
+ A list containing possible resolutions. Each item in the list should be a tuple or list
50
+ of the form `(height, width)`.
51
+ patch_size (`int`):
52
+ The size of each image patch.
53
+
54
+ Returns:
55
+ tuple: The shape of the image patch grid in the format (width, height).
56
+ """
57
+ if not isinstance(grid_pinpoints, list):
58
+ raise TypeError("grid_pinpoints should be a list of tuples or lists")
59
+
60
+ # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
61
+ if not isinstance(image_size, (list, tuple)):
62
+ if not isinstance(image_size, (torch.Tensor, np.ndarray)):
63
+ raise TypeError(
64
+ f"image_size invalid type: {type(image_size)} not valid, should be either list, tuple, np.ndarray or tensor"
65
+ )
66
+ image_size = image_size.tolist()
67
+
68
+ height, width = select_best_resolution(image_size, grid_pinpoints)
69
+ return height // patch_size, width // patch_size
70
+
71
+
72
+ def image_size_to_num_patches(image_size, grid_pinpoints, patch_size: int):
73
+ """
74
+ Calculate the number of patches after the preprocessing for images of any resolution.
75
+
76
+ Args:
77
+ image_size (`torch.LongTensor` or `np.ndarray` or `tuple[int, int]`):
78
+ The size of the input image in the format (height, width). ?
79
+ grid_pinpoints (`List`):
80
+ A list containing possible resolutions. Each item in the list should be a tuple or list
81
+ of the form `(height, width)`.
82
+ patch_size (`int`):
83
+ The size of each image patch.
84
+
85
+ Returns:
86
+ int: the number of patches
87
+ """
88
+ if not isinstance(grid_pinpoints, list):
89
+ raise TypeError("grid_pinpoints should be a list of tuples or lists")
90
+
91
+ # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
92
+ if not isinstance(image_size, (list, tuple)):
93
+ if not isinstance(image_size, (torch.Tensor, np.ndarray)):
94
+ raise TypeError(f"image_size invalid type {type(image_size)} with value {image_size}")
95
+ image_size = image_size.tolist()
96
+
97
+ best_resolution = select_best_resolution(image_size, grid_pinpoints)
98
+ height, width = best_resolution
99
+ num_patches = 0
100
+ # consider change to ceil(height/patch_size)*ceil(width/patch_size) + 1
101
+ for i in range(0, height, patch_size):
102
+ for j in range(0, width, patch_size):
103
+ num_patches += 1
104
+ # add the base patch
105
+ num_patches += 1
106
+ return num_patches
107
+
108
+
109
+ def unpad_image(tensor, original_size):
110
+ """
111
+ Unpads a PyTorch tensor of a padded and resized image.
112
+
113
+ Args:
114
+ tensor (`torch.Tensor`):
115
+ The image tensor, assumed to be of shape (num_channels, height, width).
116
+ original_size (`tuple`):
117
+ The original size of the image (height, width).
118
+
119
+ Returns:
120
+ `torch.Tensor`: The unpadded image tensor.
121
+ """
122
+ if not isinstance(original_size, (list, tuple)):
123
+ if not isinstance(original_size, (torch.Tensor, np.ndarray)):
124
+ raise TypeError(
125
+ f"image_size invalid type: {type(original_size)} not valid, should be either list, tuple, np.ndarray or tensor"
126
+ )
127
+ original_size = original_size.tolist()
128
+ original_height, original_width = original_size
129
+ current_height, current_width = tensor.shape[1:]
130
+
131
+ original_aspect_ratio = original_width / original_height
132
+ current_aspect_ratio = current_width / current_height
133
+
134
+ if original_aspect_ratio > current_aspect_ratio:
135
+ scale_factor = current_width / original_width
136
+ new_height = int(round(original_height * scale_factor, 7))
137
+ padding = (current_height - new_height) // 2
138
+ unpadded_tensor = tensor[:, padding : current_height - padding, :]
139
+ else:
140
+ scale_factor = current_height / original_height
141
+ new_width = int(round(original_width * scale_factor, 7))
142
+ padding = (current_width - new_width) // 2
143
+ unpadded_tensor = tensor[:, :, padding : current_width - padding]
144
+
145
+ return unpadded_tensor
146
+
147
+
148
+ @dataclass
149
+ @auto_docstring(
150
+ custom_intro="""
151
+ Base class for Llava outputs, with hidden states and attentions.
152
+ """
153
+ )
154
+ class LlavaNextModelOutputWithPast(BaseModelOutputWithPast):
155
+ r"""
156
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
157
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
158
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
159
+
160
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
161
+ `past_key_values` input) to speed up sequential decoding.
162
+ image_hidden_states (`torch.FloatTensor`, *optional*):
163
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
164
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
165
+ """
166
+
167
+ image_hidden_states: Optional[torch.FloatTensor] = None
168
+
169
+
170
+ @dataclass
171
+ @auto_docstring(
172
+ custom_intro="""
173
+ Base class for LlavaNext causal language model (or autoregressive) outputs.
174
+ """
175
+ )
176
+ class LlavaNextCausalLMOutputWithPast(ModelOutput):
177
+ r"""
178
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
179
+ Language modeling loss (for next-token prediction).
180
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
181
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
182
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
183
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
184
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
185
+
186
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
187
+ `past_key_values` input) to speed up sequential decoding.
188
+ image_hidden_states (`torch.FloatTensor`, *optional*):
189
+ A `torch.FloatTensor` of size (batch_size * num_patches, num_images, sequence_length, hidden_size)`.
190
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
191
+ """
192
+
193
+ loss: Optional[torch.FloatTensor] = None
194
+ logits: Optional[torch.FloatTensor] = None
195
+ past_key_values: Optional[list[torch.FloatTensor]] = None
196
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
197
+ attentions: Optional[tuple[torch.FloatTensor]] = None
198
+ image_hidden_states: Optional[torch.FloatTensor] = None
199
+
200
+
201
+ # Copied from transformers.models.llava.modeling_llava.LlavaMultiModalProjector with Llava->LlavaNext
202
+ class LlavaNextMultiModalProjector(nn.Module):
203
+ def __init__(self, config: LlavaNextConfig):
204
+ super().__init__()
205
+ # We have hidden_size * the number of vision feature layers
206
+ num_feature_layers = 1 if isinstance(config.vision_feature_layer, int) else len(config.vision_feature_layer)
207
+ self.linear_1 = nn.Linear(
208
+ config.vision_config.hidden_size * num_feature_layers,
209
+ config.text_config.hidden_size,
210
+ bias=config.multimodal_projector_bias,
211
+ )
212
+ self.act = ACT2FN[config.projector_hidden_act]
213
+ self.linear_2 = nn.Linear(
214
+ config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias
215
+ )
216
+
217
+ def forward(self, image_features):
218
+ hidden_states = self.linear_1(image_features)
219
+ hidden_states = self.act(hidden_states)
220
+ hidden_states = self.linear_2(hidden_states)
221
+ return hidden_states
222
+
223
+
224
+ @auto_docstring
225
+ class LlavaNextPreTrainedModel(PreTrainedModel):
226
+ config: LlavaNextConfig
227
+ base_model_prefix = ""
228
+ supports_gradient_checkpointing = True
229
+ _no_split_modules = ["LlamaDecoderLayer"]
230
+ _skip_keys_device_placement = "past_key_values"
231
+
232
+ _supports_flash_attn = True
233
+ _supports_sdpa = True
234
+
235
+ _can_compile_fullgraph = True
236
+ _supports_flex_attn = True
237
+ _supports_attention_backend = True
238
+
239
+ def _init_weights(self, module):
240
+ std = getattr(self.config, "initializer_range", self.config.get_text_config().initializer_range)
241
+
242
+ if isinstance(module, nn.Linear):
243
+ module.weight.data.normal_(mean=0.0, std=std)
244
+ if module.bias is not None:
245
+ module.bias.data.zero_()
246
+ elif isinstance(module, LlavaNextModel):
247
+ embed_std = 1 / math.sqrt(self.config.text_config.hidden_size)
248
+ module.image_newline.data.normal_(mean=0.0, std=embed_std)
249
+
250
+
251
+ @auto_docstring(
252
+ custom_intro="""
253
+ The Llava-Next model which consists of a vision backbone and a language model without language modeling head.
254
+ """
255
+ )
256
+ class LlavaNextModel(LlavaNextPreTrainedModel):
257
+ _checkpoint_conversion_mapping = {"language_model.model": "language_model"}
258
+
259
+ def __init__(self, config: LlavaNextConfig):
260
+ super().__init__(config)
261
+ self.vision_tower = AutoModel.from_config(config.vision_config)
262
+
263
+ self.multi_modal_projector = LlavaNextMultiModalProjector(config)
264
+ embed_std = 1 / math.sqrt(config.text_config.hidden_size)
265
+ self.image_newline = nn.Parameter(torch.randn(config.text_config.hidden_size, dtype=self.dtype) * embed_std)
266
+
267
+ self.vocab_size = config.text_config.vocab_size
268
+ self.language_model = AutoModel.from_config(config.text_config)
269
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
270
+ self.post_init()
271
+
272
+ def get_input_embeddings(self):
273
+ return self.language_model.get_input_embeddings()
274
+
275
+ def set_input_embeddings(self, value):
276
+ self.language_model.set_input_embeddings(value)
277
+
278
+ def set_decoder(self, decoder):
279
+ self.language_model = decoder
280
+
281
+ def get_decoder(self):
282
+ return self.language_model
283
+
284
+ def pack_image_features(self, image_features, image_sizes, vision_feature_select_strategy, image_newline=None):
285
+ """
286
+ Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
287
+
288
+ Args:
289
+ image_features (`list[torch.Tensor]` of length num_images, each of shape `(num_patches, image_length, embed_dim)`)
290
+ List of image feature tensor, each contains all the visual feature of all patches.
291
+ image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
292
+ Actual image size of each images (H, W).
293
+ vision_feature_select_strategy (`str`)
294
+ The feature selection strategy used to select the vision feature from the vision backbone.
295
+ image_newline (`torch.Tensor` of shape `(embed_dim)`)
296
+ New line embedding vector.
297
+ Returns:
298
+ image_features (`torch.Tensor` of shape `(all_feat_len, embed_dim)`)
299
+ feature_lens (`list[int]`)
300
+ token length of each image in image_features
301
+ """
302
+ new_image_features = []
303
+ feature_lens = []
304
+ for image_idx, image_feature in enumerate(image_features):
305
+ if image_feature.shape[0] > 1:
306
+ base_image_feature = image_feature[0]
307
+ image_feature = image_feature[1:]
308
+ height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
309
+
310
+ num_patch_height, num_patch_width = get_anyres_image_grid_shape(
311
+ image_sizes[image_idx],
312
+ self.config.image_grid_pinpoints,
313
+ self.config.vision_config.image_size,
314
+ )
315
+
316
+ if (
317
+ np.prod(image_feature.shape) % (num_patch_height * num_patch_width * height * width) != 0
318
+ and vision_feature_select_strategy == "default"
319
+ ):
320
+ logger.warning_once(
321
+ "Image feature shape does not line up with the provided patch size. "
322
+ "You may be using the `default` vision_feature_select_strategy with a"
323
+ " visual encoder that does not have CLS."
324
+ )
325
+
326
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
327
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
328
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
329
+ image_feature = unpad_image(image_feature, image_sizes[image_idx])
330
+ if image_newline is not None:
331
+ image_feature = torch.cat(
332
+ (
333
+ image_feature,
334
+ image_newline[:, None, None]
335
+ .expand(*image_feature.shape[:-1], 1)
336
+ .to(image_feature.device, image_feature.dtype),
337
+ ),
338
+ dim=-1,
339
+ )
340
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
341
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
342
+ else:
343
+ image_feature = image_feature[0]
344
+ if image_newline is not None:
345
+ image_feature = torch.cat((image_feature, image_newline[None].to(image_feature)), dim=0)
346
+ new_image_features.append(image_feature)
347
+ feature_lens.append(image_feature.size(0))
348
+ feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=image_features[0].device)
349
+ return new_image_features, feature_lens
350
+
351
+ def get_image_features(
352
+ self,
353
+ pixel_values: torch.FloatTensor,
354
+ image_sizes: torch.Tensor,
355
+ vision_feature_layer: Optional[Union[int, list[int]]] = None,
356
+ vision_feature_select_strategy: Optional[str] = None,
357
+ ):
358
+ """
359
+ Obtains image last hidden states from the vision tower and apply multimodal projection.
360
+
361
+ Args:
362
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_patches, channels, height, width)`)
363
+ The tensors corresponding to the input images.
364
+ image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
365
+ Actual image size of each images (H, W).
366
+ vision_feature_layer (`Union[int, list[int]]`, *optional*):
367
+ The index of the layer to select the vision feature. If multiple indices are provided,
368
+ the vision feature of the corresponding indices will be concatenated to form the
369
+ vision features.
370
+ vision_feature_select_strategy (`str`, *optional*):
371
+ The feature selection strategy used to select the vision feature from the vision backbone.
372
+ Can be one of `"default"` or `"full"`
373
+ Returns:
374
+ image_features (list[`torch.Tensor`]): List of image feature tensor, each contains all the visual feature of all patches
375
+ and are of shape `(num_patches, image_length, embed_dim)`).
376
+ """
377
+ vision_feature_layer = (
378
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
379
+ )
380
+ vision_feature_select_strategy = (
381
+ vision_feature_select_strategy
382
+ if vision_feature_select_strategy is not None
383
+ else self.config.vision_feature_select_strategy
384
+ )
385
+
386
+ # ! infer image_num_patches from image_sizes
387
+ image_num_patches = [
388
+ image_size_to_num_patches(
389
+ image_size=imsize,
390
+ grid_pinpoints=self.config.image_grid_pinpoints,
391
+ patch_size=self.config.vision_config.image_size,
392
+ )
393
+ for imsize in image_sizes
394
+ ]
395
+ if pixel_values.dim() == 5:
396
+ # stacked if input is (batch_size, num_patches, num_channels, height, width)
397
+ _pixel_values_list = [pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)]
398
+ pixel_values = torch.cat(_pixel_values_list, dim=0)
399
+ elif pixel_values.dim() != 4:
400
+ # otherwise has to be stacked from list of (num_patches, num_channels, height, width)
401
+ raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
402
+
403
+ image_features = self.vision_tower(pixel_values, output_hidden_states=True)
404
+ # If we have one vision feature layer, return the corresponding hidden states,
405
+ # otherwise, select the hidden states of each feature layer and concatenate them
406
+ if isinstance(vision_feature_layer, int):
407
+ selected_image_feature = image_features.hidden_states[vision_feature_layer]
408
+ else:
409
+ hs_pool = [image_features.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
410
+ selected_image_feature = torch.cat(hs_pool, dim=-1)
411
+
412
+ if vision_feature_select_strategy == "default":
413
+ selected_image_feature = selected_image_feature[:, 1:]
414
+ elif vision_feature_select_strategy == "full":
415
+ selected_image_feature = selected_image_feature
416
+
417
+ image_features = self.multi_modal_projector(selected_image_feature)
418
+ image_features = torch.split(image_features, image_num_patches, dim=0)
419
+
420
+ # NOTE we only support multimodal_patch_merge_type == "spatial_unpad"
421
+ image_features, feature_lens = self.pack_image_features(
422
+ image_features,
423
+ image_sizes,
424
+ vision_feature_select_strategy=vision_feature_select_strategy,
425
+ image_newline=self.image_newline,
426
+ )
427
+ return image_features
428
+
429
+ def get_placeholder_mask(
430
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
431
+ ):
432
+ """
433
+ Obtains multimodal placeholdr mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
434
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
435
+ """
436
+ if input_ids is None:
437
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
438
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
439
+ )
440
+ special_image_mask = special_image_mask.all(-1)
441
+ else:
442
+ special_image_mask = input_ids == self.config.image_token_id
443
+
444
+ n_image_tokens = special_image_mask.sum()
445
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
446
+ if inputs_embeds[special_image_mask].numel() != image_features.numel():
447
+ raise ValueError(
448
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.shape[0]}"
449
+ )
450
+ return special_image_mask
451
+
452
+ @can_return_tuple
453
+ @auto_docstring
454
+ def forward(
455
+ self,
456
+ input_ids: torch.LongTensor = None,
457
+ pixel_values: torch.FloatTensor = None,
458
+ image_sizes: Optional[torch.LongTensor] = None,
459
+ attention_mask: Optional[torch.Tensor] = None,
460
+ position_ids: Optional[torch.LongTensor] = None,
461
+ past_key_values: Optional[Cache] = None,
462
+ inputs_embeds: Optional[torch.FloatTensor] = None,
463
+ vision_feature_layer: Optional[Union[int, list[int]]] = None,
464
+ vision_feature_select_strategy: Optional[str] = None,
465
+ use_cache: Optional[bool] = None,
466
+ output_attentions: Optional[bool] = None,
467
+ output_hidden_states: Optional[bool] = None,
468
+ return_dict: Optional[bool] = None,
469
+ cache_position: Optional[torch.LongTensor] = None,
470
+ **kwargs: Unpack[FlashAttentionKwargs],
471
+ ) -> Union[tuple, LlavaNextModelOutputWithPast]:
472
+ r"""
473
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
474
+ The feature selection strategy used to select the vision feature from the vision backbone.
475
+ Can be one of `"default"` or `"full"`. If `"default"`, the CLS token is removed from the vision features.
476
+ If `"full"`, the full vision features are used.
477
+ """
478
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
479
+ output_hidden_states = (
480
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
481
+ )
482
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
483
+ vision_feature_layer = (
484
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
485
+ )
486
+ vision_feature_select_strategy = (
487
+ vision_feature_select_strategy
488
+ if vision_feature_select_strategy is not None
489
+ else self.config.vision_feature_select_strategy
490
+ )
491
+
492
+ if (input_ids is None) ^ (inputs_embeds is not None):
493
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
494
+
495
+ if inputs_embeds is None:
496
+ inputs_embeds = self.get_input_embeddings()(input_ids)
497
+
498
+ if pixel_values is not None and pixel_values.size(0) > 0:
499
+ image_features = self.get_image_features(
500
+ pixel_values,
501
+ image_sizes,
502
+ vision_feature_layer=vision_feature_layer,
503
+ vision_feature_select_strategy=vision_feature_select_strategy,
504
+ )
505
+ image_features = torch.cat(image_features, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
506
+ special_image_mask = self.get_placeholder_mask(
507
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
508
+ )
509
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
510
+
511
+ outputs = self.language_model(
512
+ attention_mask=attention_mask,
513
+ position_ids=position_ids,
514
+ past_key_values=past_key_values,
515
+ inputs_embeds=inputs_embeds,
516
+ use_cache=use_cache,
517
+ output_attentions=output_attentions,
518
+ output_hidden_states=output_hidden_states,
519
+ return_dict=True,
520
+ cache_position=cache_position,
521
+ **kwargs,
522
+ )
523
+
524
+ return LlavaNextModelOutputWithPast(
525
+ last_hidden_state=outputs.last_hidden_state,
526
+ past_key_values=outputs.past_key_values,
527
+ hidden_states=outputs.hidden_states,
528
+ attentions=outputs.attentions,
529
+ image_hidden_states=image_features if pixel_values is not None else None,
530
+ )
531
+
532
+
533
+ @auto_docstring(
534
+ custom_intro="""
535
+ The LLAVA-NeXT model which consists of a vision backbone and a language model.
536
+ """
537
+ )
538
+ class LlavaNextForConditionalGeneration(LlavaNextPreTrainedModel, GenerationMixin):
539
+ _checkpoint_conversion_mapping = {
540
+ "^language_model.model": "model.language_model",
541
+ "^vision_tower": "model.vision_tower",
542
+ "^multi_modal_projector": "model.multi_modal_projector",
543
+ "^image_newline": "model.image_newline",
544
+ "^language_model.lm_head": "lm_head",
545
+ }
546
+ _tied_weights_keys = ["lm_head.weight"]
547
+
548
+ def __init__(self, config: LlavaNextConfig):
549
+ super().__init__(config)
550
+ self.model = LlavaNextModel(config)
551
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
552
+ self.post_init()
553
+
554
+ def get_input_embeddings(self):
555
+ return self.model.get_input_embeddings()
556
+
557
+ def set_input_embeddings(self, value):
558
+ self.model.set_input_embeddings(value)
559
+
560
+ def get_output_embeddings(self) -> nn.Module:
561
+ return self.lm_head
562
+
563
+ def set_decoder(self, decoder):
564
+ self.model.set_decoder(decoder)
565
+
566
+ def get_decoder(self):
567
+ return self.model.get_decoder()
568
+
569
+ def pack_image_features(self, image_features, image_sizes, vision_feature_select_strategy, image_newline=None):
570
+ return self.model.pack_image_features(
571
+ image_features=image_features,
572
+ image_sizes=image_sizes,
573
+ vision_feature_select_strategy=vision_feature_select_strategy,
574
+ image_newline=image_newline,
575
+ )
576
+
577
+ def get_image_features(
578
+ self,
579
+ pixel_values: torch.FloatTensor,
580
+ image_sizes: torch.Tensor,
581
+ vision_feature_layer: Optional[Union[int, list[int]]] = None,
582
+ vision_feature_select_strategy: Optional[str] = None,
583
+ ):
584
+ return self.model.get_image_features(
585
+ pixel_values=pixel_values,
586
+ image_sizes=image_sizes,
587
+ vision_feature_layer=vision_feature_layer,
588
+ vision_feature_select_strategy=vision_feature_select_strategy,
589
+ )
590
+
591
+ # Make modules available through conditional class for BC
592
+ @property
593
+ def language_model(self):
594
+ return self.model.language_model
595
+
596
+ @property
597
+ def vision_tower(self):
598
+ return self.model.vision_tower
599
+
600
+ @property
601
+ def multi_modal_projector(self):
602
+ return self.model.multi_modal_projector
603
+
604
+ @can_return_tuple
605
+ @auto_docstring
606
+ def forward(
607
+ self,
608
+ input_ids: torch.LongTensor = None,
609
+ pixel_values: torch.FloatTensor = None,
610
+ image_sizes: Optional[torch.LongTensor] = None,
611
+ attention_mask: Optional[torch.Tensor] = None,
612
+ position_ids: Optional[torch.LongTensor] = None,
613
+ past_key_values: Optional[Cache] = None,
614
+ inputs_embeds: Optional[torch.FloatTensor] = None,
615
+ vision_feature_layer: Optional[Union[int, list[int]]] = None,
616
+ vision_feature_select_strategy: Optional[str] = None,
617
+ labels: Optional[torch.LongTensor] = None,
618
+ use_cache: Optional[bool] = None,
619
+ output_attentions: Optional[bool] = None,
620
+ output_hidden_states: Optional[bool] = None,
621
+ cache_position: Optional[torch.LongTensor] = None,
622
+ logits_to_keep: Union[int, torch.Tensor] = 0,
623
+ **kwargs: Unpack[TransformersKwargs],
624
+ ) -> Union[tuple, LlavaNextCausalLMOutputWithPast]:
625
+ r"""
626
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
627
+ The feature selection strategy used to select the vision feature from the vision backbone.
628
+ Can be one of `"default"` or `"full"`. If `"default"`, the CLS token is removed from the vision features.
629
+ If `"full"`, the full vision features are used.
630
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
631
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
632
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
633
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
634
+
635
+ Example:
636
+
637
+ ```python
638
+ >>> from PIL import Image
639
+ >>> import requests
640
+ >>> from transformers import AutoProcessor, LlavaNextForConditionalGeneration
641
+
642
+ >>> model = LlavaNextForConditionalGeneration.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
643
+ >>> processor = AutoProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
644
+
645
+ >>> prompt = "[INST] <image>\nWhat is shown in this image? [/INST]"
646
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
647
+ >>> image = Image.open(requests.get(url, stream=True).raw)
648
+
649
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
650
+
651
+ >>> # Generate
652
+ >>> generate_ids = model.generate(**inputs, max_length=30)
653
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
654
+ "[INST] \nWhat is shown in this image? [/INST] The image appears to be a radar chart, which is a type of multi-dimensional plot (...)"
655
+ ```"""
656
+
657
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
658
+ output_hidden_states = (
659
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
660
+ )
661
+ vision_feature_layer = (
662
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
663
+ )
664
+ vision_feature_select_strategy = (
665
+ vision_feature_select_strategy
666
+ if vision_feature_select_strategy is not None
667
+ else self.config.vision_feature_select_strategy
668
+ )
669
+
670
+ outputs = self.model(
671
+ input_ids,
672
+ pixel_values=pixel_values,
673
+ image_sizes=image_sizes,
674
+ vision_feature_layer=vision_feature_layer,
675
+ vision_feature_select_strategy=vision_feature_select_strategy,
676
+ attention_mask=attention_mask,
677
+ position_ids=position_ids,
678
+ past_key_values=past_key_values,
679
+ inputs_embeds=inputs_embeds,
680
+ use_cache=use_cache,
681
+ output_attentions=output_attentions,
682
+ output_hidden_states=output_hidden_states,
683
+ return_dict=True,
684
+ cache_position=cache_position,
685
+ **kwargs,
686
+ )
687
+
688
+ hidden_states = outputs[0]
689
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
690
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
691
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
692
+
693
+ loss = None
694
+ if labels is not None:
695
+ loss = self.loss_function(
696
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
697
+ )
698
+
699
+ return LlavaNextCausalLMOutputWithPast(
700
+ loss=loss,
701
+ logits=logits,
702
+ past_key_values=outputs.past_key_values,
703
+ hidden_states=outputs.hidden_states,
704
+ attentions=outputs.attentions,
705
+ image_hidden_states=outputs.image_hidden_states,
706
+ )
707
+
708
+ def prepare_inputs_for_generation(
709
+ self,
710
+ input_ids,
711
+ past_key_values=None,
712
+ inputs_embeds=None,
713
+ pixel_values=None,
714
+ image_sizes=None,
715
+ attention_mask=None,
716
+ cache_position=None,
717
+ logits_to_keep=None,
718
+ **kwargs,
719
+ ):
720
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
721
+
722
+ model_inputs = super().prepare_inputs_for_generation(
723
+ input_ids,
724
+ past_key_values=past_key_values,
725
+ inputs_embeds=inputs_embeds,
726
+ attention_mask=attention_mask,
727
+ cache_position=cache_position,
728
+ logits_to_keep=logits_to_keep,
729
+ **kwargs,
730
+ )
731
+
732
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
733
+ # Otherwise we need pixel values to be passed to model
734
+ if cache_position[0] == 0:
735
+ model_inputs["pixel_values"] = pixel_values
736
+ model_inputs["image_sizes"] = image_sizes
737
+
738
+ return model_inputs
739
+
740
+ @staticmethod
741
+ # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._prepare_4d_causal_attention_mask_with_cache_position
742
+ def _prepare_4d_causal_attention_mask_with_cache_position(
743
+ attention_mask: torch.Tensor,
744
+ sequence_length: int,
745
+ target_length: int,
746
+ dtype: torch.dtype,
747
+ cache_position: torch.Tensor,
748
+ batch_size: int,
749
+ **kwargs,
750
+ ):
751
+ """
752
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
753
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
754
+
755
+ Args:
756
+ attention_mask (`torch.Tensor`):
757
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
758
+ `(batch_size, 1, query_length, key_value_length)`.
759
+ sequence_length (`int`):
760
+ The sequence length being processed.
761
+ target_length (`int`):
762
+ The target length: when generating with static cache, the mask should be as long as the static cache,
763
+ to account for the 0 padding, the part of the cache that is not filled yet.
764
+ dtype (`torch.dtype`):
765
+ The dtype to use for the 4D attention mask.
766
+ cache_position (`torch.Tensor`):
767
+ Indices depicting the position of the input sequence tokens in the sequence.
768
+ batch_size (`torch.Tensor`):
769
+ Batch size.
770
+ """
771
+ if attention_mask is not None and attention_mask.dim() == 4:
772
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
773
+ causal_mask = attention_mask
774
+ else:
775
+ min_dtype = torch.finfo(dtype).min
776
+ causal_mask = torch.full(
777
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
778
+ )
779
+ if sequence_length != 1:
780
+ causal_mask = torch.triu(causal_mask, diagonal=1)
781
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
782
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
783
+ if attention_mask is not None:
784
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
785
+ mask_length = attention_mask.shape[-1]
786
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
787
+ causal_mask.device
788
+ )
789
+ padding_mask = padding_mask == 0
790
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
791
+ padding_mask, min_dtype
792
+ )
793
+
794
+ return causal_mask
795
+
796
+
797
+ __all__ = ["LlavaNextForConditionalGeneration", "LlavaNextPreTrainedModel", "LlavaNextModel"]