JinghuiLuAstronaut commited on
Commit
12c54ba
·
verified ·
1 Parent(s): 838e1fa

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. LTA_openwebtext_dualt/logs/lm1b_compact_gpt2bpe_v8192_len128_fullycoupled_4gpu/lta_lm1b_compact_gpt2bpe_v8192_len128_mask0p1-1p0_uniformt_fp32_ddit768x12_gbs512_4gpu_1m_20260520_232453.log +0 -0
  2. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/_punycode.py +67 -0
  3. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/port.yaml +48 -0
  4. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/byt5/tokenization_byt5.py +234 -0
  5. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/convnextv2/__init__.py +27 -0
  6. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/convnextv2/modeling_convnextv2.py +428 -0
  7. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/levit/__init__.py +30 -0
  8. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/levit/modeling_levit.py +665 -0
  9. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/megatron_gpt2/__init__.py +0 -0
  10. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/megatron_gpt2/checkpoint_reshaping_and_interoperability.py +925 -0
  11. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mllama/configuration_mllama.py +200 -0
  12. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mllama/modeling_mllama.py +1622 -0
  13. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mllama/processing_mllama.py +311 -0
  14. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/modernbert_decoder/__init__.py +27 -0
  15. LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/owt_llmclean_qwen36_35b_articlefull_full_rev8_3gpu_resume_20260531_120957.outer.log +0 -0
  16. LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/owt_t5_cleanstream_len1024_C1_to_64_d768_l12_h12_gbs512_8gpu_1m_lr3e4_20260527_132002.log +0 -0
  17. LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_norm_stateprobadd_selfcond_ce_fast_trainlogit_mn0p9_s0p9_20260605_053046.log +0 -0
  18. LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/owt_t5_ultraclean10k_len1024_C4096_to_32768_exp_d768_l12_h12_gbs512_8gpu_40k_lr3e4_20260527_212316.log +689 -0
  19. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_082000.pt +3 -0
  20. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_155000.pt +3 -0
LTA_openwebtext_dualt/logs/lm1b_compact_gpt2bpe_v8192_len128_fullycoupled_4gpu/lta_lm1b_compact_gpt2bpe_v8192_len128_mask0p1-1p0_uniformt_fp32_ddit768x12_gbs512_4gpu_1m_20260520_232453.log ADDED
The diff for this file is too large to render. See raw diff
 
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/_punycode.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2014 Mathias Bynens <https://mathiasbynens.be/>
2
+ # Copyright 2021 Taneli Hukkinen
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a copy of this software and associated documentation files (the
6
+ # "Software"), to deal in the Software without restriction, including
7
+ # without limitation the rights to use, copy, modify, merge, publish,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+
23
+ import codecs
24
+ from collections.abc import Callable
25
+ import re
26
+
27
+ REGEX_SEPARATORS = re.compile(r"[\x2E\u3002\uFF0E\uFF61]")
28
+ REGEX_NON_ASCII = re.compile(r"[^\0-\x7E]")
29
+
30
+
31
+ def encode(uni: str) -> str:
32
+ return codecs.encode(uni, encoding="punycode").decode()
33
+
34
+
35
+ def decode(ascii: str) -> str:
36
+ return codecs.decode(ascii, encoding="punycode") # type: ignore
37
+
38
+
39
+ def map_domain(string: str, fn: Callable[[str], str]) -> str:
40
+ parts = string.split("@")
41
+ result = ""
42
+ if len(parts) > 1:
43
+ # In email addresses, only the domain name should be punycoded. Leave
44
+ # the local part (i.e. everything up to `@`) intact.
45
+ result = parts[0] + "@"
46
+ string = parts[1]
47
+ labels = REGEX_SEPARATORS.split(string)
48
+ encoded = ".".join(fn(label) for label in labels)
49
+ return result + encoded
50
+
51
+
52
+ def to_unicode(obj: str) -> str:
53
+ def mapping(obj: str) -> str:
54
+ if obj.startswith("xn--"):
55
+ return decode(obj[4:].lower())
56
+ return obj
57
+
58
+ return map_domain(obj, mapping)
59
+
60
+
61
+ def to_ascii(obj: str) -> str:
62
+ def mapping(obj: str) -> str:
63
+ if REGEX_NON_ASCII.search(obj):
64
+ return "xn--" + encode(obj)
65
+ return obj
66
+
67
+ return map_domain(obj, mapping)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/port.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - package: markdown-it/markdown-it
2
+ version: 14.1.0
3
+ commit: 0fe7ccb4b7f30236fb05f623be6924961d296d3d
4
+ date: Mar 19, 2024
5
+ notes:
6
+ - Rename variables that use python built-in names, e.g.
7
+ - `max` -> `maximum`
8
+ - `len` -> `length`
9
+ - `str` -> `string`
10
+ - |
11
+ Convert JS `for` loops to `while` loops
12
+ this is generally the main difference between the codes,
13
+ because in python you can't do e.g. `for {i=1;i<x;i++} {}`
14
+ - |
15
+ `env` is a common Python dictionary, and so does not have attribute access to keys,
16
+ as with JavaScript dictionaries.
17
+ `options` have attribute access only to core markdownit configuration options
18
+ - |
19
+ `Token.attrs` is a dictionary, instead of a list of lists.
20
+ Upstream the list format is only used to guarantee order: https://github.com/markdown-it/markdown-it/issues/142,
21
+ but in Python 3.7+ order of dictionaries is guaranteed.
22
+ One should anyhow use the `attrGet`, `attrSet`, `attrPush` and `attrJoin` methods
23
+ to manipulate `Token.attrs`, which have an identical signature to those upstream.
24
+ - Use python version of `charCodeAt`
25
+ - |
26
+ Use `str` units instead of `int`s to represent Unicode codepoints.
27
+ This provides a significant performance boost
28
+ - |
29
+ In markdown_it/rules_block/reference.py,
30
+ record line range in state.env["references"] and add state.env["duplicate_refs"]
31
+ This is to allow renderers to report on issues regarding references
32
+ - |
33
+ The `MarkdownIt.__init__` signature is slightly different for updating options,
34
+ since you must always specify the config first, e.g.
35
+ use `MarkdownIt("commonmark", {"html": False})` instead of `MarkdownIt({"html": False})`
36
+ - The default configuration preset for `MarkdownIt` is "commonmark" not "default"
37
+ - Allow custom renderer to be passed to `MarkdownIt`
38
+ - |
39
+ change render method signatures
40
+ `func(tokens, idx, options, env, slf)` to
41
+ `func(self, tokens, idx, options, env)`
42
+ - |
43
+ Extensions add render methods by format
44
+ `MarkdownIt.add_render_rule(name, function, fmt="html")`,
45
+ rather than `MarkdownIt.renderer.rules[name] = function`
46
+ and renderers should declare a class property `__output__ = "html"`.
47
+ This allows for extensibility to more than just HTML renderers
48
+ - inline tokens in tables are assigned a map (this is helpful for propagation to children)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/byt5/tokenization_byt5.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 T5 Authors and HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tokenization class for model ByT5."""
15
+
16
+ import warnings
17
+
18
+ from ...tokenization_python import AddedToken, PreTrainedTokenizer
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class ByT5Tokenizer(PreTrainedTokenizer):
26
+ """
27
+ Construct a ByT5 tokenizer. ByT5 simply uses raw bytes utf-8 encoding.
28
+
29
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
30
+ this superclass for more information regarding those methods.
31
+
32
+ Args:
33
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
34
+ The end of sequence token.
35
+
36
+ <Tip>
37
+
38
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
39
+ The token used is the `sep_token`.
40
+
41
+ </Tip>
42
+
43
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
44
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
45
+ token instead.
46
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
47
+ The token used for padding, for example when batching sequences of different lengths.
48
+ extra_ids (`int`, *optional*, defaults to 125):
49
+ Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are
50
+ accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are
51
+ indexed from the end of the vocabulary up to beginning ("<extra_id_0>" is the last token in the vocabulary
52
+ like in ByT5 preprocessing see
53
+ [here](https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117)).
54
+ additional_special_tokens (`list[str]`, *optional*):
55
+ Additional special tokens used by the tokenizer.
56
+ """
57
+
58
+ model_input_names = ["input_ids", "attention_mask"]
59
+
60
+ def __init__(
61
+ self,
62
+ eos_token="</s>",
63
+ unk_token="<unk>",
64
+ pad_token="<pad>",
65
+ extra_ids=125,
66
+ additional_special_tokens=None,
67
+ **kwargs,
68
+ ) -> None:
69
+ # Add extra_ids to the special token list
70
+ if extra_ids > 0 and additional_special_tokens is None:
71
+ additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
72
+ elif extra_ids > 0 and additional_special_tokens is not None and len(additional_special_tokens) > 0:
73
+ # Check that we have the right number of extra_id special tokens
74
+ extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
75
+ if extra_tokens != extra_ids:
76
+ raise ValueError(
77
+ f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
78
+ " provided to ByT5Tokenizer. In this case the additional_special_tokens must include the"
79
+ " extra_ids tokens"
80
+ )
81
+
82
+ pad_token = AddedToken(pad_token, lstrip=True, rstrip=True) if isinstance(pad_token, str) else pad_token
83
+ # we force left and right stripping for backward compatibility. The byt5tests depend on this.
84
+ eos_token = AddedToken(eos_token, lstrip=True, rstrip=True) if isinstance(eos_token, str) else eos_token
85
+ unk_token = AddedToken(unk_token, lstrip=True, rstrip=True) if isinstance(unk_token, str) else unk_token
86
+ # unk token needs to be in the vocab with correct index
87
+ self._added_tokens_decoder = {0: pad_token, 1: eos_token, 2: unk_token}
88
+ self.offset = len(self._added_tokens_decoder)
89
+ self._utf_vocab_size = 2**8 # utf is 8 bits
90
+ super().__init__(
91
+ eos_token=eos_token,
92
+ unk_token=unk_token,
93
+ pad_token=pad_token,
94
+ extra_ids=0,
95
+ additional_special_tokens=additional_special_tokens, # TODO extra ids are not used :sweatywmile:
96
+ **kwargs,
97
+ )
98
+
99
+ @property
100
+ def vocab_size(self):
101
+ return self._utf_vocab_size
102
+
103
+ def get_vocab(self):
104
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.offset)}
105
+ vocab.update(self.added_tokens_encoder)
106
+ return vocab
107
+
108
+ def get_special_tokens_mask(
109
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
110
+ ) -> list[int]:
111
+ """
112
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
113
+ special tokens using the tokenizer `prepare_for_model` method.
114
+
115
+ Args:
116
+ token_ids_0 (`list[int]`):
117
+ List of IDs.
118
+ token_ids_1 (`list[int]`, *optional*):
119
+ Optional second list of IDs for sequence pairs.
120
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
121
+ Whether or not the token list is already formatted with special tokens for the model.
122
+
123
+ Returns:
124
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
125
+ """
126
+ if already_has_special_tokens:
127
+ return super().get_special_tokens_mask(
128
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
129
+ )
130
+
131
+ # normal case: some special tokens
132
+ if token_ids_1 is None:
133
+ return ([0] * len(token_ids_0)) + [1]
134
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
135
+
136
+ def _add_eos_if_not_present(self, token_ids: list[int]) -> list[int]:
137
+ """Do not add eos again if user already added it."""
138
+ if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
139
+ warnings.warn(
140
+ f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
141
+ " eos tokens being added."
142
+ )
143
+ return token_ids
144
+ else:
145
+ return token_ids + [self.eos_token_id]
146
+
147
+ def create_token_type_ids_from_sequences(
148
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
149
+ ) -> list[int]:
150
+ """
151
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. ByT5 does not
152
+ make use of token type ids, therefore a list of zeros is returned.
153
+
154
+ Args:
155
+ token_ids_0 (`list[int]`):
156
+ List of IDs.
157
+ token_ids_1 (`list[int]`, *optional*):
158
+ Optional second list of IDs for sequence pairs.
159
+
160
+ Returns:
161
+ `list[int]`: List of zeros.
162
+ """
163
+ eos = [self.eos_token_id]
164
+
165
+ if token_ids_1 is None:
166
+ return len(token_ids_0 + eos) * [0]
167
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
168
+
169
+ def build_inputs_with_special_tokens(
170
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
171
+ ) -> list[int]:
172
+ """
173
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
174
+ adding special tokens. A sequence has the following format:
175
+
176
+ - single sequence: `X </s>`
177
+ - pair of sequences: `A </s> B </s>`
178
+
179
+ Args:
180
+ token_ids_0 (`list[int]`):
181
+ List of IDs to which the special tokens will be added.
182
+ token_ids_1 (`list[int]`, *optional*):
183
+ Optional second list of IDs for sequence pairs.
184
+
185
+ Returns:
186
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
187
+ """
188
+ token_ids_0 = self._add_eos_if_not_present(token_ids_0)
189
+ if token_ids_1 is None:
190
+ return token_ids_0
191
+ else:
192
+ token_ids_1 = self._add_eos_if_not_present(token_ids_1)
193
+ return token_ids_0 + token_ids_1
194
+
195
+ def _tokenize(self, text: str) -> list[str]:
196
+ """Take as input a string and return a list of strings (tokens) for words/sub-words"""
197
+ tokens = [chr(i) for i in text.encode("utf-8")]
198
+ return tokens
199
+
200
+ def _convert_token_to_id(self, token):
201
+ """Converts a token (str) in an id using the vocab."""
202
+
203
+ if len(token) != 1:
204
+ token_id = None
205
+ else:
206
+ token_id = ord(token) + self.offset
207
+
208
+ return token_id
209
+
210
+ def _convert_id_to_token(self, index):
211
+ """Converts an index (integer) in a token (str) using the vocab."""
212
+ token = chr(index - self.offset)
213
+ return token
214
+
215
+ def convert_tokens_to_string(self, tokens):
216
+ """Converts a sequence of tokens (string) in a single string."""
217
+ bstring = b""
218
+ for token in tokens:
219
+ if token in self.added_tokens_decoder:
220
+ tok_string = self.added_tokens_decoder[token].encode("utf-8")
221
+ elif token in self.added_tokens_encoder:
222
+ tok_string = token.encode("utf-8")
223
+ else:
224
+ tok_string = bytes([ord(token)])
225
+ bstring += tok_string
226
+ string = bstring.decode("utf-8", errors="ignore")
227
+ return string
228
+
229
+ # ByT5Tokenizer has no vocab file
230
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
231
+ return ()
232
+
233
+
234
+ __all__ = ["ByT5Tokenizer"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/convnextv2/__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_convnextv2 import *
22
+ from .modeling_convnextv2 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__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/convnextv2/modeling_convnextv2.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Meta Platforms, Inc. 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
+ """PyTorch ConvNextV2 model."""
15
+
16
+ import torch
17
+ from torch import nn
18
+
19
+ from ... import initialization as init
20
+ from ...activations import ACT2FN
21
+ from ...backbone_utils import BackboneMixin, filter_output_hidden_states
22
+ from ...modeling_outputs import (
23
+ BackboneOutput,
24
+ BaseModelOutputWithNoAttention,
25
+ BaseModelOutputWithPoolingAndNoAttention,
26
+ ImageClassifierOutputWithNoAttention,
27
+ )
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...processing_utils import Unpack
30
+ from ...utils import TransformersKwargs, auto_docstring, logging
31
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
32
+ from ...utils.output_capturing import capture_outputs
33
+ from .configuration_convnextv2 import ConvNextV2Config
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ class ConvNextV2GRN(nn.Module):
40
+ """GRN (Global Response Normalization) layer"""
41
+
42
+ def __init__(self, dim: int):
43
+ super().__init__()
44
+ self.weight = nn.Parameter(torch.zeros(1, 1, 1, dim))
45
+ self.bias = nn.Parameter(torch.zeros(1, 1, 1, dim))
46
+
47
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
48
+ # Compute and normalize global spatial feature maps
49
+ global_features = torch.linalg.vector_norm(hidden_states, ord=2, dim=(1, 2), keepdim=True)
50
+ norm_features = global_features / (global_features.mean(dim=-1, keepdim=True) + 1e-6)
51
+ hidden_states = self.weight * (hidden_states * norm_features) + self.bias + hidden_states
52
+
53
+ return hidden_states
54
+
55
+
56
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextLayerNorm with ConvNext->ConvNextV2
57
+ class ConvNextV2LayerNorm(nn.LayerNorm):
58
+ r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
59
+ The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
60
+ width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
61
+ """
62
+
63
+ def __init__(self, normalized_shape, *, eps=1e-6, data_format="channels_last", **kwargs):
64
+ super().__init__(normalized_shape, eps=eps, **kwargs)
65
+ if data_format not in ["channels_last", "channels_first"]:
66
+ raise NotImplementedError(f"Unsupported data format: {data_format}")
67
+ self.data_format = data_format
68
+
69
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
70
+ """
71
+ Args:
72
+ features: Tensor of shape (batch_size, channels, height, width) OR (batch_size, height, width, channels)
73
+ """
74
+ if self.data_format == "channels_first":
75
+ features = features.permute(0, 2, 3, 1)
76
+ features = super().forward(features)
77
+ features = features.permute(0, 3, 1, 2)
78
+ else:
79
+ features = super().forward(features)
80
+ return features
81
+
82
+
83
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextEmbeddings with ConvNext->ConvNextV2
84
+ class ConvNextV2Embeddings(nn.Module):
85
+ """This class is comparable to (and inspired by) the SwinEmbeddings class
86
+ found in src/transformers/models/swin/modeling_swin.py.
87
+ """
88
+
89
+ def __init__(self, config):
90
+ super().__init__()
91
+ self.patch_embeddings = nn.Conv2d(
92
+ config.num_channels, config.hidden_sizes[0], kernel_size=config.patch_size, stride=config.patch_size
93
+ )
94
+ self.layernorm = ConvNextV2LayerNorm(config.hidden_sizes[0], eps=1e-6, data_format="channels_first")
95
+ self.num_channels = config.num_channels
96
+
97
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
98
+ num_channels = pixel_values.shape[1]
99
+ if num_channels != self.num_channels:
100
+ raise ValueError(
101
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
102
+ )
103
+ embeddings = self.patch_embeddings(pixel_values)
104
+ embeddings = self.layernorm(embeddings)
105
+ return embeddings
106
+
107
+
108
+ # Copied from transformers.models.swin.modular_swin.SwinDropPath with SwinDropPath->ConvNextV2DropPath
109
+ class ConvNextV2DropPath(nn.Module):
110
+ """Stochastic depth (DropPath) per sample, for residual blocks.
111
+
112
+ Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
113
+ <https://arxiv.org/abs/1603.09382>`_.
114
+ """
115
+
116
+ def __init__(self, drop_prob: float = 0.0) -> None:
117
+ super().__init__()
118
+ self.drop_prob = drop_prob
119
+
120
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
121
+ if self.drop_prob == 0.0 or not self.training:
122
+ return hidden_states
123
+ keep_prob = 1 - self.drop_prob
124
+ shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
125
+ random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
126
+ random_tensor = torch.floor(random_tensor + keep_prob)
127
+ return hidden_states.div(keep_prob) * random_tensor
128
+
129
+ def extra_repr(self) -> str:
130
+ return f"p={self.drop_prob}"
131
+
132
+
133
+ class ConvNextV2Layer(nn.Module):
134
+ """This corresponds to the `Block` class in the original implementation.
135
+
136
+ There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C,
137
+ H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Permute back
138
+
139
+ The authors used (2) as they find it slightly faster in PyTorch.
140
+
141
+ Args:
142
+ config ([`ConvNextV2Config`]): Model configuration class.
143
+ dim (`int`): Number of input channels.
144
+ drop_path (`float`): Stochastic depth rate. Default: 0.0.
145
+ """
146
+
147
+ def __init__(self, config, dim, drop_path=0):
148
+ super().__init__()
149
+ # depthwise conv
150
+ self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)
151
+ self.layernorm = ConvNextV2LayerNorm(dim, eps=1e-6)
152
+ # pointwise/1x1 convs, implemented with linear layers
153
+ self.pwconv1 = nn.Linear(dim, 4 * dim)
154
+ self.act = ACT2FN[config.hidden_act]
155
+ self.grn = ConvNextV2GRN(4 * dim)
156
+ self.pwconv2 = nn.Linear(4 * dim, dim)
157
+ self.drop_path = ConvNextV2DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
158
+
159
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
160
+ residual = features
161
+ features = self.dwconv(features)
162
+ # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
163
+ features = features.permute(0, 2, 3, 1)
164
+ features = self.layernorm(features)
165
+ features = self.pwconv1(features)
166
+ features = self.act(features)
167
+ features = self.grn(features)
168
+ features = self.pwconv2(features)
169
+ # (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
170
+ features = features.permute(0, 3, 1, 2)
171
+
172
+ features = residual + self.drop_path(features)
173
+ return features
174
+
175
+
176
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextStage with ConvNeXT->ConvNeXTV2, ConvNext->ConvNextV2
177
+ class ConvNextV2Stage(nn.Module):
178
+ """ConvNeXTV2 stage, consisting of an optional downsampling layer + multiple residual blocks.
179
+
180
+ Args:
181
+ config ([`ConvNextV2Config`]): Model configuration class.
182
+ in_channels (`int`): Number of input channels.
183
+ out_channels (`int`): Number of output channels.
184
+ depth (`int`): Number of residual blocks.
185
+ drop_path_rates(`list[float]`): Stochastic depth rates for each layer.
186
+ """
187
+
188
+ def __init__(self, config, in_channels, out_channels, kernel_size=2, stride=2, depth=2, drop_path_rates=None):
189
+ super().__init__()
190
+
191
+ if in_channels != out_channels or stride > 1:
192
+ self.downsampling_layer = nn.ModuleList(
193
+ [
194
+ ConvNextV2LayerNorm(in_channels, eps=1e-6, data_format="channels_first"),
195
+ nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride),
196
+ ]
197
+ )
198
+ else:
199
+ self.downsampling_layer = nn.ModuleList()
200
+ drop_path_rates = drop_path_rates or [0.0] * depth
201
+ self.layers = nn.ModuleList(
202
+ [ConvNextV2Layer(config, dim=out_channels, drop_path=drop_path_rates[j]) for j in range(depth)]
203
+ )
204
+
205
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
206
+ for layer in self.downsampling_layer:
207
+ features = layer(features)
208
+ for layer in self.layers:
209
+ features = layer(features)
210
+ return features
211
+
212
+
213
+ @auto_docstring
214
+ class ConvNextV2PreTrainedModel(PreTrainedModel):
215
+ config: ConvNextV2Config
216
+ base_model_prefix = "convnextv2"
217
+ main_input_name = "pixel_values"
218
+ input_modalities = ("image",)
219
+ _no_split_modules = ["ConvNextV2Layer"]
220
+
221
+ @torch.no_grad()
222
+ def _init_weights(self, module):
223
+ """Initialize the weights"""
224
+ super()._init_weights(module)
225
+ if isinstance(module, ConvNextV2GRN):
226
+ init.zeros_(module.weight)
227
+ init.zeros_(module.bias)
228
+
229
+
230
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextEncoder with CONVNEXT->CONVNEXTV2, ConvNext->ConvNextV2
231
+ class ConvNextV2Encoder(ConvNextV2PreTrainedModel):
232
+ main_input_name = "hidden_states"
233
+ _can_record_outputs = {"hidden_states": ConvNextV2Stage}
234
+
235
+ def __init__(self, config):
236
+ super().__init__(config)
237
+ self.stages = nn.ModuleList()
238
+ drop_path_rates = [
239
+ x.tolist()
240
+ for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu").split(config.depths)
241
+ ]
242
+ prev_chs = config.hidden_sizes[0]
243
+ for i in range(config.num_stages):
244
+ out_chs = config.hidden_sizes[i]
245
+ stage = ConvNextV2Stage(
246
+ config,
247
+ in_channels=prev_chs,
248
+ out_channels=out_chs,
249
+ stride=2 if i > 0 else 1,
250
+ depth=config.depths[i],
251
+ drop_path_rates=drop_path_rates[i],
252
+ )
253
+ self.stages.append(stage)
254
+ prev_chs = out_chs
255
+
256
+ self.post_init()
257
+
258
+ @merge_with_config_defaults
259
+ @capture_outputs(tie_last_hidden_states=False)
260
+ def forward(
261
+ self,
262
+ hidden_states: torch.Tensor,
263
+ **kwargs: Unpack[TransformersKwargs],
264
+ ) -> BaseModelOutputWithNoAttention:
265
+ for layer_module in self.stages:
266
+ hidden_states = layer_module(hidden_states)
267
+
268
+ return BaseModelOutputWithNoAttention(last_hidden_state=hidden_states)
269
+
270
+
271
+ @auto_docstring
272
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextModel with CONVNEXT->CONVNEXTV2, ConvNext->ConvNextV2
273
+ class ConvNextV2Model(ConvNextV2PreTrainedModel):
274
+ def __init__(self, config):
275
+ super().__init__(config)
276
+ self.config = config
277
+
278
+ self.embeddings = ConvNextV2Embeddings(config)
279
+ self.encoder = ConvNextV2Encoder(config)
280
+
281
+ # final layernorm layer
282
+ self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
283
+
284
+ # Initialize weights and apply final processing
285
+ self.post_init()
286
+
287
+ @can_return_tuple
288
+ @auto_docstring
289
+ def forward(
290
+ self, pixel_values: torch.FloatTensor | None = None, **kwargs: Unpack[TransformersKwargs]
291
+ ) -> BaseModelOutputWithPoolingAndNoAttention:
292
+ if pixel_values is None:
293
+ raise ValueError("You have to specify pixel_values")
294
+
295
+ embedding_output = self.embeddings(pixel_values)
296
+ encoder_outputs: BaseModelOutputWithNoAttention = self.encoder(embedding_output, **kwargs)
297
+ last_hidden_state = encoder_outputs.last_hidden_state
298
+
299
+ # global average pooling, (N, C, H, W) -> (N, C)
300
+ pooled_output = self.layernorm(last_hidden_state.mean([-2, -1]))
301
+
302
+ return BaseModelOutputWithPoolingAndNoAttention(
303
+ last_hidden_state=last_hidden_state,
304
+ pooler_output=pooled_output,
305
+ hidden_states=encoder_outputs.hidden_states,
306
+ )
307
+
308
+
309
+ @auto_docstring(
310
+ custom_intro="""
311
+ ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
312
+ ImageNet.
313
+ """
314
+ )
315
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextForImageClassification with CONVNEXT->CONVNEXTV2,ConvNext->ConvNextV2,convnext->convnextv2
316
+ class ConvNextV2ForImageClassification(ConvNextV2PreTrainedModel):
317
+ accepts_loss_kwargs = False
318
+
319
+ def __init__(self, config):
320
+ super().__init__(config)
321
+
322
+ self.num_labels = config.num_labels
323
+ self.convnextv2 = ConvNextV2Model(config)
324
+
325
+ # Classifier head
326
+ if config.num_labels > 0:
327
+ self.classifier = nn.Linear(config.hidden_sizes[-1], config.num_labels)
328
+ else:
329
+ self.classifier = nn.Identity()
330
+
331
+ # Initialize weights and apply final processing
332
+ self.post_init()
333
+
334
+ @can_return_tuple
335
+ @auto_docstring
336
+ def forward(
337
+ self, pixel_values: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, **kwargs
338
+ ) -> ImageClassifierOutputWithNoAttention:
339
+ r"""
340
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
341
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
342
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
343
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
344
+ """
345
+ outputs: BaseModelOutputWithPoolingAndNoAttention = self.convnextv2(pixel_values, **kwargs)
346
+ pooled_output = outputs.pooler_output
347
+ logits = self.classifier(pooled_output)
348
+
349
+ loss = None
350
+ if labels is not None:
351
+ loss = self.loss_function(labels=labels, pooled_logits=logits, config=self.config)
352
+
353
+ return ImageClassifierOutputWithNoAttention(
354
+ loss=loss,
355
+ logits=logits,
356
+ hidden_states=outputs.hidden_states,
357
+ )
358
+
359
+
360
+ @auto_docstring(
361
+ custom_intro="""
362
+ ConvNeXT V2 backbone, to be used with frameworks like DETR and MaskFormer.
363
+ """
364
+ )
365
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextBackbone with CONVNEXT->CONVNEXTV2,ConvNext->ConvNextV2,facebook/convnext-tiny-224->facebook/convnextv2-tiny-1k-224
366
+ class ConvNextV2Backbone(BackboneMixin, ConvNextV2PreTrainedModel):
367
+ has_attentions = False
368
+
369
+ def __init__(self, config):
370
+ super().__init__(config)
371
+
372
+ self.embeddings = ConvNextV2Embeddings(config)
373
+ self.encoder = ConvNextV2Encoder(config)
374
+ self.num_features = [config.hidden_sizes[0]] + config.hidden_sizes
375
+
376
+ # Add layer norms to hidden states of out_features
377
+ hidden_states_norms = {}
378
+ for stage, num_channels in zip(self.out_features, self.channels):
379
+ hidden_states_norms[stage] = ConvNextV2LayerNorm(num_channels, data_format="channels_first")
380
+ self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
381
+
382
+ # initialize weights and apply final processing
383
+ self.post_init()
384
+
385
+ @can_return_tuple
386
+ @filter_output_hidden_states
387
+ @auto_docstring
388
+ def forward(
389
+ self,
390
+ pixel_values: torch.Tensor,
391
+ **kwargs: Unpack[TransformersKwargs],
392
+ ) -> BackboneOutput:
393
+ r"""
394
+ Examples:
395
+
396
+ ```python
397
+ >>> from transformers import AutoImageProcessor, AutoBackbone
398
+ >>> import torch
399
+ >>> from PIL import Image
400
+ >>> import httpx
401
+ >>> from io import BytesIO
402
+
403
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
404
+ >>> with httpx.stream("GET", url) as response:
405
+ ... image = Image.open(BytesIO(response.read()))
406
+
407
+ >>> processor = AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224")
408
+ >>> model = AutoBackbone.from_pretrained("facebook/convnextv2-tiny-1k-224")
409
+
410
+ >>> inputs = processor(image, return_tensors="pt")
411
+ >>> outputs = model(**inputs)
412
+ ```"""
413
+ kwargs["output_hidden_states"] = True # required to extract layers for the stages
414
+
415
+ embedding_output = self.embeddings(pixel_values)
416
+ encoder_outputs: BaseModelOutputWithNoAttention = self.encoder(embedding_output, **kwargs)
417
+ hidden_states = encoder_outputs.hidden_states
418
+
419
+ feature_maps = []
420
+ for stage, hidden_state in zip(self.stage_names, hidden_states):
421
+ if stage in self.out_features:
422
+ hidden_state = self.hidden_states_norms[stage](hidden_state)
423
+ feature_maps.append(hidden_state)
424
+
425
+ return BackboneOutput(feature_maps=tuple(feature_maps), hidden_states=hidden_states)
426
+
427
+
428
+ __all__ = ["ConvNextV2ForImageClassification", "ConvNextV2Model", "ConvNextV2PreTrainedModel", "ConvNextV2Backbone"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/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_pil_levit 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__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/levit/modeling_levit.py ADDED
@@ -0,0 +1,665 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Meta Platforms, Inc. 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
+ """PyTorch LeViT model."""
15
+
16
+ import itertools
17
+ from dataclasses import dataclass
18
+
19
+ import torch
20
+ from torch import nn
21
+
22
+ from ... import initialization as init
23
+ from ...modeling_outputs import (
24
+ BaseModelOutputWithNoAttention,
25
+ BaseModelOutputWithPoolingAndNoAttention,
26
+ ImageClassifierOutputWithNoAttention,
27
+ ModelOutput,
28
+ )
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import auto_docstring, logging
31
+ from .configuration_levit import LevitConfig
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ @auto_docstring(
38
+ custom_intro="""
39
+ Output type of [`LevitForImageClassificationWithTeacher`].
40
+ """
41
+ )
42
+ @dataclass
43
+ class LevitForImageClassificationWithTeacherOutput(ModelOutput):
44
+ r"""
45
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
46
+ Prediction scores as the average of the `cls_logits` and `distillation_logits`.
47
+ cls_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
48
+ Prediction scores of the classification head (i.e. the linear layer on top of the final hidden state of the
49
+ class token).
50
+ distillation_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
51
+ Prediction scores of the distillation head (i.e. the linear layer on top of the final hidden state of the
52
+ distillation token).
53
+ """
54
+
55
+ logits: torch.FloatTensor | None = None
56
+ cls_logits: torch.FloatTensor | None = None
57
+ distillation_logits: torch.FloatTensor | None = None
58
+ hidden_states: tuple[torch.FloatTensor] | None = None
59
+
60
+
61
+ class LevitConvEmbeddings(nn.Module):
62
+ """
63
+ LeViT Conv Embeddings with Batch Norm, used in the initial patch embedding layer.
64
+ """
65
+
66
+ def __init__(
67
+ self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, groups=1, bn_weight_init=1
68
+ ):
69
+ super().__init__()
70
+ self.convolution = nn.Conv2d(
71
+ in_channels, out_channels, kernel_size, stride, padding, dilation=dilation, groups=groups, bias=False
72
+ )
73
+ self.batch_norm = nn.BatchNorm2d(out_channels)
74
+
75
+ def forward(self, embeddings):
76
+ embeddings = self.convolution(embeddings)
77
+ embeddings = self.batch_norm(embeddings)
78
+ return embeddings
79
+
80
+
81
+ class LevitPatchEmbeddings(nn.Module):
82
+ """
83
+ LeViT patch embeddings, for final embeddings to be passed to transformer blocks. It consists of multiple
84
+ `LevitConvEmbeddings`.
85
+ """
86
+
87
+ def __init__(self, config):
88
+ super().__init__()
89
+ self.embedding_layer_1 = LevitConvEmbeddings(
90
+ config.num_channels, config.hidden_sizes[0] // 8, config.kernel_size, config.stride, config.padding
91
+ )
92
+ self.activation_layer_1 = nn.Hardswish()
93
+
94
+ self.embedding_layer_2 = LevitConvEmbeddings(
95
+ config.hidden_sizes[0] // 8, config.hidden_sizes[0] // 4, config.kernel_size, config.stride, config.padding
96
+ )
97
+ self.activation_layer_2 = nn.Hardswish()
98
+
99
+ self.embedding_layer_3 = LevitConvEmbeddings(
100
+ config.hidden_sizes[0] // 4, config.hidden_sizes[0] // 2, config.kernel_size, config.stride, config.padding
101
+ )
102
+ self.activation_layer_3 = nn.Hardswish()
103
+
104
+ self.embedding_layer_4 = LevitConvEmbeddings(
105
+ config.hidden_sizes[0] // 2, config.hidden_sizes[0], config.kernel_size, config.stride, config.padding
106
+ )
107
+ self.num_channels = config.num_channels
108
+
109
+ def forward(self, pixel_values):
110
+ num_channels = pixel_values.shape[1]
111
+ if num_channels != self.num_channels:
112
+ raise ValueError(
113
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
114
+ )
115
+ embeddings = self.embedding_layer_1(pixel_values)
116
+ embeddings = self.activation_layer_1(embeddings)
117
+ embeddings = self.embedding_layer_2(embeddings)
118
+ embeddings = self.activation_layer_2(embeddings)
119
+ embeddings = self.embedding_layer_3(embeddings)
120
+ embeddings = self.activation_layer_3(embeddings)
121
+ embeddings = self.embedding_layer_4(embeddings)
122
+ return embeddings.flatten(2).transpose(1, 2)
123
+
124
+
125
+ class MLPLayerWithBN(nn.Module):
126
+ def __init__(self, input_dim, output_dim, bn_weight_init=1):
127
+ super().__init__()
128
+ self.linear = nn.Linear(in_features=input_dim, out_features=output_dim, bias=False)
129
+ self.batch_norm = nn.BatchNorm1d(output_dim)
130
+
131
+ def forward(self, hidden_state):
132
+ hidden_state = self.linear(hidden_state)
133
+ hidden_state = self.batch_norm(hidden_state.flatten(0, 1)).reshape_as(hidden_state)
134
+ return hidden_state
135
+
136
+
137
+ class LevitSubsample(nn.Module):
138
+ def __init__(self, stride, resolution):
139
+ super().__init__()
140
+ self.stride = stride
141
+ self.resolution = resolution
142
+
143
+ def forward(self, hidden_state):
144
+ batch_size, _, channels = hidden_state.shape
145
+ hidden_state = hidden_state.view(batch_size, self.resolution, self.resolution, channels)[
146
+ :, :: self.stride, :: self.stride
147
+ ].reshape(batch_size, -1, channels)
148
+ return hidden_state
149
+
150
+
151
+ class LevitAttention(nn.Module):
152
+ def __init__(self, hidden_sizes, key_dim, num_attention_heads, attention_ratio, resolution):
153
+ super().__init__()
154
+ self.num_attention_heads = num_attention_heads
155
+ self.scale = key_dim**-0.5
156
+ self.key_dim = key_dim
157
+ self.attention_ratio = attention_ratio
158
+ self.out_dim_keys_values = attention_ratio * key_dim * num_attention_heads + key_dim * num_attention_heads * 2
159
+ self.out_dim_projection = attention_ratio * key_dim * num_attention_heads
160
+
161
+ self.queries_keys_values = MLPLayerWithBN(hidden_sizes, self.out_dim_keys_values)
162
+ self.activation = nn.Hardswish()
163
+ self.projection = MLPLayerWithBN(self.out_dim_projection, hidden_sizes, bn_weight_init=0)
164
+
165
+ points = list(itertools.product(range(resolution), range(resolution)))
166
+ len_points = len(points)
167
+ self.len_points = len_points
168
+ attention_offsets, indices = {}, []
169
+ for p1 in points:
170
+ for p2 in points:
171
+ offset = (abs(p1[0] - p2[0]), abs(p1[1] - p2[1]))
172
+ if offset not in attention_offsets:
173
+ attention_offsets[offset] = len(attention_offsets)
174
+ indices.append(attention_offsets[offset])
175
+ self.indices = indices
176
+
177
+ self.attention_bias_cache = {}
178
+ self.attention_biases = torch.nn.Parameter(torch.zeros(num_attention_heads, len(attention_offsets)))
179
+ self.register_buffer(
180
+ "attention_bias_idxs", torch.LongTensor(indices).view(len_points, len_points), persistent=False
181
+ )
182
+
183
+ @torch.no_grad()
184
+ def train(self, mode=True):
185
+ super().train(mode)
186
+ if mode and self.attention_bias_cache:
187
+ self.attention_bias_cache = {} # clear ab cache
188
+
189
+ def get_attention_biases(self, device):
190
+ if self.training:
191
+ return self.attention_biases[:, self.attention_bias_idxs]
192
+ else:
193
+ device_key = str(device)
194
+ if device_key not in self.attention_bias_cache:
195
+ self.attention_bias_cache[device_key] = self.attention_biases[:, self.attention_bias_idxs]
196
+ return self.attention_bias_cache[device_key]
197
+
198
+ def forward(self, hidden_state):
199
+ batch_size, seq_length, _ = hidden_state.shape
200
+ queries_keys_values = self.queries_keys_values(hidden_state)
201
+ query, key, value = queries_keys_values.view(batch_size, seq_length, self.num_attention_heads, -1).split(
202
+ [self.key_dim, self.key_dim, self.attention_ratio * self.key_dim], dim=3
203
+ )
204
+ query = query.permute(0, 2, 1, 3)
205
+ key = key.permute(0, 2, 1, 3)
206
+ value = value.permute(0, 2, 1, 3)
207
+
208
+ attention = query @ key.transpose(-2, -1) * self.scale + self.get_attention_biases(hidden_state.device)
209
+ attention = attention.softmax(dim=-1)
210
+ hidden_state = (attention @ value).transpose(1, 2).reshape(batch_size, seq_length, self.out_dim_projection)
211
+ hidden_state = self.projection(self.activation(hidden_state))
212
+ return hidden_state
213
+
214
+
215
+ class LevitAttentionSubsample(nn.Module):
216
+ def __init__(
217
+ self,
218
+ input_dim,
219
+ output_dim,
220
+ key_dim,
221
+ num_attention_heads,
222
+ attention_ratio,
223
+ stride,
224
+ resolution_in,
225
+ resolution_out,
226
+ ):
227
+ super().__init__()
228
+ self.num_attention_heads = num_attention_heads
229
+ self.scale = key_dim**-0.5
230
+ self.key_dim = key_dim
231
+ self.attention_ratio = attention_ratio
232
+ self.out_dim_keys_values = attention_ratio * key_dim * num_attention_heads + key_dim * num_attention_heads
233
+ self.out_dim_projection = attention_ratio * key_dim * num_attention_heads
234
+ self.resolution_out = resolution_out
235
+ # resolution_in is the initial resolution, resolution_out is final resolution after downsampling
236
+ self.keys_values = MLPLayerWithBN(input_dim, self.out_dim_keys_values)
237
+ self.queries_subsample = LevitSubsample(stride, resolution_in)
238
+ self.queries = MLPLayerWithBN(input_dim, key_dim * num_attention_heads)
239
+ self.activation = nn.Hardswish()
240
+ self.projection = MLPLayerWithBN(self.out_dim_projection, output_dim)
241
+
242
+ self.attention_bias_cache = {}
243
+
244
+ points = list(itertools.product(range(resolution_in), range(resolution_in)))
245
+ points_ = list(itertools.product(range(resolution_out), range(resolution_out)))
246
+ len_points, len_points_ = len(points), len(points_)
247
+ self.len_points_ = len_points_
248
+ self.len_points = len_points
249
+ attention_offsets, indices = {}, []
250
+ for p1 in points_:
251
+ for p2 in points:
252
+ size = 1
253
+ offset = (abs(p1[0] * stride - p2[0] + (size - 1) / 2), abs(p1[1] * stride - p2[1] + (size - 1) / 2))
254
+ if offset not in attention_offsets:
255
+ attention_offsets[offset] = len(attention_offsets)
256
+ indices.append(attention_offsets[offset])
257
+ self.indices = indices
258
+
259
+ self.attention_biases = torch.nn.Parameter(torch.zeros(num_attention_heads, len(attention_offsets)))
260
+ self.register_buffer(
261
+ "attention_bias_idxs", torch.LongTensor(indices).view(len_points_, len_points), persistent=False
262
+ )
263
+
264
+ @torch.no_grad()
265
+ def train(self, mode=True):
266
+ super().train(mode)
267
+ if mode and self.attention_bias_cache:
268
+ self.attention_bias_cache = {} # clear ab cache
269
+
270
+ def get_attention_biases(self, device):
271
+ if self.training:
272
+ return self.attention_biases[:, self.attention_bias_idxs]
273
+ else:
274
+ device_key = str(device)
275
+ if device_key not in self.attention_bias_cache:
276
+ self.attention_bias_cache[device_key] = self.attention_biases[:, self.attention_bias_idxs]
277
+ return self.attention_bias_cache[device_key]
278
+
279
+ def forward(self, hidden_state):
280
+ batch_size, seq_length, _ = hidden_state.shape
281
+ key, value = (
282
+ self.keys_values(hidden_state)
283
+ .view(batch_size, seq_length, self.num_attention_heads, -1)
284
+ .split([self.key_dim, self.attention_ratio * self.key_dim], dim=3)
285
+ )
286
+ key = key.permute(0, 2, 1, 3)
287
+ value = value.permute(0, 2, 1, 3)
288
+
289
+ query = self.queries(self.queries_subsample(hidden_state))
290
+ query = query.view(batch_size, self.resolution_out**2, self.num_attention_heads, self.key_dim).permute(
291
+ 0, 2, 1, 3
292
+ )
293
+
294
+ attention = query @ key.transpose(-2, -1) * self.scale + self.get_attention_biases(hidden_state.device)
295
+ attention = attention.softmax(dim=-1)
296
+ hidden_state = (attention @ value).transpose(1, 2).reshape(batch_size, -1, self.out_dim_projection)
297
+ hidden_state = self.projection(self.activation(hidden_state))
298
+ return hidden_state
299
+
300
+
301
+ class LevitMLPLayer(nn.Module):
302
+ """
303
+ MLP Layer with `2X` expansion in contrast to ViT with `4X`.
304
+ """
305
+
306
+ def __init__(self, input_dim, hidden_dim):
307
+ super().__init__()
308
+ self.linear_up = MLPLayerWithBN(input_dim, hidden_dim)
309
+ self.activation = nn.Hardswish()
310
+ self.linear_down = MLPLayerWithBN(hidden_dim, input_dim)
311
+
312
+ def forward(self, hidden_state):
313
+ hidden_state = self.linear_up(hidden_state)
314
+ hidden_state = self.activation(hidden_state)
315
+ hidden_state = self.linear_down(hidden_state)
316
+ return hidden_state
317
+
318
+
319
+ class LevitResidualLayer(nn.Module):
320
+ """
321
+ Residual Block for LeViT
322
+ """
323
+
324
+ def __init__(self, module, drop_rate):
325
+ super().__init__()
326
+ self.module = module
327
+ self.drop_rate = drop_rate
328
+
329
+ def forward(self, hidden_state):
330
+ if self.training and self.drop_rate > 0:
331
+ rnd = torch.rand(hidden_state.size(0), 1, 1, device=hidden_state.device)
332
+ rnd = rnd.ge_(self.drop_rate).div(1 - self.drop_rate).detach()
333
+ hidden_state = hidden_state + self.module(hidden_state) * rnd
334
+ return hidden_state
335
+ else:
336
+ hidden_state = hidden_state + self.module(hidden_state)
337
+ return hidden_state
338
+
339
+
340
+ class LevitStage(nn.Module):
341
+ """
342
+ LeViT Stage consisting of `LevitMLPLayer` and `LevitAttention` layers.
343
+ """
344
+
345
+ def __init__(
346
+ self,
347
+ config,
348
+ idx,
349
+ hidden_sizes,
350
+ key_dim,
351
+ depths,
352
+ num_attention_heads,
353
+ attention_ratio,
354
+ mlp_ratio,
355
+ down_ops,
356
+ resolution_in,
357
+ ):
358
+ super().__init__()
359
+ self.layers = []
360
+ self.config = config
361
+ self.resolution_in = resolution_in
362
+ # resolution_in is the initial resolution, resolution_out is final resolution after downsampling
363
+ for _ in range(depths):
364
+ self.layers.append(
365
+ LevitResidualLayer(
366
+ LevitAttention(hidden_sizes, key_dim, num_attention_heads, attention_ratio, resolution_in),
367
+ self.config.drop_path_rate,
368
+ )
369
+ )
370
+ if mlp_ratio > 0:
371
+ hidden_dim = hidden_sizes * mlp_ratio
372
+ self.layers.append(
373
+ LevitResidualLayer(LevitMLPLayer(hidden_sizes, hidden_dim), self.config.drop_path_rate)
374
+ )
375
+
376
+ if down_ops[0] == "Subsample":
377
+ self.resolution_out = (self.resolution_in - 1) // down_ops[5] + 1
378
+ self.layers.append(
379
+ LevitAttentionSubsample(
380
+ *self.config.hidden_sizes[idx : idx + 2],
381
+ key_dim=down_ops[1],
382
+ num_attention_heads=down_ops[2],
383
+ attention_ratio=down_ops[3],
384
+ stride=down_ops[5],
385
+ resolution_in=resolution_in,
386
+ resolution_out=self.resolution_out,
387
+ )
388
+ )
389
+ self.resolution_in = self.resolution_out
390
+ if down_ops[4] > 0:
391
+ hidden_dim = self.config.hidden_sizes[idx + 1] * down_ops[4]
392
+ self.layers.append(
393
+ LevitResidualLayer(
394
+ LevitMLPLayer(self.config.hidden_sizes[idx + 1], hidden_dim), self.config.drop_path_rate
395
+ )
396
+ )
397
+
398
+ self.layers = nn.ModuleList(self.layers)
399
+
400
+ def get_resolution(self):
401
+ return self.resolution_in
402
+
403
+ def forward(self, hidden_state):
404
+ for layer in self.layers:
405
+ hidden_state = layer(hidden_state)
406
+ return hidden_state
407
+
408
+
409
+ class LevitEncoder(nn.Module):
410
+ """
411
+ LeViT Encoder consisting of multiple `LevitStage` stages.
412
+ """
413
+
414
+ def __init__(self, config):
415
+ super().__init__()
416
+ self.config = config
417
+ resolution = self.config.image_size // self.config.patch_size
418
+ self.stages = []
419
+ self.config.down_ops.append([""])
420
+
421
+ for stage_idx in range(len(config.depths)):
422
+ stage = LevitStage(
423
+ config,
424
+ stage_idx,
425
+ config.hidden_sizes[stage_idx],
426
+ config.key_dim[stage_idx],
427
+ config.depths[stage_idx],
428
+ config.num_attention_heads[stage_idx],
429
+ config.attention_ratio[stage_idx],
430
+ config.mlp_ratio[stage_idx],
431
+ config.down_ops[stage_idx],
432
+ resolution,
433
+ )
434
+ resolution = stage.get_resolution()
435
+ self.stages.append(stage)
436
+
437
+ self.stages = nn.ModuleList(self.stages)
438
+
439
+ def forward(self, hidden_state, output_hidden_states=False, return_dict=True):
440
+ all_hidden_states = () if output_hidden_states else None
441
+
442
+ for stage in self.stages:
443
+ if output_hidden_states:
444
+ all_hidden_states = all_hidden_states + (hidden_state,)
445
+ hidden_state = stage(hidden_state)
446
+
447
+ if output_hidden_states:
448
+ all_hidden_states = all_hidden_states + (hidden_state,)
449
+ if not return_dict:
450
+ return tuple(v for v in [hidden_state, all_hidden_states] if v is not None)
451
+
452
+ return BaseModelOutputWithNoAttention(last_hidden_state=hidden_state, hidden_states=all_hidden_states)
453
+
454
+
455
+ class LevitClassificationLayer(nn.Module):
456
+ """
457
+ LeViT Classification Layer
458
+ """
459
+
460
+ def __init__(self, input_dim, output_dim):
461
+ super().__init__()
462
+ self.batch_norm = nn.BatchNorm1d(input_dim)
463
+ self.linear = nn.Linear(input_dim, output_dim)
464
+
465
+ def forward(self, hidden_state):
466
+ hidden_state = self.batch_norm(hidden_state)
467
+ logits = self.linear(hidden_state)
468
+ return logits
469
+
470
+
471
+ @auto_docstring
472
+ class LevitPreTrainedModel(PreTrainedModel):
473
+ config: LevitConfig
474
+ base_model_prefix = "levit"
475
+ main_input_name = "pixel_values"
476
+ input_modalities = ("image",)
477
+ _no_split_modules = ["LevitResidualLayer"]
478
+
479
+ def _init_weights(self, module):
480
+ super()._init_weights(module)
481
+ if isinstance(module, LevitAttention):
482
+ init.copy_(
483
+ module.attention_bias_idxs, torch.LongTensor(module.indices).view(module.len_points, module.len_points)
484
+ )
485
+ elif isinstance(module, LevitAttentionSubsample):
486
+ init.copy_(
487
+ module.attention_bias_idxs,
488
+ torch.LongTensor(module.indices).view(module.len_points_, module.len_points),
489
+ )
490
+
491
+
492
+ @auto_docstring
493
+ class LevitModel(LevitPreTrainedModel):
494
+ def __init__(self, config):
495
+ super().__init__(config)
496
+ self.config = config
497
+ self.patch_embeddings = LevitPatchEmbeddings(config)
498
+ self.encoder = LevitEncoder(config)
499
+ # Initialize weights and apply final processing
500
+ self.post_init()
501
+
502
+ @auto_docstring
503
+ def forward(
504
+ self,
505
+ pixel_values: torch.FloatTensor | None = None,
506
+ output_hidden_states: bool | None = None,
507
+ return_dict: bool | None = None,
508
+ **kwargs,
509
+ ) -> tuple | BaseModelOutputWithPoolingAndNoAttention:
510
+ output_hidden_states = (
511
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
512
+ )
513
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
514
+
515
+ if pixel_values is None:
516
+ raise ValueError("You have to specify pixel_values")
517
+
518
+ embeddings = self.patch_embeddings(pixel_values)
519
+ encoder_outputs = self.encoder(
520
+ embeddings,
521
+ output_hidden_states=output_hidden_states,
522
+ return_dict=return_dict,
523
+ )
524
+
525
+ last_hidden_state = encoder_outputs[0]
526
+
527
+ # global average pooling, (batch_size, seq_length, hidden_sizes) -> (batch_size, hidden_sizes)
528
+ pooled_output = last_hidden_state.mean(dim=1)
529
+
530
+ if not return_dict:
531
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
532
+
533
+ return BaseModelOutputWithPoolingAndNoAttention(
534
+ last_hidden_state=last_hidden_state,
535
+ pooler_output=pooled_output,
536
+ hidden_states=encoder_outputs.hidden_states,
537
+ )
538
+
539
+
540
+ @auto_docstring(
541
+ custom_intro="""
542
+ Levit Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
543
+ ImageNet.
544
+ """
545
+ )
546
+ class LevitForImageClassification(LevitPreTrainedModel):
547
+ def __init__(self, config):
548
+ super().__init__(config)
549
+ self.config = config
550
+ self.num_labels = config.num_labels
551
+ self.levit = LevitModel(config)
552
+
553
+ # Classifier head
554
+ self.classifier = (
555
+ LevitClassificationLayer(config.hidden_sizes[-1], config.num_labels)
556
+ if config.num_labels > 0
557
+ else torch.nn.Identity()
558
+ )
559
+
560
+ # Initialize weights and apply final processing
561
+ self.post_init()
562
+
563
+ @auto_docstring
564
+ def forward(
565
+ self,
566
+ pixel_values: torch.FloatTensor | None = None,
567
+ labels: torch.LongTensor | None = None,
568
+ output_hidden_states: bool | None = None,
569
+ return_dict: bool | None = None,
570
+ **kwargs,
571
+ ) -> tuple | ImageClassifierOutputWithNoAttention:
572
+ r"""
573
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
574
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
575
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
576
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
577
+ """
578
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
579
+
580
+ outputs = self.levit(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
581
+
582
+ sequence_output = outputs[0]
583
+ sequence_output = sequence_output.mean(1)
584
+ logits = self.classifier(sequence_output)
585
+
586
+ loss = None
587
+ if labels is not None:
588
+ loss = self.loss_function(labels, logits, self.config)
589
+
590
+ if not return_dict:
591
+ output = (logits,) + outputs[2:]
592
+ return ((loss,) + output) if loss is not None else output
593
+
594
+ return ImageClassifierOutputWithNoAttention(
595
+ loss=loss,
596
+ logits=logits,
597
+ hidden_states=outputs.hidden_states,
598
+ )
599
+
600
+
601
+ @auto_docstring(
602
+ custom_intro="""
603
+ LeViT Model transformer with image classification heads on top (a linear layer on top of the final hidden state and
604
+ a linear layer on top of the final hidden state of the distillation token) e.g. for ImageNet. .. warning::
605
+ This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet
606
+ supported.
607
+ """
608
+ )
609
+ class LevitForImageClassificationWithTeacher(LevitPreTrainedModel):
610
+ def __init__(self, config):
611
+ super().__init__(config)
612
+ self.config = config
613
+ self.num_labels = config.num_labels
614
+ self.levit = LevitModel(config)
615
+
616
+ # Classifier head
617
+ self.classifier = (
618
+ LevitClassificationLayer(config.hidden_sizes[-1], config.num_labels)
619
+ if config.num_labels > 0
620
+ else torch.nn.Identity()
621
+ )
622
+ self.classifier_distill = (
623
+ LevitClassificationLayer(config.hidden_sizes[-1], config.num_labels)
624
+ if config.num_labels > 0
625
+ else torch.nn.Identity()
626
+ )
627
+
628
+ # Initialize weights and apply final processing
629
+ self.post_init()
630
+
631
+ @auto_docstring
632
+ def forward(
633
+ self,
634
+ pixel_values: torch.FloatTensor | None = None,
635
+ output_hidden_states: bool | None = None,
636
+ return_dict: bool | None = None,
637
+ **kwargs,
638
+ ) -> tuple | LevitForImageClassificationWithTeacherOutput:
639
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
640
+
641
+ outputs = self.levit(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
642
+
643
+ sequence_output = outputs[0]
644
+ sequence_output = sequence_output.mean(1)
645
+ cls_logits, distill_logits = self.classifier(sequence_output), self.classifier_distill(sequence_output)
646
+ logits = (cls_logits + distill_logits) / 2
647
+
648
+ if not return_dict:
649
+ output = (logits, cls_logits, distill_logits) + outputs[2:]
650
+ return output
651
+
652
+ return LevitForImageClassificationWithTeacherOutput(
653
+ logits=logits,
654
+ cls_logits=cls_logits,
655
+ distillation_logits=distill_logits,
656
+ hidden_states=outputs.hidden_states,
657
+ )
658
+
659
+
660
+ __all__ = [
661
+ "LevitForImageClassification",
662
+ "LevitForImageClassificationWithTeacher",
663
+ "LevitModel",
664
+ "LevitPreTrainedModel",
665
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/megatron_gpt2/__init__.py ADDED
File without changes
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/megatron_gpt2/checkpoint_reshaping_and_interoperability.py ADDED
@@ -0,0 +1,925 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import argparse
16
+ import importlib.util
17
+ import json
18
+ import os
19
+ import re
20
+ import sys
21
+ import types
22
+
23
+ import torch
24
+ from huggingface_hub import split_torch_state_dict_into_shards
25
+ from packaging import version
26
+
27
+ from transformers import AutoTokenizer, GPT2Config
28
+ from transformers.modeling_utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME
29
+ from transformers.utils import check_torch_load_is_safe
30
+
31
+
32
+ def add_checkpointing_args(parser):
33
+ parser.add_argument("--megatron-path", type=str, default=None, help="Base directory of Megatron repository")
34
+ parser.add_argument(
35
+ "--convert_checkpoint_from_megatron_to_transformers",
36
+ action="store_true",
37
+ help=(
38
+ "If True, convert a Megatron checkpoint to a Transformers checkpoint. "
39
+ "If False, convert a Transformers checkpoint to a Megatron checkpoint."
40
+ ),
41
+ )
42
+ parser.add_argument(
43
+ "--load_path",
44
+ type=str,
45
+ required=True,
46
+ help="Path to the checkpoint to convert.",
47
+ )
48
+ parser.add_argument(
49
+ "--save_path",
50
+ type=str,
51
+ required=True,
52
+ help="Path to the converted checkpoint.",
53
+ )
54
+ parser.add_argument("--print-checkpoint-structure", action="store_true")
55
+ return parser
56
+
57
+
58
+ def add_megatron_checkpoint_args(parser):
59
+ parser.add_argument(
60
+ "--target_tensor_model_parallel_size",
61
+ type=int,
62
+ default=1,
63
+ help=(
64
+ "The tensor model parallel size of the converted checkpoint. "
65
+ "Only used when converting a Transformers checkpoint to a Megatron checkpoint."
66
+ ),
67
+ )
68
+ parser.add_argument(
69
+ "--target_pipeline_model_parallel_size",
70
+ type=int,
71
+ default=1,
72
+ help=(
73
+ "The pipeline model parallel size of the converted checkpoint. "
74
+ "Only used when converting a Transformers checkpoint to a Megatron checkpoint."
75
+ ),
76
+ )
77
+ parser.add_argument(
78
+ "--target_data_parallel_size",
79
+ type=int,
80
+ default=1,
81
+ help=(
82
+ "The data parallel size of the converted checkpoint. "
83
+ "Only used when converting a Transformers checkpoint to a Megatron checkpoint."
84
+ ),
85
+ )
86
+ parser.add_argument(
87
+ "--target_params_dtype",
88
+ type=str,
89
+ default="fp32",
90
+ help=(
91
+ "The dtype of the converted checkpoint. "
92
+ "Only used when converting a Transformers checkpoint to a Megatron checkpoint."
93
+ ),
94
+ )
95
+ parser.add_argument(
96
+ "--make_vocab_size_divisible_by",
97
+ type=int,
98
+ default=128,
99
+ help=(
100
+ "Pad the vocab size to be divisible by this value. "
101
+ "This is added for computational efficiency reasons. "
102
+ "Only used when converting a Transformers checkpoint to a Megatron checkpoint."
103
+ ),
104
+ )
105
+ parser.add_argument(
106
+ "--use_distributed_optimizer",
107
+ action="store_true",
108
+ help=(
109
+ "If True, use the distributed optimizer. "
110
+ "Only used when converting a Transformers checkpoint to a Megatron checkpoint."
111
+ ),
112
+ )
113
+ return parser
114
+
115
+
116
+ def add_transformers_checkpoint_args(parser):
117
+ parser.add_argument(
118
+ "--tokenizer_name",
119
+ type=str,
120
+ default=None,
121
+ help=(
122
+ "The name of the pre-trained tokenizer to save. "
123
+ "If not None, the tokenizer will be saved. "
124
+ "Only used when converting a Megatron checkpoint to a Transformers checkpoint."
125
+ ),
126
+ )
127
+ parser.add_argument(
128
+ "--max_shard_size",
129
+ type=str,
130
+ default="10GB",
131
+ help=(
132
+ "The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size "
133
+ "lower than this size. If expressed as a string, needs to be digits followed by a unit (like `5MB`). "
134
+ "Only used when converting a Megatron checkpoint to a Transformers checkpoint."
135
+ ),
136
+ )
137
+
138
+ return parser
139
+
140
+
141
+ # The simple map of names for "automated" rules.
142
+ megatron_to_transformers = {
143
+ "attention.dense": ".attn.c_proj.",
144
+ "self_attention.dense": ".attn.c_proj.",
145
+ "mlp.dense_h_to_4h": ".mlp.c_fc.",
146
+ "mlp.dense_4h_to_h": ".mlp.c_proj.",
147
+ }
148
+ transformers_to_megatron = {v[1:-1]: k for k, v in megatron_to_transformers.items()}
149
+
150
+ tensor_parallel_params = [
151
+ # megatron-lm layers to merge across tp ranks
152
+ "self_attention.query_key_value.weight",
153
+ "self_attention.query_key_value.bias",
154
+ "self_attention.dense.weight",
155
+ "mlp.dense_h_to_4h.weight",
156
+ "mlp.dense_h_to_4h.bias",
157
+ "mlp.dense_4h_to_h.weight",
158
+ # deprecated
159
+ "attention.query_key_value.weight",
160
+ "attention.query_key_value.bias",
161
+ "attention.dense.weight",
162
+ # transformers layers to split across tp ranks
163
+ "attn.c_attn.weight",
164
+ "attn.c_attn.bias",
165
+ "attn.c_proj.weight",
166
+ "mlp.c_fc.weight",
167
+ "mlp.c_fc.bias",
168
+ "mlp.c_proj.weight",
169
+ ]
170
+
171
+
172
+ def recursive_print(name, val, spaces=0):
173
+ """
174
+ Recursively print the structure of a checkpoint. This function is taken from `convert_megatron_gpt2_checkpoint.py`
175
+
176
+ Args:
177
+ name (str): the name of the current tensor parameter
178
+ val (Tuple(int)): the shape of the current tensor parameter
179
+ spaces (int): the number of spaces to print before the output for a nested structure
180
+ """
181
+ # Format the message.
182
+ if name is None:
183
+ msg = None
184
+ else:
185
+ fmt = "." * max(0, spaces - 2) + "# {:" + str(50 - spaces) + "s}"
186
+ msg = fmt.format(name)
187
+
188
+ # Print and recurse (if needed).
189
+ if isinstance(val, dict):
190
+ if msg is not None:
191
+ print(msg)
192
+ for k in val:
193
+ recursive_print(k, val[k], spaces + 2)
194
+ elif isinstance(val, torch.Tensor):
195
+ print(msg, ":", val.size())
196
+ else:
197
+ print(msg, ":", val)
198
+
199
+
200
+ def megatron_to_transformers_fix_query_key_value_ordering(
201
+ param, checkpoint_version, num_splits, num_heads, hidden_size
202
+ ):
203
+ """
204
+ Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :] for compatibility with later versions
205
+ of NVIDIA Megatron-LM. The inverse operation is performed inside Megatron-LM to read checkpoints:
206
+ https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209 If param is the weight tensor of the
207
+ self-attention block, the returned tensor will have to be transposed one more time to be read by HuggingFace GPT2.
208
+ This function is taken from `convert_megatron_gpt2_checkpoint.py`
209
+
210
+ Args:
211
+ param (torch.Tensor): the tensor to permute
212
+ checkpoint_version (int): the version of the checkpoint.
213
+ num_splits (int): the number of projections, usually 3 for (Query, Key, Value)
214
+ num_heads (int): the number of attention heads
215
+ hidden_size (int): the hidden size per head
216
+ """
217
+
218
+ input_shape = param.size()
219
+ if checkpoint_version == 1.0:
220
+ # version 1.0 stores [num_heads * hidden_size * num_splits, :]
221
+ saved_shape = (num_heads, hidden_size, num_splits) + input_shape[1:]
222
+ param = param.view(*saved_shape)
223
+ param = param.transpose(0, 2)
224
+ param = param.transpose(1, 2).contiguous()
225
+ elif checkpoint_version >= 2.0:
226
+ # other versions store [num_heads * num_splits * hidden_size, :]
227
+ saved_shape = (num_heads, num_splits, hidden_size) + input_shape[1:]
228
+ param = param.view(*saved_shape)
229
+ param = param.transpose(0, 1).contiguous()
230
+ param = param.view(*input_shape)
231
+ return param
232
+
233
+
234
+ def transformers_to_megatron_fix_query_key_value_ordering(
235
+ param, checkpoint_version, num_splits, num_heads, hidden_size
236
+ ):
237
+ """
238
+ Permutes layout of param tensor to the one compatible with respective NVIDIA Megatron-LM checkpoint versions. Input
239
+ is [num_splits * num_heads * hidden_size, :] and output is [num_heads * hidden_size * num_splits, :] for version
240
+ 1.0 and [num_heads * num_splits * hidden_size, :] for version 2.0 and later. If param is the weight tensor of the
241
+ self-attention block, the param needs to be already transposed before calling this function.
242
+
243
+ Args:
244
+ param (torch.Tensor): the tensor to permute
245
+ checkpoint_version (int): the version of the checkpoint.
246
+ num_splits (int): the number of projections, usually 3 for (Query, Key, Value)
247
+ num_heads (int): the number of attention heads
248
+ hidden_size (int): the hidden size per head
249
+ """
250
+
251
+ # Input is [num_splits * num_heads * hidden_size, :]
252
+ input_shape = param.size()
253
+ if checkpoint_version == 1.0:
254
+ # version 1.0 stores [num_heads * hidden_size * num_splits, :]
255
+ current_shape = (num_splits, num_heads, hidden_size) + input_shape[1:]
256
+ param = param.view(*current_shape)
257
+ param = param.transpose(0, 2)
258
+ param = param.transpose(1, 2).contiguous()
259
+ elif checkpoint_version >= 2.0:
260
+ # other versions store [num_heads * num_splits * hidden_size, :]
261
+ current_shape = (num_splits, num_heads, hidden_size) + input_shape[1:]
262
+ param = param.view(*current_shape)
263
+ param = param.transpose(0, 1).contiguous()
264
+ param = param.view(*input_shape)
265
+ return param
266
+
267
+
268
+ def merge_transformers_sharded_states(path, num_checkpoints):
269
+ """
270
+ Merge sharded checkpoints from transformers into a single checkpoint.
271
+
272
+ Args:
273
+ path (str): the path to the sharded checkpoints
274
+ num_checkpoints (int): the number of checkpoints to merge
275
+ """
276
+ state_dict = {}
277
+ for i in range(1, num_checkpoints + 1):
278
+ checkpoint_path = os.path.join(path, f"pytorch_model-{i:05d}-of-{num_checkpoints:05d}.bin")
279
+ check_torch_load_is_safe()
280
+ current_chunk = torch.load(checkpoint_path, map_location="cpu", weights_only=True)
281
+ state_dict.update(current_chunk)
282
+ return state_dict
283
+
284
+
285
+ def get_megatron_sharded_states(args, tp_size, pp_size, pp_rank):
286
+ """
287
+ Get sharded checkpoints from NVIDIA Megatron-LM checkpoint based on the provided tensor parallel size, pipeline
288
+ parallel size and pipeline parallel rank.
289
+
290
+ Args:
291
+ args (argparse.Namespace): the arguments to the script
292
+ tp_size (int): the tensor parallel size
293
+ pp_size (int): the pipeline parallel size
294
+ pp_rank (int): the pipeline parallel rank
295
+ """
296
+ tp_state_dicts = []
297
+ for i in range(tp_size):
298
+ sub_dir_name = f"mp_rank_{i:02d}" if pp_size == 1 else f"mp_rank_{i:02d}_{pp_rank:03d}"
299
+ for checkpoint_name in ["model_optim_rng.pt", "model_rng.pt"]:
300
+ checkpoint_path = os.path.join(args.load_path, sub_dir_name, checkpoint_name)
301
+ if os.path.isfile(checkpoint_path):
302
+ break
303
+ check_torch_load_is_safe()
304
+ state_dict = torch.load(checkpoint_path, map_location="cpu", weights_only=True)
305
+ tp_state_dicts.append(state_dict)
306
+ return tp_state_dicts
307
+
308
+
309
+ def get_element_from_dict_by_path(d, path):
310
+ """
311
+ Get element from dictionary by path. If element is not present, recursively add empty dictionaries.
312
+
313
+ Args:
314
+ d (dict): the dictionary to get the element from
315
+ path (list): the path to the element which is delimited by "."
316
+ """
317
+ path = path.split(".")
318
+ for k in path:
319
+ if k not in d:
320
+ d[k] = {}
321
+ d = d[k]
322
+ return d
323
+
324
+
325
+ def convert_checkpoint_from_megatron_to_transformers(args):
326
+ """
327
+ Convert NVIDIA Megatron-LM checkpoint to HuggingFace Transformers checkpoint. This handles Megatron checkpoints
328
+ with different tensor parallelism and pipeline parallelism sizes. It saves the converted checkpoint into shards
329
+ using HuggingFace Transformers checkpoint sharding functionality. This greatly extends the functionality of
330
+ `convert_megatron_gpt2_checkpoint.py`
331
+
332
+ Args:
333
+ args (argparse.Namespace): the arguments to the script
334
+ """
335
+ # Load Megatron-LM checkpoint arguments from the state dict
336
+ sub_dirs = os.listdir(args.load_path)
337
+ possible_sub_dirs = ["mp_rank_00", "mp_rank_00_000"]
338
+ for sub_dir in possible_sub_dirs:
339
+ if sub_dir in sub_dirs:
340
+ rank0_checkpoint_name = os.listdir(os.path.join(args.load_path, sub_dir))[0]
341
+ rank0_checkpoint_path = os.path.join(args.load_path, sub_dir, rank0_checkpoint_name)
342
+ break
343
+ print(f"Loading Megatron-LM checkpoint arguments from: {rank0_checkpoint_path}")
344
+ check_torch_load_is_safe()
345
+ state_dict = torch.load(rank0_checkpoint_path, map_location="cpu", weights_only=True)
346
+ megatron_args = state_dict.get("args", None)
347
+ if megatron_args is None:
348
+ raise ValueError(
349
+ "Megatron-LM checkpoint does not contain arguments. This utility only supports Megatron-LM checkpoints"
350
+ " containing all the megatron arguments. This is because it loads all config related to model"
351
+ " architecture, the tensor and pipeline model parallel size from the checkpoint instead of user having to"
352
+ " manually specify all the details. Please save Megatron-LM checkpoint along with all the megatron"
353
+ " arguments to use this utility."
354
+ )
355
+
356
+ # Create Transformers GPT2 config from Megatron-LM arguments
357
+ if megatron_args is not None:
358
+ if megatron_args.bias_gelu_fusion:
359
+ activation_function = "gelu_fast"
360
+ elif megatron_args.openai_gelu:
361
+ activation_function = "gelu_new"
362
+ else:
363
+ activation_function = "gelu"
364
+ else:
365
+ # in the very early days this used to be "gelu_new"
366
+ activation_function = "gelu_new"
367
+ vocab_size = (
368
+ megatron_args.padded_vocab_size
369
+ if getattr(megatron_args, "orig_vocab_size", None) is None
370
+ else megatron_args.orig_vocab_size
371
+ )
372
+ print(vocab_size)
373
+
374
+ config = GPT2Config(
375
+ vocab_size=vocab_size,
376
+ n_positions=megatron_args.max_position_embeddings,
377
+ n_embd=megatron_args.hidden_size,
378
+ n_layer=megatron_args.num_layers,
379
+ n_head=megatron_args.num_attention_heads,
380
+ n_inner=megatron_args.ffn_hidden_size,
381
+ activation_function=activation_function,
382
+ resid_pdrop=0.1,
383
+ embd_pdrop=0.1,
384
+ attn_pdrop=0.1,
385
+ layer_norm_epsilon=1e-5,
386
+ initializer_range=0.02,
387
+ summary_type="cls_index",
388
+ summary_use_proj=True,
389
+ summary_activation=None,
390
+ summary_proj_to_labels=True,
391
+ summary_first_dropout=0.1,
392
+ scale_attn_weights=True,
393
+ use_cache=True,
394
+ bos_token_id=vocab_size - 1,
395
+ eos_token_id=vocab_size - 1,
396
+ architectures=["GPT2LMHeadModel"],
397
+ )
398
+
399
+ output_state_dict = {}
400
+
401
+ checkpoint_version = state_dict.get("checkpoint_version", 0.0)
402
+ tp_size = megatron_args.tensor_model_parallel_size
403
+ pp_size = megatron_args.pipeline_model_parallel_size
404
+ dtype = torch.float32
405
+ # The regex to extract layer names.
406
+ layer_re = re.compile(r"layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)")
407
+
408
+ # Convert.
409
+ print("Converting")
410
+
411
+ # Embeddings
412
+ print("Converting embeddings")
413
+ tp_state_dicts = get_megatron_sharded_states(args, tp_size, pp_size, 0)
414
+
415
+ # Convert and store the position embeddings.
416
+ position_embeddings = get_element_from_dict_by_path(
417
+ tp_state_dicts[0], "model.language_model.embedding.position_embeddings.weight"
418
+ )
419
+ output_state_dict["transformer.wpe.weight"] = position_embeddings.to(dtype)
420
+
421
+ # Convert and store the word embeddings.
422
+ word_embeddings = torch.cat(
423
+ [
424
+ get_element_from_dict_by_path(
425
+ tp_state_dicts[tp_rank], "model.language_model.embedding.word_embeddings.weight"
426
+ )
427
+ for tp_rank in range(tp_size)
428
+ ],
429
+ dim=0,
430
+ )
431
+ word_embeddings = word_embeddings[:vocab_size].to(dtype)
432
+ output_state_dict["transformer.wte.weight"] = word_embeddings
433
+
434
+ # Transformer Layers
435
+ print("Converting transformer layers")
436
+ # The number of heads.
437
+ heads = config.n_head
438
+ # The hidden_size per head.
439
+ hidden_size_per_head = config.n_embd // config.n_head
440
+ n_positions = config.n_positions
441
+ num_layers = config.num_hidden_layers // pp_size
442
+
443
+ for pp_rank in range(pp_size):
444
+ if pp_size > 0:
445
+ print(f"Converting pipeline parallel rank {pp_rank}")
446
+ tp_state_dicts = get_megatron_sharded_states(args, tp_size, pp_size, pp_rank)
447
+
448
+ # The transformer.
449
+ path = (
450
+ "model.language_model.transformer"
451
+ if "transformer" in get_element_from_dict_by_path(tp_state_dicts[0], "model.language_model")
452
+ else "model.language_model.encoder"
453
+ )
454
+ # Extract the layers.
455
+ for key, val in get_element_from_dict_by_path(tp_state_dicts[0], path).items():
456
+ # Match the name.
457
+ m = layer_re.match(key)
458
+ # Stop if that's not a layer
459
+ if m is None:
460
+ break
461
+
462
+ # The index of the layer.
463
+ layer_idx = int(m.group(1)) + pp_rank * num_layers
464
+ # The name of the operation.
465
+ op_name = m.group(2)
466
+ # Is it a weight or a bias?
467
+ weight_or_bias = m.group(3)
468
+
469
+ # The name of the layer.
470
+ layer_name = f"transformer.h.{layer_idx}"
471
+
472
+ if op_name + "." + weight_or_bias not in tensor_parallel_params:
473
+ params = val.to(dtype)
474
+ else:
475
+ dim = 1 if op_name in ["self_attention.dense", "mlp.dense_4h_to_h", "attention.dense"] else 0
476
+ params = torch.cat(
477
+ [val]
478
+ + [
479
+ get_element_from_dict_by_path(tp_state_dicts[tp_rank], f"{path}")[key]
480
+ for tp_rank in range(1, tp_size)
481
+ ],
482
+ dim=dim,
483
+ ).to(dtype)
484
+
485
+ # For layernorm(s), simply store the layer norm.
486
+ if op_name.endswith("layernorm"):
487
+ ln_name = "ln_1" if op_name.startswith("input") else "ln_2"
488
+ output_state_dict[layer_name + "." + ln_name + "." + weight_or_bias] = params
489
+
490
+ # Transpose the QKV matrix.
491
+ elif (
492
+ op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
493
+ ) and weight_or_bias == "weight":
494
+ # Insert a tensor of 1x1xDxD bias.
495
+ causal_mask = torch.tril(torch.ones((n_positions, n_positions), dtype=dtype)).view(
496
+ 1, 1, n_positions, n_positions
497
+ )
498
+ output_state_dict[layer_name + ".attn.bias"] = causal_mask
499
+
500
+ # Insert a "dummy" tensor for masked_bias.
501
+ masked_bias = torch.tensor(-1e4, dtype=dtype)
502
+ output_state_dict[layer_name + ".attn.masked_bias"] = masked_bias
503
+
504
+ out_val = megatron_to_transformers_fix_query_key_value_ordering(
505
+ params,
506
+ checkpoint_version,
507
+ 3,
508
+ heads,
509
+ hidden_size_per_head,
510
+ )
511
+ # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D.
512
+ out_val = out_val.transpose(0, 1).contiguous()
513
+ # Store.
514
+ output_state_dict[layer_name + ".attn.c_attn.weight"] = out_val
515
+
516
+ # Transpose the bias.
517
+ elif (
518
+ op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
519
+ ) and weight_or_bias == "bias":
520
+ out_val = megatron_to_transformers_fix_query_key_value_ordering(
521
+ params, checkpoint_version, 3, heads, hidden_size_per_head
522
+ )
523
+ # Store. No change of shape.
524
+ output_state_dict[layer_name + ".attn.c_attn.bias"] = out_val
525
+
526
+ # Transpose the weights.
527
+ elif weight_or_bias == "weight":
528
+ out_name = megatron_to_transformers[op_name]
529
+ output_state_dict[layer_name + out_name + "weight"] = params.transpose(0, 1)
530
+
531
+ # Copy the bias.
532
+ elif weight_or_bias == "bias":
533
+ out_name = megatron_to_transformers[op_name]
534
+ output_state_dict[layer_name + out_name + "bias"] = params
535
+
536
+ if config.n_layer != (layer_idx + 1):
537
+ raise ValueError(f"Expected {config.n_layer} layers but found {layer_idx + 1}")
538
+
539
+ # The final layernorm.
540
+ print("Converting final layernorm")
541
+ params = get_element_from_dict_by_path(tp_state_dicts[0], str(path))
542
+ output_state_dict["transformer.ln_f.weight"] = params["final_layernorm.weight"].to(dtype)
543
+ output_state_dict["transformer.ln_f.bias"] = params["final_layernorm.bias"].to(dtype)
544
+
545
+ # For LM head, transformers' wants the matrix to weight embeddings.
546
+ print("Converting LM head")
547
+ output_state_dict["lm_head.weight"] = word_embeddings.to(dtype)
548
+
549
+ # It should be done!
550
+ print("Conversion from Megatron-LM to Transformers is done!")
551
+
552
+ # Print the structure of converted state dict.
553
+ if args.print_checkpoint_structure:
554
+ recursive_print(None, output_state_dict)
555
+
556
+ # Add tokenizer class info to config
557
+ # see https://github.com/huggingface/transformers/issues/13906)
558
+
559
+ if args.tokenizer_name is None:
560
+ tokenizer_name = "openai-community/gpt2"
561
+ else:
562
+ tokenizer_name = args.tokenizer_name
563
+
564
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
565
+ tokenizer_class = type(tokenizer).__name__
566
+ config.tokenizer_class = tokenizer_class
567
+
568
+ # Store the config to file.
569
+ print("Saving config")
570
+ config.save_pretrained(args.save_path)
571
+
572
+ # Save tokenizer based on args
573
+ if args.tokenizer_name is not None:
574
+ print(f"Adding {tokenizer_class} tokenizer files")
575
+ tokenizer.save_pretrained(args.save_path)
576
+
577
+ # Store the state_dict to file.
578
+ max_shard_size = int(args.max_shard_size) if args.max_shard_size.isdigit() else args.max_shard_size
579
+ state_dict_split = split_torch_state_dict_into_shards(output_state_dict, max_shard_size=max_shard_size)
580
+ shards = index = None
581
+ for tensors in state_dict_split.filename_to_tensors.values():
582
+ shards = {tensor: state_dict[tensor] for tensor in tensors}
583
+ if state_dict_split.is_sharded:
584
+ index = {
585
+ "metadata": state_dict_split.metadata,
586
+ "weight_map": state_dict_split.tensor_to_filename,
587
+ }
588
+
589
+ # Save the model
590
+ for shard_file, shard in shards.items():
591
+ torch.save(shard, os.path.join(args.save_path, shard_file))
592
+
593
+ if index is None:
594
+ print(f"Model weights saved in {os.path.join(args.save_path, WEIGHTS_NAME)}")
595
+ else:
596
+ save_index_file = os.path.join(args.save_path, WEIGHTS_INDEX_NAME)
597
+ # Save the index as well
598
+ with open(save_index_file, "w", encoding="utf-8") as f:
599
+ content = json.dumps(index, indent=2, sort_keys=True) + "\n"
600
+ f.write(content)
601
+ print(
602
+ f"The model is bigger than the maximum size per checkpoint ({args.max_shard_size}) and is going to be "
603
+ f"split in {len(shards)} checkpoint shards. You can find where each parameters has been saved in the "
604
+ f"index located at {save_index_file}."
605
+ )
606
+
607
+
608
+ def convert_checkpoint_from_transformers_to_megatron(args):
609
+ """
610
+ Convert a checkpoint from HuggingFace Transformers to Megatron-LM. This allows converted checkpoints with variable
611
+ tensor parallelism and pipeline parallelism sizes. It takes as input a checkpoint from HuggingFace Transformers
612
+ which can have multiple shards.
613
+
614
+ Args:
615
+ args (argparse.Namespace): the arguments to the script
616
+
617
+ """
618
+ os.makedirs(args.save_path, exist_ok=True)
619
+ # Search in directory above this
620
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
621
+ if args.megatron_path is not None:
622
+ sys.path.insert(0, args.megatron_path)
623
+
624
+ megatron_exists = importlib.util.find_spec("megatron") is not None
625
+ if megatron_exists:
626
+ from megatron.core import package_info
627
+
628
+ if version.parse(package_info.__version__) >= version.parse("0.6.0"):
629
+ from megatron.training.tokenizer.tokenizer import _vocab_size_with_padding
630
+ else:
631
+ from megatron.tokenizer.tokenizer import _vocab_size_with_padding
632
+
633
+ else:
634
+ print("Unable to import Megatron, please specify the path to Megatron using --megatron-path. Exiting.")
635
+ exit(1)
636
+
637
+ # load the transformers model state dict and config
638
+ sub_dirs = [x for x in os.listdir(args.load_path) if x.startswith("pytorch_model")]
639
+ if len(sub_dirs) == 1:
640
+ checkpoint_name = "pytorch_model.bin"
641
+ check_torch_load_is_safe()
642
+ state_dict = torch.load(os.path.join(args.load_path, checkpoint_name), map_location="cpu", weights_only=True)
643
+ else:
644
+ num_checkpoints = len(sub_dirs) - 1
645
+ state_dict = merge_transformers_sharded_states(args.load_path, num_checkpoints)
646
+
647
+ config = GPT2Config.from_pretrained(args.load_path)
648
+
649
+ # Saving the tracker file
650
+ tracker_filepath = os.path.join(args.save_path, "latest_checkpointed_iteration.txt")
651
+ with open(tracker_filepath, "w") as f:
652
+ f.write("release")
653
+
654
+ # create `release` dir in args.load_path
655
+ release_dir = os.path.join(args.save_path, "release")
656
+ os.makedirs(release_dir, exist_ok=True)
657
+
658
+ # megatron args
659
+ megatron_args = {
660
+ "orig_vocab_size": config.vocab_size,
661
+ "max_position_embeddings": config.n_positions,
662
+ "hidden_size": config.n_embd,
663
+ "num_layers": config.n_layer,
664
+ "num_attention_heads": config.n_head,
665
+ "ffn_hidden_size": config.n_inner,
666
+ "tensor_model_parallel_size": args.target_tensor_model_parallel_size,
667
+ "pipeline_model_parallel_size": args.target_pipeline_model_parallel_size,
668
+ "data_parallel_size": args.target_data_parallel_size,
669
+ "make_vocab_size_divisible_by": args.make_vocab_size_divisible_by,
670
+ "rank": 0,
671
+ "tokenizer_type": "GPT2BPETokenizer",
672
+ }
673
+
674
+ if config.activation_function == "gelu":
675
+ megatron_args["bias_gelu_fusion"] = False
676
+ megatron_args["openai_gelu"] = False
677
+ elif config.activation_function == "gelu_fast":
678
+ megatron_args["bias_gelu_fusion"] = True
679
+ megatron_args["openai_gelu"] = False
680
+ elif config.activation_function == "gelu_new":
681
+ megatron_args["bias_gelu_fusion"] = False
682
+ megatron_args["openai_gelu"] = True
683
+
684
+ margs = types.SimpleNamespace()
685
+ for k, v in megatron_args.items():
686
+ setattr(margs, k, v)
687
+
688
+ # params dtype
689
+ if args.target_params_dtype == "fp16":
690
+ dtype = torch.float16
691
+ elif args.target_params_dtype == "bf16":
692
+ dtype = torch.bfloat16
693
+ else:
694
+ dtype = torch.float32
695
+ setattr(margs, "params_dtype", dtype)
696
+
697
+ # save dummy optim state dict
698
+ dummy_optim_state_dict = {}
699
+ dummy_optim_state_dict["optimizer"] = {
700
+ "step": 0,
701
+ "param_groups": [
702
+ {
703
+ "lr": 0.0,
704
+ "beta1": 0.0,
705
+ "beta2": 0.0,
706
+ "eps": 0.0,
707
+ "weight_decay": 0.0,
708
+ "correct_bias": False,
709
+ "params": [],
710
+ }
711
+ ],
712
+ }
713
+ if args.use_distributed_optimizer:
714
+ for i in range(args.target_pipeline_model_parallel_size):
715
+ for j in range(args.target_tensor_model_parallel_size):
716
+ for k in range(args.target_data_parallel_size):
717
+ if args.target_pipeline_model_parallel_size == 1:
718
+ checkpoint_dir = f"mp_rank_{j:02d}_{k:03d}"
719
+ else:
720
+ checkpoint_dir = f"mp_rank_{j:02d}_{i:03d}_{k:03d}"
721
+ checkpoint_dir = os.path.join(release_dir, checkpoint_dir)
722
+ os.makedirs(checkpoint_dir, exist_ok=True)
723
+ torch.save(
724
+ dummy_optim_state_dict,
725
+ os.path.join(checkpoint_dir, "optim.pt"),
726
+ )
727
+
728
+ # Convert.
729
+ print("Converting")
730
+ output_state_dict = []
731
+ for i in range(args.target_tensor_model_parallel_size):
732
+ output_state_dict.append({})
733
+
734
+ # Embedding layer
735
+ print("converting embedding layer")
736
+ pos_embedding = state_dict["transformer.wpe.weight"].to(dtype)
737
+ word_embedding = state_dict["transformer.wte.weight"].to(dtype)
738
+ orig_vocab_size = config.vocab_size
739
+ padded_vocab_size = _vocab_size_with_padding(orig_vocab_size, margs)
740
+ setattr(margs, "padded_vocab_size", padded_vocab_size)
741
+ # Cut out extra padding we don't need
742
+ if orig_vocab_size > padded_vocab_size:
743
+ full_word_embed = word_embedding[0:padded_vocab_size, :]
744
+ # Expanding embedding to larger size by replicating final entry
745
+ elif orig_vocab_size < padded_vocab_size:
746
+ padding_size = padded_vocab_size - orig_vocab_size
747
+ full_word_embed = torch.cat((word_embedding, word_embedding[-1].unsqueeze(0).expand(padding_size, -1)))
748
+ # Same size!
749
+ else:
750
+ full_word_embed = word_embedding
751
+
752
+ # Split into new tensor model parallel sizes
753
+ out_word_embed = torch.chunk(full_word_embed, args.target_tensor_model_parallel_size, dim=0)
754
+ for i in range(args.target_tensor_model_parallel_size):
755
+ pos_emb_dict = get_element_from_dict_by_path(
756
+ output_state_dict[i], "model.language_model.embedding.position_embeddings"
757
+ )
758
+ pos_emb_dict["weight"] = pos_embedding
759
+
760
+ word_emb_dict = get_element_from_dict_by_path(
761
+ output_state_dict[i], "model.language_model.embedding.word_embeddings"
762
+ )
763
+ word_emb_dict["weight"] = out_word_embed[i].clone()
764
+
765
+ # Transformer layers
766
+ print("converting transformer layers")
767
+ if config.num_attention_heads % args.target_tensor_model_parallel_size != 0:
768
+ raise ValueError(
769
+ f"Number of attention heads ({config.num_attention_heads}) must be divisible by number of tensor parallelism"
770
+ f" ({args.target_tensor_model_parallel_size})"
771
+ )
772
+
773
+ if config.num_hidden_layers % args.target_pipeline_model_parallel_size != 0:
774
+ raise ValueError(
775
+ f"Number of layers ({config.num_hidden_layers}) must be divisible by number of pipeline parallelism"
776
+ f" ({args.target_pipeline_model_parallel_size})"
777
+ )
778
+
779
+ num_layers = config.num_hidden_layers // args.target_pipeline_model_parallel_size
780
+
781
+ layer_re = re.compile(r"transformer.h\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)")
782
+ # The number of heads.
783
+ heads = config.n_head
784
+ # The hidden_size per head.
785
+ hidden_size_per_head = config.n_embd // config.n_head
786
+ for pp_rank in range(args.target_pipeline_model_parallel_size):
787
+ layer_offset = pp_rank * num_layers
788
+ if pp_rank > 0:
789
+ output_state_dict = []
790
+ for i in range(args.target_tensor_model_parallel_size):
791
+ output_state_dict.append({})
792
+
793
+ for layer in range(num_layers):
794
+ pp_layer_id = layer + layer_offset
795
+ layers_to_copy = [
796
+ layer_name for layer_name in state_dict if layer_name.startswith(f"transformer.h.{pp_layer_id}.")
797
+ ]
798
+
799
+ for layer_name in layers_to_copy:
800
+ m = layer_re.match(layer_name)
801
+ # Stop if that's not a layer
802
+ if m is None:
803
+ break
804
+
805
+ # The index of the layer.
806
+ _ = int(m.group(1))
807
+ # The name of the operation.
808
+ op_name = m.group(2)
809
+ # Is it a weight or a bias?
810
+ weight_or_bias = m.group(3)
811
+
812
+ params = state_dict[layer_name].to(dtype)
813
+ # handle layernorm
814
+ if op_name.startswith("ln"):
815
+ out_name = "input_layernorm" if op_name.endswith("1") else "post_attention_layernorm"
816
+ layer_name = f"layers.{layer}.{out_name}.{weight_or_bias}"
817
+
818
+ # handle attention K, V, Q weights
819
+ elif op_name.startswith("attn.c_attn") and weight_or_bias == "weight":
820
+ # transformers stores D X (3*D) but Megatron-LM expects (3*D) X D.
821
+ params = params.transpose(0, 1).contiguous()
822
+
823
+ params = transformers_to_megatron_fix_query_key_value_ordering(
824
+ params,
825
+ 3.0,
826
+ 3,
827
+ heads,
828
+ hidden_size_per_head,
829
+ )
830
+ layer_name = f"layers.{layer}.self_attention.query_key_value.{weight_or_bias}"
831
+
832
+ # handle attention K, V, Q bias
833
+ elif op_name.startswith("attn.c_attn") and weight_or_bias == "bias":
834
+ params = transformers_to_megatron_fix_query_key_value_ordering(
835
+ params,
836
+ 3.0,
837
+ 3,
838
+ heads,
839
+ hidden_size_per_head,
840
+ )
841
+ layer_name = f"layers.{layer}.self_attention.query_key_value.{weight_or_bias}"
842
+
843
+ # handle attention and mlp weights
844
+ elif weight_or_bias == "weight":
845
+ out_name = transformers_to_megatron.get(op_name)
846
+ if out_name is None:
847
+ continue
848
+ params = params.transpose(0, 1)
849
+ layer_name = f"layers.{layer}.{out_name}.{weight_or_bias}"
850
+
851
+ # handle attention and mlp bias
852
+ elif weight_or_bias == "bias":
853
+ out_name = transformers_to_megatron.get(op_name)
854
+ if out_name is None:
855
+ continue
856
+ layer_name = f"layers.{layer}.{out_name}.{weight_or_bias}"
857
+
858
+ # skip
859
+ else:
860
+ continue
861
+
862
+ if op_name + "." + weight_or_bias in tensor_parallel_params:
863
+ dim = 1 if op_name in ["attn.c_proj", "mlp.c_proj"] else 0
864
+ params = torch.chunk(params, args.target_tensor_model_parallel_size, dim=dim)
865
+
866
+ for i in range(args.target_tensor_model_parallel_size):
867
+ params_dict = get_element_from_dict_by_path(output_state_dict[i], "model.language_model.encoder")
868
+ params_dict[layer_name] = (
869
+ params[i].clone() if (op_name + "." + weight_or_bias in tensor_parallel_params) else params
870
+ )
871
+
872
+ if pp_rank == args.target_pipeline_model_parallel_size - 1:
873
+ # handle final layernorm
874
+ for weight_or_bias in ["weight", "bias"]:
875
+ params = state_dict[f"transformer.ln_f.{weight_or_bias}"].to(dtype)
876
+ layer_name = f"final_layernorm.{weight_or_bias}"
877
+ for i in range(args.target_tensor_model_parallel_size):
878
+ params_dict = get_element_from_dict_by_path(output_state_dict[i], "model.language_model.encoder")
879
+ params_dict[layer_name] = params
880
+
881
+ # add the LM head
882
+ for i in range(args.target_tensor_model_parallel_size):
883
+ params_dict = get_element_from_dict_by_path(output_state_dict[i], "model.word_embeddings_for_head")
884
+ params_dict["weight"] = out_word_embed[i].clone()
885
+
886
+ # saving the state dict as per the tp_rank and pp_rank
887
+ for tp_rank in range(args.target_tensor_model_parallel_size):
888
+ output_state_dict[tp_rank]["checkpoint_version"] = 3.0
889
+ output_state_dict[tp_rank]["args"] = margs
890
+ checkpoint_dir = (
891
+ f"mp_rank_{tp_rank:02d}"
892
+ if args.target_pipeline_model_parallel_size == 1
893
+ else f"mp_rank_{tp_rank:02d}_{pp_rank:03d}"
894
+ )
895
+ if args.use_distributed_optimizer:
896
+ checkpoint_name = "model_rng.pt"
897
+ else:
898
+ checkpoint_name = "model_optim_rng.pt"
899
+ output_state_dict[tp_rank]["optimizer"] = dummy_optim_state_dict["optimizer"]
900
+ checkpoint_dir = os.path.join(release_dir, checkpoint_dir)
901
+ os.makedirs(checkpoint_dir, exist_ok=True)
902
+ checkpoint_path = os.path.join(checkpoint_dir, checkpoint_name)
903
+ if args.print_checkpoint_structure:
904
+ print(
905
+ f"Checkpoint structure of model state dict shard belonging to TP rank {tp_rank} and PP rank"
906
+ f" {pp_rank}:"
907
+ )
908
+ recursive_print(None, output_state_dict[tp_rank])
909
+ torch.save(output_state_dict[tp_rank], checkpoint_path)
910
+
911
+
912
+ def main():
913
+ parser = argparse.ArgumentParser()
914
+ parser = add_checkpointing_args(parser)
915
+ parser = add_megatron_checkpoint_args(parser)
916
+ parser = add_transformers_checkpoint_args(parser)
917
+ args = parser.parse_args()
918
+ if args.convert_checkpoint_from_megatron_to_transformers:
919
+ convert_checkpoint_from_megatron_to_transformers(args)
920
+ else:
921
+ convert_checkpoint_from_transformers_to_megatron(args)
922
+
923
+
924
+ if __name__ == "__main__":
925
+ main()
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mllama/configuration_mllama.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ """Mllama model configuration"""
14
+
15
+ from huggingface_hub.dataclasses import strict
16
+
17
+ from ...configuration_utils import PreTrainedConfig
18
+ from ...utils import auto_docstring, logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ @auto_docstring(checkpoint="meta-llama/Llama-3.2-11B-Vision")
25
+ @strict
26
+ class MllamaVisionConfig(PreTrainedConfig):
27
+ r"""
28
+ num_global_layers (`int`, *optional*, defaults to 8):
29
+ Number of global layers in the Transformer encoder. Vision model has a second transformer encoder, called global.
30
+ vision_output_dim (`int`, *optional*, defaults to 7680):
31
+ Dimensionality of the vision model output. Includes output of transformer
32
+ encoder with intermediate layers and global transformer encoder.
33
+ max_num_tiles (`int`, *optional*, defaults to 4):
34
+ Maximum number of tiles for image splitting.
35
+ intermediate_layers_indices (`list[int]`, *optional*, defaults to [3, 7, 15, 23, 30]):
36
+ Indices of intermediate layers of transformer encoder from which to extract and output features.
37
+ These output features are concatenated with final hidden state of transformer encoder.
38
+ supported_aspect_ratios (`list[list[int]]`, *optional*):
39
+ List of supported aspect ratios for image splitting. If not specified, the default supported aspect ratios
40
+ are [[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [3, 1], [4, 1]] for `max_num_tiles=4`.
41
+
42
+ Example:
43
+
44
+ ```python
45
+ >>> from transformers import MllamaVisionConfig, MllamaVisionModel
46
+
47
+ >>> # Initializing a Llama config
48
+ >>> config = MllamaVisionConfig()
49
+
50
+ >>> # Initializing a vision model from the mllama-11b style configuration
51
+ >>> model = MllamaVisionModel(config)
52
+
53
+ >>> # Accessing the model configuration
54
+ >>> configuration = model.config
55
+ ```"""
56
+
57
+ model_type = "mllama_vision_model"
58
+ base_config_key = "vision_config"
59
+ attribute_map = {"num_attention_heads": "attention_heads"}
60
+
61
+ hidden_size: int = 1280
62
+ hidden_act: str = "gelu"
63
+ num_hidden_layers: int = 32
64
+ num_global_layers: int = 8
65
+ attention_heads: int = 16
66
+ num_channels: int = 3
67
+ intermediate_size: int = 5120
68
+ vision_output_dim: int = 7680
69
+ image_size: int | list[int] | tuple[int, int] = 448
70
+ patch_size: int | list[int] | tuple[int, int] = 14
71
+ norm_eps: float = 1e-5
72
+ max_num_tiles: int = 4
73
+ intermediate_layers_indices: list[int] | None = None
74
+ supported_aspect_ratios: list[list[int]] | None = None
75
+ initializer_range: float = 0.02
76
+
77
+ def __post_init__(self, **kwargs):
78
+ if self.supported_aspect_ratios is None:
79
+ self.supported_aspect_ratios = [[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [3, 1], [4, 1]]
80
+
81
+ if self.intermediate_layers_indices is None:
82
+ self.intermediate_layers_indices = [3, 7, 15, 23, 30]
83
+ super().__post_init__(**kwargs)
84
+
85
+ def validate_architecture(self):
86
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
87
+ if (
88
+ self.supported_aspect_ratios == [[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [3, 1], [4, 1]]
89
+ and self.max_num_tiles != 4
90
+ ):
91
+ raise ValueError("max_num_tiles must be 4 for default supported aspect ratios")
92
+
93
+ @property
94
+ def max_aspect_ratio_id(self) -> int:
95
+ return len(self.supported_aspect_ratios)
96
+
97
+
98
+ @auto_docstring(checkpoint="meta-llama/Llama-3.2-11B-Vision")
99
+ @strict
100
+ class MllamaTextConfig(PreTrainedConfig):
101
+ r"""
102
+ cross_attention_layers (`list[int]`, *optional*):
103
+ Indices of the cross attention layers. If not specified, will default to [3, 8, 13, 18, 23, 28, 33, 38].
104
+
105
+ Example:
106
+
107
+ ```python
108
+ >>> from transformers import MllamaTextModel, MllamaTextConfig
109
+
110
+ >>> # Initializing a Mllama text config
111
+ >>> config = MllamaTextConfig()
112
+
113
+ >>> # Initializing a model from the Mllama text configuration
114
+ >>> model = MllamaTextModel(config)
115
+
116
+ >>> # Accessing the model configuration
117
+ >>> configuration = model.config
118
+ ```"""
119
+
120
+ model_type = "mllama_text_model"
121
+ base_config_key = "text_config"
122
+ default_theta = 500000.0
123
+
124
+ vocab_size: int = 128256
125
+ hidden_size: int = 4096
126
+ hidden_act: str = "silu"
127
+ num_hidden_layers: int = 40
128
+ num_attention_heads: int = 32
129
+ num_key_value_heads: int = 8
130
+ intermediate_size: int = 14_336
131
+ rope_parameters: dict | None = None
132
+ rms_norm_eps: float = 1e-5
133
+ max_position_embeddings: int = 131_072
134
+ initializer_range: float = 0.02
135
+ use_cache: bool = True
136
+ tie_word_embeddings: bool = False
137
+ cross_attention_layers: list[int] | None = None
138
+ dropout: float | int = 0.0
139
+ bos_token_id: int = 128000
140
+ eos_token_id: int | list[int] | None = 128001
141
+ pad_token_id: int | None = 128004
142
+
143
+ def __post_init__(self, **kwargs):
144
+ if self.cross_attention_layers is None:
145
+ self.cross_attention_layers = [3, 8, 13, 18, 23, 28, 33, 38]
146
+ super().__post_init__(**kwargs)
147
+
148
+
149
+ @auto_docstring(checkpoint="meta-llama/Llama-3.2-11B-Vision")
150
+ @strict
151
+ class MllamaConfig(PreTrainedConfig):
152
+ r"""
153
+ Example:
154
+
155
+ ```python
156
+ >>> from transformers import MllamaForConditionalGeneration, MllamaConfig, MllamaVisionConfig, MllamaTextConfig
157
+
158
+ >>> # Initializing a CLIP-vision config
159
+ >>> vision_config = MllamaVisionConfig()
160
+
161
+ >>> # Initializing a Llama config
162
+ >>> text_config = MllamaTextConfig()
163
+
164
+ >>> # Initializing a mllama-11b style configuration
165
+ >>> configuration = MllamaConfig(vision_config, text_config)
166
+
167
+ >>> # Initializing a model from the mllama-11b style configuration
168
+ >>> model = MllamaForConditionalGeneration(configuration)
169
+
170
+ >>> # Accessing the model configuration
171
+ >>> configuration = model.config
172
+ ```"""
173
+
174
+ model_type = "mllama"
175
+ attribute_map = {
176
+ "image_token_id": "image_token_index",
177
+ }
178
+ sub_configs = {"text_config": MllamaTextConfig, "vision_config": MllamaVisionConfig}
179
+
180
+ vision_config: dict | PreTrainedConfig | None = None
181
+ text_config: dict | PreTrainedConfig | None = None
182
+ image_token_index: int = 128256
183
+
184
+ def __post_init__(self, **kwargs):
185
+ if self.vision_config is None:
186
+ self.vision_config = MllamaVisionConfig()
187
+ logger.info("vision_config is None, using default mllama vision config")
188
+ elif isinstance(self.vision_config, dict):
189
+ self.vision_config = MllamaVisionConfig(**self.vision_config)
190
+
191
+ if self.text_config is None:
192
+ self.text_config = MllamaTextConfig()
193
+ logger.info("text_config is None, using default mllama text config")
194
+ elif isinstance(self.text_config, dict):
195
+ self.text_config = MllamaTextConfig(**self.text_config)
196
+
197
+ super().__post_init__(**kwargs)
198
+
199
+
200
+ __all__ = ["MllamaConfig", "MllamaTextConfig", "MllamaVisionConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mllama/modeling_mllama.py ADDED
@@ -0,0 +1,1622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """PyTorch Mllama model."""
15
+
16
+ import math
17
+ from collections.abc import Callable
18
+ from typing import Optional
19
+
20
+ import torch
21
+ import torch.nn.functional as F
22
+ from torch import nn
23
+
24
+ from ... import initialization as init
25
+ from ...activations import ACT2FN
26
+ from ...cache_utils import Cache, DynamicCache
27
+ from ...generation import GenerationMixin
28
+ from ...masking_utils import create_causal_mask
29
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
30
+ from ...modeling_layers import GradientCheckpointingLayer
31
+ from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPast, CausalLMOutputWithPast
32
+ from ...modeling_rope_utils import (
33
+ ROPE_INIT_FUNCTIONS,
34
+ dynamic_rope_update,
35
+ )
36
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
37
+ from ...processing_utils import Unpack
38
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
39
+ from ...utils.generic import (
40
+ maybe_autocast,
41
+ merge_with_config_defaults,
42
+ )
43
+ from ...utils.output_capturing import OutputRecorder, capture_outputs
44
+ from .configuration_mllama import MllamaConfig, MllamaTextConfig, MllamaVisionConfig
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+
50
+ def _prepare_cross_attention_mask(
51
+ cross_attention_mask: torch.Tensor,
52
+ num_vision_tokens: int,
53
+ dtype: str,
54
+ ) -> tuple[torch.Tensor, torch.Tensor]:
55
+ # reshape so it can be used by attn module
56
+ batch_size, text_total_length, *_ = cross_attention_mask.shape
57
+ cross_attention_mask = cross_attention_mask.repeat_interleave(num_vision_tokens, dim=3)
58
+ cross_attention_mask = cross_attention_mask.view(batch_size, text_total_length, -1)
59
+ cross_attention_mask = cross_attention_mask.unsqueeze(1)
60
+
61
+ # invert the mask
62
+ inverted_cross_attn_mask = (1.0 - cross_attention_mask).to(dtype)
63
+ cross_attention_mask = inverted_cross_attn_mask.masked_fill(
64
+ inverted_cross_attn_mask.to(torch.bool), torch.finfo(dtype).min
65
+ )
66
+
67
+ # apply full-row bias, which return 4D tensor of shape [B, H, S1, 1] where value is 0 if the a full row in cross attn mask's
68
+ # last dimension contains negative infinity values, otherwise it's 1
69
+ negative_inf_value = torch.finfo(dtype).min
70
+ full_text_row_masked_out_mask = (
71
+ (cross_attention_mask != negative_inf_value).any(dim=-1).type_as(cross_attention_mask)[..., None]
72
+ )
73
+ cross_attention_mask *= full_text_row_masked_out_mask
74
+
75
+ return cross_attention_mask, full_text_row_masked_out_mask
76
+
77
+
78
+ def _prepare_aspect_ratio_attention_mask(
79
+ aspect_ratio_mask: torch.Tensor,
80
+ num_patches: int,
81
+ target_length: int,
82
+ dtype: torch.dtype,
83
+ ) -> torch.Tensor:
84
+ # Expand aspect ratio mask to target_length
85
+ batch_size, max_num_tiles = aspect_ratio_mask.shape
86
+ attention_mask = aspect_ratio_mask.view(batch_size, max_num_tiles, 1, 1).to(dtype)
87
+ attention_mask = attention_mask.repeat(1, 1, target_length, 1)
88
+
89
+ # Mask padding patches
90
+ pad_patches = target_length - num_patches
91
+ attention_mask[:, :, -pad_patches:] = 0
92
+
93
+ # Invert the mask (0 -> 1, 1 -> 0)
94
+ attention_mask = 1 - attention_mask
95
+
96
+ # Reshape to 2D and create 4D attention mask
97
+ # (batch_size, 1, max_num_tiles * target_length, max_num_tiles * target_length)
98
+ attention_mask = attention_mask.reshape(batch_size, max_num_tiles * target_length, 1)
99
+ attention_mask = attention_mask @ attention_mask.transpose(-1, -2) * torch.finfo(dtype).min
100
+ attention_mask = attention_mask.unsqueeze(1)
101
+
102
+ return attention_mask
103
+
104
+
105
+ class MllamaPrecomputedAspectRatioEmbedding(nn.Module):
106
+ def __init__(self, config: MllamaVisionConfig, is_gated: bool = True):
107
+ super().__init__()
108
+ self.max_num_tiles = config.max_num_tiles
109
+ self.hidden_size = config.hidden_size
110
+ self.max_aspect_ratio_id = config.max_aspect_ratio_id
111
+ self.is_gated = is_gated
112
+
113
+ self.embedding = nn.Embedding(self.max_aspect_ratio_id + 1, self.max_num_tiles * self.hidden_size)
114
+ if is_gated:
115
+ self.gate = nn.Parameter(torch.zeros(1))
116
+
117
+ def forward(self, hidden_state: torch.Tensor, aspect_ratio_ids: torch.Tensor) -> torch.Tensor:
118
+ embeddings = self.embedding(aspect_ratio_ids)
119
+ embeddings = embeddings.reshape(-1, self.max_num_tiles, 1, self.hidden_size)
120
+
121
+ if self.is_gated:
122
+ embeddings = embeddings * self.gate.tanh()
123
+
124
+ hidden_state = hidden_state + embeddings
125
+ return hidden_state
126
+
127
+
128
+ class MllamaPrecomputedPositionEmbedding(nn.Module):
129
+ def __init__(self, config: MllamaVisionConfig):
130
+ super().__init__()
131
+ self.max_num_tiles = config.max_num_tiles
132
+ self.max_aspect_ratio_id = config.max_aspect_ratio_id
133
+ self.num_patches = (config.image_size // config.patch_size) ** 2 + 1
134
+ self.hidden_size = config.hidden_size
135
+ self.scale = config.hidden_size**-0.5
136
+
137
+ self.gate = nn.Parameter(torch.zeros(1))
138
+
139
+ # position embedding
140
+ position_embedding = torch.randn(self.num_patches, self.hidden_size)
141
+ self.embedding = nn.Parameter(self.scale * position_embedding)
142
+
143
+ # tile position embedding
144
+ self.tile_embedding = nn.Embedding(
145
+ self.max_aspect_ratio_id + 1, self.max_num_tiles * self.num_patches * self.hidden_size
146
+ )
147
+
148
+ def forward(self, hidden_state: torch.Tensor, aspect_ratio_ids: torch.Tensor) -> torch.Tensor:
149
+ # position embeddings
150
+ gated_position_embedding = (1 - self.gate.tanh()) * self.embedding
151
+ hidden_state = hidden_state + gated_position_embedding.view(1, 1, self.num_patches, self.hidden_size)
152
+
153
+ # precomputed tile position embeddings
154
+ tile_position_embedding = self.tile_embedding(aspect_ratio_ids)
155
+ batch_size = hidden_state.shape[0]
156
+ tile_position_embedding = tile_position_embedding.reshape(
157
+ batch_size, self.max_num_tiles, self.num_patches, self.hidden_size
158
+ )
159
+ gated_tile_position_embedding = self.gate.tanh() * tile_position_embedding
160
+ hidden_state = hidden_state + gated_tile_position_embedding
161
+
162
+ return hidden_state
163
+
164
+
165
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->MllamaVision
166
+ class MllamaVisionMLP(nn.Module):
167
+ def __init__(self, config):
168
+ super().__init__()
169
+ self.config = config
170
+ self.activation_fn = ACT2FN[config.hidden_act]
171
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
172
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
173
+
174
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
175
+ hidden_states = self.fc1(hidden_states)
176
+ hidden_states = self.activation_fn(hidden_states)
177
+ hidden_states = self.fc2(hidden_states)
178
+ return hidden_states
179
+
180
+
181
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
182
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
183
+ """
184
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
185
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
186
+ """
187
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
188
+ if n_rep == 1:
189
+ return hidden_states
190
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
191
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
192
+
193
+
194
+ # Copied from transformers.models.llama.modeling_llama.eager_attention_forward
195
+ def eager_attention_forward(
196
+ module: nn.Module,
197
+ query: torch.Tensor,
198
+ key: torch.Tensor,
199
+ value: torch.Tensor,
200
+ attention_mask: torch.Tensor | None,
201
+ scaling: float,
202
+ dropout: float = 0.0,
203
+ **kwargs: Unpack[TransformersKwargs],
204
+ ):
205
+ key_states = repeat_kv(key, module.num_key_value_groups)
206
+ value_states = repeat_kv(value, module.num_key_value_groups)
207
+
208
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
209
+ if attention_mask is not None:
210
+ attn_weights = attn_weights + attention_mask
211
+
212
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
213
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
214
+ attn_output = torch.matmul(attn_weights, value_states)
215
+ attn_output = attn_output.transpose(1, 2).contiguous()
216
+
217
+ return attn_output, attn_weights
218
+
219
+
220
+ class MllamaVisionAttention(nn.Module):
221
+ def __init__(self, config: MllamaVisionConfig):
222
+ super().__init__()
223
+
224
+ self.config = config
225
+ self.embed_dim = config.hidden_size
226
+ self.num_heads = config.attention_heads
227
+ self.head_dim = config.hidden_size // config.attention_heads
228
+ self.scaling = self.head_dim**-0.5
229
+ self.num_key_value_groups = 1
230
+
231
+ self.q_proj = nn.Linear(self.embed_dim, self.num_heads * self.head_dim, bias=False)
232
+ self.k_proj = nn.Linear(self.embed_dim, self.num_heads * self.head_dim, bias=False)
233
+ self.v_proj = nn.Linear(self.embed_dim, self.num_heads * self.head_dim, bias=False)
234
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.embed_dim, bias=False)
235
+
236
+ def forward(
237
+ self,
238
+ hidden_state: torch.Tensor,
239
+ attention_mask: torch.Tensor | None = None,
240
+ **kwargs,
241
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
242
+ query = self.q_proj(hidden_state)
243
+ key = self.k_proj(hidden_state)
244
+ value = self.v_proj(hidden_state)
245
+
246
+ batch_size, q_seq_len, _ = query.shape
247
+ _, kv_seq_len, _ = key.shape
248
+
249
+ query = query.view(batch_size, q_seq_len, self.num_heads, self.head_dim).transpose(1, 2)
250
+ key = key.view(batch_size, kv_seq_len, self.num_heads, self.head_dim).transpose(1, 2)
251
+ value = value.view(batch_size, kv_seq_len, self.num_heads, self.head_dim).transpose(1, 2)
252
+
253
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
254
+ self.config._attn_implementation, eager_attention_forward
255
+ )
256
+
257
+ attn_output, attn_weights = attention_interface(
258
+ self,
259
+ query,
260
+ key,
261
+ value,
262
+ attention_mask,
263
+ dropout=0.0,
264
+ scaling=self.scaling,
265
+ **kwargs,
266
+ )
267
+
268
+ attn_output = attn_output.reshape(batch_size, q_seq_len, -1).contiguous()
269
+ attn_output = self.o_proj(attn_output)
270
+
271
+ return attn_output, attn_weights
272
+
273
+
274
+ class MllamaVisionEncoderLayer(nn.Module):
275
+ def __init__(self, config: MllamaVisionConfig, is_gated: bool = False):
276
+ super().__init__()
277
+
278
+ self.hidden_size = config.hidden_size
279
+ self.num_attention_heads = config.attention_heads
280
+ self.is_gated = is_gated
281
+ self.intermediate_size = config.intermediate_size
282
+
283
+ self.self_attn = MllamaVisionAttention(config)
284
+ self.mlp = MllamaVisionMLP(config)
285
+
286
+ self.input_layernorm = nn.LayerNorm(self.hidden_size, eps=config.norm_eps)
287
+ self.post_attention_layernorm = nn.LayerNorm(self.hidden_size, eps=config.norm_eps)
288
+
289
+ if is_gated:
290
+ self.gate_attn = nn.Parameter(torch.ones(1) * math.pi / 4)
291
+ self.gate_ffn = nn.Parameter(torch.ones(1) * math.pi / 4)
292
+
293
+ def forward(
294
+ self,
295
+ hidden_state: torch.Tensor,
296
+ attention_mask: torch.Tensor | None = None,
297
+ ):
298
+ # Self Attention
299
+ residual = hidden_state
300
+ hidden_state = self.input_layernorm(hidden_state)
301
+ hidden_state, attn_weights = self.self_attn(hidden_state, attention_mask=attention_mask)
302
+ if self.is_gated:
303
+ hidden_state = self.gate_attn.tanh() * hidden_state
304
+ hidden_state = residual + hidden_state
305
+
306
+ # Feed forward
307
+ residual = hidden_state
308
+ hidden_state = self.post_attention_layernorm(hidden_state)
309
+ hidden_state = self.mlp(hidden_state)
310
+ if self.is_gated:
311
+ hidden_state = self.gate_ffn.tanh() * hidden_state
312
+ hidden_state = residual + hidden_state
313
+
314
+ return hidden_state
315
+
316
+
317
+ class MllamaVisionEncoder(nn.Module):
318
+ """
319
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
320
+ [`MllamaEncoderLayer`].
321
+
322
+ Args:
323
+ config: MllamaConfig
324
+ """
325
+
326
+ def __init__(self, config: MllamaVisionConfig, num_layers=32, is_gated=False):
327
+ super().__init__()
328
+ self.config = config
329
+ self.layers = nn.ModuleList([MllamaVisionEncoderLayer(config, is_gated) for _ in range(num_layers)])
330
+ self.gradient_checkpointing = False
331
+ self.config = config
332
+
333
+ def forward(
334
+ self,
335
+ hidden_states: torch.Tensor,
336
+ attention_mask: torch.Tensor | None = None,
337
+ ) -> BaseModelOutput:
338
+ r"""
339
+ Args:
340
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
341
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
342
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
343
+ than the model's internal embedding lookup matrix.
344
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
345
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
346
+
347
+ - 1 for tokens that are **not masked**,
348
+ - 0 for tokens that are **masked**.
349
+
350
+ [What are attention masks?](../glossary#attention-mask)
351
+
352
+ """
353
+ encoder_states = ()
354
+ for encoder_layer in self.layers:
355
+ hidden_states = encoder_layer(
356
+ hidden_state=hidden_states,
357
+ attention_mask=attention_mask,
358
+ )
359
+ encoder_states = encoder_states + (hidden_states,)
360
+
361
+ return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=encoder_states)
362
+
363
+
364
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->MllamaText
365
+ class MllamaTextRMSNorm(nn.Module):
366
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
367
+ """
368
+ MllamaTextRMSNorm is equivalent to T5LayerNorm
369
+ """
370
+ super().__init__()
371
+ self.weight = nn.Parameter(torch.ones(hidden_size))
372
+ self.variance_epsilon = eps
373
+
374
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
375
+ input_dtype = hidden_states.dtype
376
+ hidden_states = hidden_states.to(torch.float32)
377
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
378
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
379
+ return self.weight * hidden_states.to(input_dtype)
380
+
381
+ def extra_repr(self):
382
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
383
+
384
+
385
+ class MllamaTextCrossAttention(nn.Module):
386
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
387
+
388
+ def __init__(
389
+ self,
390
+ config: MllamaTextConfig | None = None,
391
+ layer_idx: int | None = None,
392
+ ):
393
+ super().__init__()
394
+ self.config = config
395
+ self.num_heads = self.config.num_attention_heads
396
+ self.num_key_value_heads = self.config.num_key_value_heads
397
+ self.dropout = config.dropout
398
+ self.hidden_size = config.hidden_size
399
+ self.head_dim = config.hidden_size // self.num_heads
400
+ self.layer_idx = layer_idx
401
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
402
+ self.scaling = self.head_dim**-0.5
403
+
404
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
405
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
406
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
407
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
408
+
409
+ self.q_norm = MllamaTextRMSNorm(self.head_dim, eps=config.rms_norm_eps)
410
+ self.k_norm = MllamaTextRMSNorm(self.head_dim, eps=config.rms_norm_eps)
411
+
412
+ def forward(
413
+ self,
414
+ hidden_states: torch.Tensor,
415
+ cross_attention_states: torch.Tensor | None = None,
416
+ past_key_values: Cache | None = None,
417
+ attention_mask: torch.Tensor | None = None,
418
+ use_cache: bool | None = None,
419
+ **kwargs,
420
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
421
+ """Input shape: Batch x Time x Channel"""
422
+ bsz, q_len, _ = hidden_states.size()
423
+ query_states = self.q_proj(hidden_states)
424
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
425
+ query_states = self.q_norm(query_states)
426
+
427
+ if cross_attention_states is not None:
428
+ key_states = self.k_proj(cross_attention_states)
429
+ value_states = self.v_proj(cross_attention_states)
430
+ key_states = key_states.view(bsz, -1, self.num_key_value_heads, self.head_dim).transpose(1, 2)
431
+ value_states = value_states.view(bsz, -1, self.num_key_value_heads, self.head_dim).transpose(1, 2)
432
+
433
+ key_states = self.k_norm(key_states)
434
+ if past_key_values is not None:
435
+ # if we have a new image + new tokens, we only computed key_states on that new image
436
+ # we still update the cross key states, past_image, new_image. And use it!
437
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
438
+ elif past_key_values is not None and past_key_values.get_seq_length() > 0:
439
+ key_states, value_states = (
440
+ past_key_values.layers[self.layer_idx].keys,
441
+ past_key_values.layers[self.layer_idx].values,
442
+ )
443
+ else:
444
+ raise ValueError(
445
+ "Cross attention layer can't find neither `cross_attn_states` nor cached values for key/values!"
446
+ )
447
+
448
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
449
+ self.config._attn_implementation, eager_attention_forward
450
+ )
451
+
452
+ attn_output, attn_weights = attention_interface(
453
+ self,
454
+ query_states,
455
+ key_states,
456
+ value_states,
457
+ attention_mask,
458
+ dropout=0.0 if not self.training else self.dropout,
459
+ scaling=self.scaling,
460
+ **kwargs,
461
+ )
462
+
463
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
464
+ attn_output = self.o_proj(attn_output)
465
+
466
+ return attn_output, attn_weights
467
+
468
+
469
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
470
+ def rotate_half(x):
471
+ """Rotates half the hidden dims of the input."""
472
+ x1 = x[..., : x.shape[-1] // 2]
473
+ x2 = x[..., x.shape[-1] // 2 :]
474
+ return torch.cat((-x2, x1), dim=-1)
475
+
476
+
477
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
478
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
479
+ """Applies Rotary Position Embedding to the query and key tensors.
480
+
481
+ Args:
482
+ q (`torch.Tensor`): The query tensor.
483
+ k (`torch.Tensor`): The key tensor.
484
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
485
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
486
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
487
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
488
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
489
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
490
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
491
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
492
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
493
+ Returns:
494
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
495
+ """
496
+ cos = cos.unsqueeze(unsqueeze_dim)
497
+ sin = sin.unsqueeze(unsqueeze_dim)
498
+ q_embed = (q * cos) + (rotate_half(q) * sin)
499
+ k_embed = (k * cos) + (rotate_half(k) * sin)
500
+ return q_embed, k_embed
501
+
502
+
503
+ class MllamaTextSelfAttention(nn.Module):
504
+ def __init__(self, config: MllamaTextConfig, layer_idx: int):
505
+ super().__init__()
506
+ self.config = config
507
+ self.num_heads = config.num_attention_heads
508
+ self.dropout = config.dropout
509
+ self.hidden_size = config.hidden_size
510
+ self.num_key_value_heads = config.num_key_value_heads
511
+ self.head_dim = config.hidden_size // self.num_heads
512
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
513
+ self.scaling = self.head_dim**-0.5
514
+
515
+ self.layer_idx = layer_idx
516
+ self.is_causal = True
517
+
518
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
519
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
520
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
521
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
522
+
523
+ def forward(
524
+ self,
525
+ hidden_states: torch.Tensor,
526
+ attention_mask: torch.Tensor,
527
+ position_embeddings: torch.Tensor,
528
+ past_key_values=None,
529
+ **kwargs,
530
+ ):
531
+ bsz, q_len, _ = hidden_states.size()
532
+
533
+ query_states = self.q_proj(hidden_states)
534
+ key_states = self.k_proj(hidden_states)
535
+ value_states = self.v_proj(hidden_states)
536
+
537
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
538
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
539
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
540
+
541
+ cos, sin = position_embeddings
542
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
543
+
544
+ if past_key_values is not None:
545
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
546
+
547
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
548
+ self.config._attn_implementation, eager_attention_forward
549
+ )
550
+
551
+ attn_output, attn_weights = attention_interface(
552
+ self,
553
+ query_states,
554
+ key_states,
555
+ value_states,
556
+ attention_mask,
557
+ dropout=0.0 if not self.training else self.dropout,
558
+ scaling=self.scaling,
559
+ **kwargs,
560
+ )
561
+
562
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
563
+ attn_output = self.o_proj(attn_output)
564
+
565
+ return attn_output, attn_weights
566
+
567
+
568
+ # Copied from transformers.models.gemma2.modeling_gemma2.Gemma2MLP with Gemma2->MllamaText
569
+ class MllamaTextMLP(nn.Module):
570
+ def __init__(self, config):
571
+ super().__init__()
572
+ self.config = config
573
+ self.hidden_size = config.hidden_size
574
+ self.intermediate_size = config.intermediate_size
575
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
576
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
577
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
578
+ # Ignore copy
579
+ self.act_fn = ACT2FN[config.hidden_act]
580
+
581
+ def forward(self, x):
582
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
583
+ return down_proj
584
+
585
+
586
+ # Modified from transformers.models.llama.modeling_llama.LlamaDecoderLayer
587
+ class MllamaSelfAttentionDecoderLayer(GradientCheckpointingLayer):
588
+ def __init__(self, config: MllamaTextConfig, layer_idx: int):
589
+ super().__init__()
590
+ self.hidden_size = config.hidden_size
591
+
592
+ self.self_attn = MllamaTextSelfAttention(config=config, layer_idx=layer_idx)
593
+
594
+ self.mlp = MllamaTextMLP(config)
595
+ self.input_layernorm = MllamaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
596
+ self.post_attention_layernorm = MllamaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
597
+
598
+ self.layer_idx = layer_idx
599
+
600
+ def forward(
601
+ self,
602
+ hidden_states: torch.Tensor,
603
+ cross_attention_states: torch.Tensor | None = None,
604
+ cross_attention_mask: torch.Tensor | None = None,
605
+ attention_mask: torch.Tensor | None = None,
606
+ full_text_row_masked_out_mask: tuple[torch.Tensor, torch.Tensor] | None = None,
607
+ position_ids: torch.LongTensor | None = None,
608
+ past_key_values: Cache | None = None,
609
+ use_cache: bool | None = False,
610
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
611
+ **kwargs: Unpack[FlashAttentionKwargs],
612
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
613
+ """
614
+ Args:
615
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
616
+ attention_mask (`torch.FloatTensor`, *optional*):
617
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
618
+ query_sequence_length, key_sequence_length)` if default attention is used.
619
+
620
+ use_cache (`bool`, *optional*):
621
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
622
+ (see `past_key_values`).
623
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
624
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
625
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
626
+ with `head_dim` being the embedding dimension of each attention head.
627
+ kwargs (`dict`, *optional*):
628
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
629
+ into the model
630
+ """
631
+ residual = hidden_states
632
+
633
+ hidden_states = self.input_layernorm(hidden_states)
634
+
635
+ # Self Attention
636
+ hidden_states, self_attn_weights = self.self_attn(
637
+ hidden_states=hidden_states,
638
+ attention_mask=attention_mask,
639
+ position_ids=position_ids,
640
+ past_key_values=past_key_values,
641
+ use_cache=use_cache,
642
+ position_embeddings=position_embeddings,
643
+ **kwargs,
644
+ )
645
+ hidden_states = residual + hidden_states
646
+
647
+ # Fully Connected
648
+ residual = hidden_states
649
+ hidden_states = self.post_attention_layernorm(hidden_states)
650
+ hidden_states = self.mlp(hidden_states)
651
+ hidden_states = residual + hidden_states
652
+
653
+ return hidden_states
654
+
655
+
656
+ class MllamaCrossAttentionDecoderLayer(GradientCheckpointingLayer):
657
+ """Cross-attention transformer block with tanh-gated attention and feedforward."""
658
+
659
+ def __init__(self, config: MllamaTextConfig, layer_idx: int) -> None:
660
+ super().__init__()
661
+ self.layer_idx = layer_idx
662
+ self.cross_attn = MllamaTextCrossAttention(config, layer_idx=layer_idx)
663
+
664
+ self.input_layernorm = MllamaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
665
+ self.cross_attn_attn_gate = torch.nn.Parameter(torch.zeros(1))
666
+
667
+ self.mlp = MllamaTextMLP(config)
668
+ self.post_attention_layernorm = MllamaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
669
+ self.cross_attn_mlp_gate = torch.nn.Parameter(torch.zeros(1))
670
+
671
+ def forward(
672
+ self,
673
+ hidden_states: torch.Tensor,
674
+ cross_attention_states: torch.Tensor,
675
+ cross_attention_mask: torch.Tensor,
676
+ attention_mask: torch.Tensor,
677
+ full_text_row_masked_out_mask: tuple[torch.Tensor, torch.Tensor],
678
+ position_ids: torch.LongTensor | None = None,
679
+ past_key_values: Cache | None = None,
680
+ use_cache: bool | None = False,
681
+ position_embeddings: torch.Tensor | None = None,
682
+ **kwargs: Unpack[FlashAttentionKwargs],
683
+ ) -> tuple[torch.Tensor]:
684
+ residual = hidden_states
685
+ hidden_states = self.input_layernorm(hidden_states)
686
+
687
+ hidden_states, attn_weights = self.cross_attn(
688
+ hidden_states=hidden_states,
689
+ attention_mask=cross_attention_mask,
690
+ cross_attention_states=cross_attention_states,
691
+ past_key_values=past_key_values,
692
+ **kwargs,
693
+ )
694
+ hidden_states = residual + self.cross_attn_attn_gate.tanh() * hidden_states
695
+
696
+ residual = hidden_states
697
+ hidden_states = self.post_attention_layernorm(hidden_states)
698
+ hidden_states = self.mlp(hidden_states)
699
+ if full_text_row_masked_out_mask is not None:
700
+ hidden_states = full_text_row_masked_out_mask[:, 0] * hidden_states # type: ignore
701
+ hidden_states = residual + self.cross_attn_mlp_gate.tanh() * hidden_states
702
+
703
+ return hidden_states
704
+
705
+
706
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with LlamaConfig->MllamaTextConfig,Llama->Mllama
707
+ class MllamaRotaryEmbedding(nn.Module):
708
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
709
+
710
+ def __init__(self, config: MllamaTextConfig, device=None):
711
+ super().__init__()
712
+ self.max_seq_len_cached = config.max_position_embeddings
713
+ self.original_max_seq_len = config.max_position_embeddings
714
+
715
+ self.config = config
716
+
717
+ self.rope_type = self.config.rope_parameters["rope_type"]
718
+ rope_init_fn: Callable = self.compute_default_rope_parameters
719
+ if self.rope_type != "default":
720
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
721
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
722
+
723
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
724
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
725
+
726
+ @staticmethod
727
+ def compute_default_rope_parameters(
728
+ config: MllamaTextConfig | None = None,
729
+ device: Optional["torch.device"] = None,
730
+ seq_len: int | None = None,
731
+ ) -> tuple["torch.Tensor", float]:
732
+ """
733
+ Computes the inverse frequencies according to the original RoPE implementation
734
+ Args:
735
+ config ([`~transformers.PreTrainedConfig`]):
736
+ The model configuration.
737
+ device (`torch.device`):
738
+ The device to use for initialization of the inverse frequencies.
739
+ seq_len (`int`, *optional*):
740
+ The current sequence length. Unused for this type of RoPE.
741
+ Returns:
742
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
743
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
744
+ """
745
+ base = config.rope_parameters["rope_theta"]
746
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
747
+
748
+ attention_factor = 1.0 # Unused in this type of RoPE
749
+
750
+ # Compute the inverse frequencies
751
+ inv_freq = 1.0 / (
752
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
753
+ )
754
+ return inv_freq, attention_factor
755
+
756
+ # Ignore copy
757
+ @torch.no_grad()
758
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
759
+ def forward(self, x, position_ids):
760
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
761
+ position_ids_expanded = position_ids[:, None, :].float()
762
+
763
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
764
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
765
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
766
+ emb = torch.cat((freqs, freqs), dim=-1)
767
+ cos = emb.cos() * self.attention_scaling
768
+ sin = emb.sin() * self.attention_scaling
769
+
770
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
771
+
772
+
773
+ @auto_docstring
774
+ class MllamaPreTrainedModel(PreTrainedModel):
775
+ config: MllamaConfig
776
+ base_model_prefix = "model"
777
+ input_modalities = ("image", "text")
778
+ supports_gradient_checkpointing = True
779
+ _no_split_modules = [
780
+ "MllamaVisionEncoderLayer",
781
+ "MllamaCrossAttentionDecoderLayer",
782
+ "MllamaSelfAttentionDecoderLayer",
783
+ ]
784
+ _can_compile_fullgraph = False # static cache cannot have different shapes for each layer
785
+ _supports_sdpa = True
786
+ _supports_flash_attn = True
787
+ _supports_flex_attn = True
788
+ _supports_attention_backend = True
789
+ _can_record_outputs = {
790
+ "hidden_states": [MllamaSelfAttentionDecoderLayer, MllamaCrossAttentionDecoderLayer],
791
+ "attentions": [
792
+ OutputRecorder(MllamaTextSelfAttention, index=1, layer_name="self_attn"),
793
+ OutputRecorder(MllamaTextSelfAttention, index=1, layer_name="cross_attn"),
794
+ OutputRecorder(MllamaTextCrossAttention, index=1, layer_name="cross_attn"),
795
+ ],
796
+ }
797
+
798
+ @torch.no_grad()
799
+ def _init_weights(self, module):
800
+ std = getattr(self.config, "initializer_range", self.config.get_text_config().initializer_range)
801
+
802
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
803
+ init.normal_(module.weight, mean=0.0, std=std)
804
+ if module.bias is not None:
805
+ init.zeros_(module.bias)
806
+ elif isinstance(module, nn.Embedding):
807
+ init.normal_(module.weight, mean=0.0, std=std)
808
+ # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
809
+ if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
810
+ init.zeros_(module.weight[module.padding_idx])
811
+ elif isinstance(module, nn.LayerNorm):
812
+ init.ones_(module.weight)
813
+ init.zeros_(module.bias)
814
+ elif isinstance(module, MllamaTextRMSNorm):
815
+ init.ones_(module.weight)
816
+ elif isinstance(module, MllamaVisionModel):
817
+ init.normal_(module.class_embedding, std=std)
818
+ elif isinstance(module, MllamaPrecomputedPositionEmbedding):
819
+ init.normal_(module.embedding, std=std)
820
+ init.zeros_(module.gate)
821
+ elif isinstance(module, MllamaVisionEncoderLayer) and module.is_gated:
822
+ init.normal_(module.gate_attn, std=std)
823
+ init.normal_(module.gate_ffn, std=std)
824
+ elif isinstance(module, MllamaCrossAttentionDecoderLayer):
825
+ init.zeros_(module.cross_attn_attn_gate)
826
+ init.zeros_(module.cross_attn_mlp_gate)
827
+ elif isinstance(module, MllamaPrecomputedAspectRatioEmbedding):
828
+ if module.is_gated:
829
+ init.zeros_(module.gate)
830
+ elif isinstance(module, MllamaRotaryEmbedding):
831
+ rope_fn = (
832
+ ROPE_INIT_FUNCTIONS[module.rope_type]
833
+ if module.rope_type != "default"
834
+ else module.compute_default_rope_parameters
835
+ )
836
+ buffer_value, _ = rope_fn(module.config)
837
+ init.copy_(module.inv_freq, buffer_value)
838
+ init.copy_(module.original_inv_freq, buffer_value)
839
+
840
+
841
+ @auto_docstring(
842
+ custom_intro="""
843
+ The Mllama Vision Model which consists of two vision encoders.
844
+ """
845
+ )
846
+ class MllamaVisionModel(MllamaPreTrainedModel):
847
+ config: MllamaVisionConfig
848
+ base_model_prefix = "vision_model"
849
+ input_modalities = ("image",)
850
+
851
+ def __init__(self, config: MllamaVisionConfig):
852
+ super().__init__(config)
853
+ self.image_size = config.image_size
854
+ self.patch_size = config.patch_size
855
+ self.max_num_tiles = config.max_num_tiles
856
+ self.hidden_size = config.hidden_size
857
+ self.num_channels = config.num_channels
858
+ self.intermediate_layers_indices = config.intermediate_layers_indices
859
+
860
+ self.num_patches = (self.image_size // self.patch_size) ** 2 + 1
861
+ self.scale = config.hidden_size**-0.5
862
+
863
+ self.patch_embedding = nn.Conv2d(
864
+ in_channels=config.num_channels,
865
+ out_channels=self.hidden_size,
866
+ kernel_size=self.patch_size,
867
+ stride=self.patch_size,
868
+ padding="valid",
869
+ bias=False,
870
+ )
871
+
872
+ self.class_embedding = nn.Parameter(self.scale * torch.randn(self.hidden_size))
873
+ self.gated_positional_embedding = MllamaPrecomputedPositionEmbedding(config)
874
+
875
+ self.pre_tile_positional_embedding = MllamaPrecomputedAspectRatioEmbedding(config, is_gated=True)
876
+ self.post_tile_positional_embedding = MllamaPrecomputedAspectRatioEmbedding(config, is_gated=True)
877
+
878
+ # layer norms
879
+ self.layernorm_pre = nn.LayerNorm(self.hidden_size)
880
+ self.layernorm_post = nn.LayerNorm(self.hidden_size)
881
+
882
+ # encoders
883
+ self.transformer = MllamaVisionEncoder(config, config.num_hidden_layers, is_gated=False)
884
+ self.global_transformer = MllamaVisionEncoder(config, config.num_global_layers, is_gated=True)
885
+
886
+ self.post_init()
887
+
888
+ def get_input_embeddings(self):
889
+ """
890
+ This function is used to fetch the first embedding layer to activate grads on inputs.
891
+ """
892
+ return self.patch_embedding
893
+
894
+ def apply_class_embedding(self, hidden_state: torch.Tensor) -> torch.Tensor:
895
+ batch_size, _, hidden_size = hidden_state.shape
896
+ class_embedding = self.class_embedding.expand(batch_size, 1, hidden_size)
897
+ hidden_state = torch.cat([class_embedding, hidden_state], dim=1)
898
+ return hidden_state
899
+
900
+ @merge_with_config_defaults
901
+ @capture_outputs
902
+ @auto_docstring
903
+ def forward(
904
+ self, pixel_values: torch.Tensor, aspect_ratio_ids: torch.Tensor, aspect_ratio_mask: torch.Tensor, **kwargs
905
+ ) -> BaseModelOutput:
906
+ r"""
907
+ aspect_ratio_ids (`torch.Tensor` of shape `(batch_size, max_num_images)`, *optional*):
908
+ Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image.
909
+ These ids correspond to indices in the model's list of supported aspect ratios, offset by 1.
910
+
911
+ For example, if the model supports aspect ratios [[1, 1], [1, 2], [2, 1]]:
912
+ - An image with aspect ratio [1, 1] would have ID 1
913
+ - An image with aspect ratio [1, 2] would have ID 2
914
+ - An image with aspect ratio [2, 1] would have ID 3
915
+
916
+ The id 0 is reserved for padding (i.e., no image).
917
+
918
+ If an image has aspect ratio [1, 2], that means it was split into 2 tiles horizontally, and its `aspect_ratio_id` would be 2.
919
+ aspect_ratio_mask (`torch.Tensor` of shape `(batch_size, max_num_images, max_num_tiles)`, *optional*):
920
+ Mask to avoid performing attention on padding tiles. Mask values selected in `[0, 1]`:
921
+
922
+ - 1 for tiles that are **not masked**,
923
+ - 0 for tiles that are **masked**.
924
+
925
+ Example:
926
+
927
+ ```python
928
+ >>> from PIL import Image
929
+ >>> import httpx
930
+ >>> from io import BytesIO
931
+ >>> from transformers import AutoProcessor, MllamaVisionModel
932
+
933
+ >>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
934
+ >>> model = MllamaVisionModel.from_pretrained(checkpoint)
935
+ >>> processor = AutoProcessor.from_pretrained(checkpoint)
936
+
937
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
938
+ >>> with httpx.stream("GET", url) as response:
939
+ ... image = Image.open(BytesIO(response.read()))
940
+ >>> inputs = processor(images=image, return_tensors="pt")
941
+
942
+ >>> output = model(**inputs)
943
+
944
+ >>> print(output.last_hidden_state.shape)
945
+ torch.Size([1, 1, 4, 1025, 7680])
946
+ ```
947
+ """
948
+ batch_size, num_concurrent_media, num_tiles, num_channels, height, width = pixel_values.shape
949
+
950
+ pixel_values = pixel_values.reshape(batch_size * num_concurrent_media * num_tiles, num_channels, height, width)
951
+ aspect_ratio_ids = aspect_ratio_ids.reshape(batch_size * num_concurrent_media, -1)
952
+
953
+ # Patch embedding
954
+ target_dtype = self.patch_embedding.weight.dtype
955
+ target_device = self.patch_embedding.weight.device
956
+ patch_embeds = self.patch_embedding(pixel_values.to(target_device, target_dtype))
957
+ hidden_state = patch_embeds.flatten(2).transpose(1, 2)
958
+
959
+ # Tile embeddings
960
+ _, num_patches, dim = hidden_state.shape
961
+ hidden_state = hidden_state.reshape(batch_size * num_concurrent_media, num_tiles, -1, dim)
962
+ hidden_state = self.pre_tile_positional_embedding(hidden_state, aspect_ratio_ids)
963
+
964
+ # Add cls token
965
+ hidden_state = hidden_state.reshape(batch_size * num_concurrent_media * num_tiles, num_patches, dim)
966
+ hidden_state = self.apply_class_embedding(hidden_state)
967
+ num_patches += 1
968
+
969
+ # Position embeddings
970
+ hidden_state = hidden_state.reshape(batch_size * num_concurrent_media, num_tiles, num_patches, dim)
971
+ hidden_state = self.gated_positional_embedding(hidden_state, aspect_ratio_ids)
972
+
973
+ hidden_state = self.layernorm_pre(hidden_state)
974
+
975
+ # Compute the number of tokens to pad
976
+ num_padding_patches = (8 - (hidden_state.shape[-2] % 8)) % 8
977
+ # Compute padding tuple for pad function
978
+ padding = (0, 0, 0, num_padding_patches) # (pad_left, pad_right, pad_left for dim -2, pad_right for dim -2)
979
+ # Pad the tensor
980
+ hidden_state = F.pad(hidden_state, padding, mode="constant", value=0)
981
+ slice_index = -num_padding_patches if num_padding_patches > 0 else None
982
+
983
+ # Prepare attention mask
984
+ attention_mask = aspect_ratio_mask.reshape(batch_size * num_concurrent_media, -1)
985
+ attention_mask = _prepare_aspect_ratio_attention_mask(
986
+ aspect_ratio_mask=attention_mask,
987
+ num_patches=self.num_patches,
988
+ target_length=hidden_state.shape[2],
989
+ dtype=self.dtype,
990
+ )
991
+
992
+ # Apply encoder
993
+ hidden_state = hidden_state.view(batch_size * num_concurrent_media, -1, dim)
994
+ output = self.transformer(
995
+ hidden_state,
996
+ attention_mask=attention_mask,
997
+ )
998
+ hidden_state = output.last_hidden_state
999
+
1000
+ hidden_state = self.layernorm_post(hidden_state)
1001
+
1002
+ # Apply global encoder
1003
+ hidden_state = hidden_state.reshape(
1004
+ batch_size * num_concurrent_media, num_tiles, num_patches + num_padding_patches, dim
1005
+ )
1006
+ hidden_state = self.post_tile_positional_embedding(hidden_state, aspect_ratio_ids)
1007
+ hidden_state = hidden_state.reshape(
1008
+ batch_size * num_concurrent_media, num_tiles * (num_patches + num_padding_patches), dim
1009
+ )
1010
+ global_output = self.global_transformer(
1011
+ hidden_state,
1012
+ attention_mask=attention_mask,
1013
+ )
1014
+ hidden_state = global_output.last_hidden_state
1015
+
1016
+ # Remove padding form hidden state
1017
+ hidden_state = hidden_state.reshape(
1018
+ batch_size * num_concurrent_media, num_tiles, num_patches + num_padding_patches, dim
1019
+ )
1020
+ hidden_state = hidden_state[:, :, :slice_index]
1021
+ hidden_state = hidden_state.reshape(batch_size, num_concurrent_media, num_tiles, num_patches, dim)
1022
+
1023
+ # Collect intermediate layer outputs from encoder output
1024
+ all_intermediate_hidden_states = [output.hidden_states[i] for i in self.intermediate_layers_indices]
1025
+ intermediate_hidden_states = torch.stack(all_intermediate_hidden_states, dim=-1)
1026
+
1027
+ # Remove padding from intermediate hidden states
1028
+ intermediate_hidden_states = intermediate_hidden_states.reshape(
1029
+ batch_size * num_concurrent_media, num_tiles, num_patches + num_padding_patches, -1
1030
+ )
1031
+ intermediate_hidden_states = intermediate_hidden_states[:, :, :slice_index]
1032
+ intermediate_hidden_states = intermediate_hidden_states.reshape(
1033
+ batch_size, num_concurrent_media, num_tiles, num_patches, -1
1034
+ )
1035
+
1036
+ # Concatenate final hidden state and intermediate hidden states
1037
+ hidden_state = torch.cat([hidden_state, intermediate_hidden_states], dim=-1)
1038
+
1039
+ return BaseModelOutput(last_hidden_state=hidden_state)
1040
+
1041
+
1042
+ @auto_docstring(
1043
+ custom_intro="""
1044
+ The Mllama Text Model which consists of transformer with self and cross attention layers.
1045
+ """
1046
+ )
1047
+ class MllamaTextModel(MllamaPreTrainedModel):
1048
+ config: MllamaTextConfig
1049
+ base_model_prefix = "language_model.model"
1050
+ input_modalities = ("text",)
1051
+
1052
+ def __init__(self, config: MllamaTextConfig):
1053
+ super().__init__(config)
1054
+ self.padding_idx = config.pad_token_id
1055
+ self.vocab_size = config.vocab_size
1056
+ self.embed_tokens = nn.Embedding(config.vocab_size + 8, config.hidden_size, self.padding_idx)
1057
+ self.cross_attention_layers = config.cross_attention_layers
1058
+
1059
+ layers = []
1060
+ for layer_idx in range(config.num_hidden_layers):
1061
+ if layer_idx in self.cross_attention_layers:
1062
+ layers.append(MllamaCrossAttentionDecoderLayer(config, layer_idx))
1063
+ else:
1064
+ layers.append(MllamaSelfAttentionDecoderLayer(config, layer_idx))
1065
+
1066
+ self.layers = nn.ModuleList(layers)
1067
+ self.norm = MllamaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1068
+ self.rotary_emb = MllamaRotaryEmbedding(config=config)
1069
+
1070
+ self.gradient_checkpointing = False
1071
+ self.post_init()
1072
+
1073
+ @merge_with_config_defaults
1074
+ @capture_outputs
1075
+ @can_return_tuple
1076
+ @auto_docstring
1077
+ def forward(
1078
+ self,
1079
+ input_ids: torch.LongTensor | None = None,
1080
+ attention_mask: torch.Tensor | None = None,
1081
+ position_ids: torch.LongTensor | None = None,
1082
+ cross_attention_states: torch.FloatTensor | None = None,
1083
+ cross_attention_mask: torch.Tensor | None = None,
1084
+ full_text_row_masked_out_mask: tuple[torch.Tensor, torch.Tensor] | None = None,
1085
+ past_key_values: Cache | None = None,
1086
+ inputs_embeds: torch.FloatTensor | None = None,
1087
+ use_cache: bool | None = None,
1088
+ **kwargs: Unpack[FlashAttentionKwargs],
1089
+ ) -> BaseModelOutputWithPast:
1090
+ r"""
1091
+ cross_attention_states (`torch.FloatTensor`, *optional*):
1092
+ Output of the vision model, used for cross-attention. This tensor contains the processed image features that
1093
+ the language model will attend to.
1094
+ cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
1095
+ Cross-attention mask to control the interaction between text tokens and image tiles.
1096
+ This 4D tensor defines which image tiles each text token should attend to.
1097
+
1098
+ For each text token (in seq_length):
1099
+ - 1 indicates the token **should attend** to the corresponding image tile
1100
+ - 0 indicates the token **should not attend** to the corresponding image tile
1101
+ full_text_row_masked_out_mask (`tuple[torch.Tensor, torch.Tensor]`, *optional*):
1102
+ A tuple containing two tensors that mask out rows in the cross-attention mechanism:
1103
+ - The first tensor has shape `(batch_size, 1, seq_length, 1)` and contains values of 0 or 1.
1104
+ A value of 0 indicates that the corresponding text token's entire row in the cross-attention
1105
+ matrix should be masked out (all image tokens ignored).
1106
+ - The second tensor has the same shape and is used internally to apply the masking during
1107
+ the forward pass of cross-attention layers.
1108
+ This mask is derived from the cross_attention_mask and is used to handle cases where a text token
1109
+ should not attend to any image token.
1110
+
1111
+ Example:
1112
+
1113
+ ```python
1114
+ >>> from transformers import AutoProcessor, MllamaTextModel
1115
+
1116
+ >>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
1117
+ >>> model = MllamaTextModel.from_pretrained(checkpoint)
1118
+ >>> processor = AutoProcessor.from_pretrained(checkpoint)
1119
+
1120
+ >>> text = "<|image|>If I had to write a haiku for this one"
1121
+ >>> inputs = processor(text=text, return_tensors="pt")
1122
+
1123
+ >>> output = model(**inputs)
1124
+
1125
+ >>> print(output.last_hidden_state.shape)
1126
+ torch.Size([1, 13, 4096])
1127
+ ```
1128
+ """
1129
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1130
+
1131
+ if (input_ids is None) ^ (inputs_embeds is not None):
1132
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1133
+
1134
+ if inputs_embeds is None:
1135
+ inputs_embeds = self.embed_tokens(input_ids)
1136
+
1137
+ hidden_states = inputs_embeds
1138
+
1139
+ if use_cache and past_key_values is None:
1140
+ past_key_values = DynamicCache(config=self.config)
1141
+
1142
+ if position_ids is None:
1143
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1144
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
1145
+ position_ids = position_ids.unsqueeze(0)
1146
+
1147
+ causal_mask = create_causal_mask(
1148
+ config=self.config,
1149
+ inputs_embeds=inputs_embeds,
1150
+ attention_mask=attention_mask,
1151
+ past_key_values=past_key_values,
1152
+ position_ids=position_ids,
1153
+ )
1154
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
1155
+
1156
+ # decoder layers
1157
+ for idx, decoder_layer in enumerate(self.layers):
1158
+ # For text-only path we should skip cross attention layers.
1159
+ # Let's check if the layer is cross attention layer and if we have cross attention states
1160
+ # or cached cross attention states.
1161
+ is_cross_attention_layer = idx in self.cross_attention_layers
1162
+ is_cross_attention_cache_empty = past_key_values is None or (
1163
+ past_key_values is not None and past_key_values.get_seq_length(idx) == 0
1164
+ )
1165
+
1166
+ if is_cross_attention_layer and cross_attention_states is None and is_cross_attention_cache_empty:
1167
+ continue
1168
+
1169
+ hidden_states = decoder_layer(
1170
+ hidden_states,
1171
+ cross_attention_states=cross_attention_states,
1172
+ cross_attention_mask=cross_attention_mask,
1173
+ attention_mask=causal_mask,
1174
+ full_text_row_masked_out_mask=full_text_row_masked_out_mask,
1175
+ position_ids=position_ids,
1176
+ past_key_values=past_key_values,
1177
+ use_cache=use_cache,
1178
+ position_embeddings=position_embeddings,
1179
+ **kwargs,
1180
+ )
1181
+
1182
+ hidden_states = self.norm(hidden_states)
1183
+
1184
+ return BaseModelOutputWithPast(
1185
+ last_hidden_state=hidden_states,
1186
+ past_key_values=past_key_values,
1187
+ )
1188
+
1189
+
1190
+ @auto_docstring(
1191
+ custom_intro="""
1192
+ The Mllama Text Model with a language modeling head on top.
1193
+ """
1194
+ )
1195
+ class MllamaForCausalLM(MllamaPreTrainedModel, GenerationMixin):
1196
+ config: MllamaTextConfig
1197
+ _can_compile_fullgraph = True # only the LLM without cross attn can do compile
1198
+ base_model_prefix = "language_model"
1199
+
1200
+ def __init__(self, config):
1201
+ super().__init__(config.get_text_config())
1202
+ self.text_config = config.get_text_config()
1203
+ self.vocab_size = self.text_config.vocab_size
1204
+ self.model = MllamaTextModel._from_config(self.text_config)
1205
+ self.lm_head = nn.Linear(self.text_config.hidden_size, self.vocab_size, bias=False)
1206
+
1207
+ self.post_init()
1208
+
1209
+ @can_return_tuple
1210
+ @auto_docstring
1211
+ def forward(
1212
+ self,
1213
+ input_ids: torch.LongTensor | None = None,
1214
+ attention_mask: torch.Tensor | None = None,
1215
+ position_ids: torch.LongTensor | None = None,
1216
+ cross_attention_states: torch.LongTensor | None = None,
1217
+ cross_attention_mask: torch.LongTensor | None = None,
1218
+ full_text_row_masked_out_mask: tuple[torch.Tensor, torch.Tensor] | None = None,
1219
+ past_key_values: Cache | None = None,
1220
+ inputs_embeds: torch.FloatTensor | None = None,
1221
+ labels: torch.LongTensor | None = None,
1222
+ use_cache: bool | None = None,
1223
+ logits_to_keep: int | torch.Tensor = 0,
1224
+ **kwargs: Unpack[TransformersKwargs],
1225
+ ) -> tuple | CausalLMOutputWithPast:
1226
+ r"""
1227
+ cross_attention_states (`torch.FloatTensor`, *optional*):
1228
+ Output of the vision model, used for cross-attention. This tensor contains the processed image features that
1229
+ the language model will attend to.
1230
+ cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
1231
+ Cross-attention mask to control the interaction between text tokens and image tiles.
1232
+ This 4D tensor defines which image tiles each text token should attend to.
1233
+
1234
+ For each text token (in seq_length):
1235
+ - 1 indicates the token **should attend** to the corresponding image tile
1236
+ - 0 indicates the token **should not attend** to the corresponding image tile
1237
+ full_text_row_masked_out_mask (`tuple[torch.Tensor, torch.Tensor]`, *optional*):
1238
+ A tuple containing two tensors that mask out rows in the cross-attention mechanism:
1239
+ - The first tensor has shape `(batch_size, 1, seq_length, 1)` and contains values of 0 or 1.
1240
+ A value of 0 indicates that the corresponding text token's entire row in the cross-attention
1241
+ matrix should be masked out (all image tokens ignored).
1242
+ - The second tensor has the same shape and is used internally to apply the masking during
1243
+ the forward pass of cross-attention layers.
1244
+ This mask is derived from the cross_attention_mask and is used to handle cases where a text token
1245
+ should not attend to any image token.
1246
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1247
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1248
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1249
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1250
+
1251
+ Example:
1252
+
1253
+ ```python
1254
+ >>> from transformers import AutoTokenizer, MllamaForCausalLM
1255
+
1256
+ >>> model = MllamaForCausalLM.from_pretrained("Llama-3.2-11B-Vision")
1257
+ >>> tokenizer = AutoTokenizer.from_pretrained("Llama-3.2-11B-Vision")
1258
+
1259
+ >>> prompt = "If I had to write a haiku, it would be:"
1260
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1261
+
1262
+ >>> # Generate
1263
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=40, do_sample=True, temperature=0.6)
1264
+ >>> result = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1265
+ >>> print(result)
1266
+ If I had to write a haiku, it would be: "Snowflakes gently fall" - simple, yet peaceful.
1267
+ I love the idea of snowflakes gently falling, each one
1268
+ ```
1269
+ """
1270
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1271
+ outputs = self.model(
1272
+ input_ids=input_ids,
1273
+ cross_attention_states=cross_attention_states,
1274
+ attention_mask=attention_mask,
1275
+ position_ids=position_ids,
1276
+ cross_attention_mask=cross_attention_mask,
1277
+ full_text_row_masked_out_mask=full_text_row_masked_out_mask,
1278
+ past_key_values=past_key_values,
1279
+ inputs_embeds=inputs_embeds,
1280
+ use_cache=use_cache,
1281
+ **kwargs,
1282
+ )
1283
+
1284
+ hidden_states = outputs.last_hidden_state
1285
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1286
+ logits = self.lm_head(hidden_states[:, slice_indices, :]).float()
1287
+
1288
+ loss = None
1289
+ if labels is not None:
1290
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
1291
+
1292
+ return CausalLMOutputWithPast(
1293
+ loss=loss,
1294
+ logits=logits,
1295
+ past_key_values=outputs.past_key_values,
1296
+ hidden_states=outputs.hidden_states,
1297
+ attentions=outputs.attentions,
1298
+ )
1299
+
1300
+
1301
+ @auto_docstring(
1302
+ custom_intro="""
1303
+ The Mllama model which consists of a vision encoder and a language model without language modeling head.
1304
+ """
1305
+ )
1306
+ class MllamaModel(MllamaPreTrainedModel):
1307
+ def __init__(self, config: MllamaConfig):
1308
+ super().__init__(config)
1309
+ self.vocab_size = config.text_config.vocab_size
1310
+ self.hidden_size = config.text_config.hidden_size
1311
+ self.max_num_tiles = config.vision_config.max_num_tiles
1312
+ self.vision_output_dim = config.vision_config.vision_output_dim
1313
+
1314
+ self.vision_model = MllamaVisionModel._from_config(config.vision_config)
1315
+ self.language_model = MllamaTextModel._from_config(config.text_config)
1316
+ self.multi_modal_projector = nn.Linear(
1317
+ config.vision_config.vision_output_dim,
1318
+ config.text_config.hidden_size,
1319
+ bias=True,
1320
+ )
1321
+ self.post_init()
1322
+
1323
+ @can_return_tuple
1324
+ @auto_docstring
1325
+ def forward(
1326
+ self,
1327
+ input_ids: torch.LongTensor | None = None,
1328
+ pixel_values: torch.FloatTensor | None = None,
1329
+ aspect_ratio_mask: torch.Tensor | None = None,
1330
+ aspect_ratio_ids: torch.Tensor | None = None,
1331
+ attention_mask: torch.Tensor | None = None,
1332
+ cross_attention_mask: torch.Tensor | None = None,
1333
+ cross_attention_states: torch.Tensor | None = None,
1334
+ position_ids: torch.LongTensor | None = None,
1335
+ past_key_values: Cache | None = None,
1336
+ inputs_embeds: torch.FloatTensor | None = None,
1337
+ use_cache: bool | None = None,
1338
+ **kwargs: Unpack[FlashAttentionKwargs],
1339
+ ) -> BaseModelOutputWithPast:
1340
+ r"""
1341
+ aspect_ratio_mask (`torch.Tensor` of shape `(batch_size, max_num_images, max_num_tiles)`, *optional*):
1342
+ Mask to avoid performing attention on padding tiles. Mask values selected in `[0, 1]`:
1343
+
1344
+ - 1 for tiles that are **not masked**,
1345
+ - 0 for tiles that are **masked**.
1346
+ aspect_ratio_ids (`torch.Tensor` of shape `(batch_size, max_num_images)`, *optional*):
1347
+ Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image.
1348
+ These ids correspond to indices in the model's list of supported aspect ratios, offset by 1.
1349
+
1350
+ For example, if the model supports aspect ratios [[1, 1], [1, 2], [2, 1]]:
1351
+ - An image with aspect ratio [1, 1] would have ID 1
1352
+ - An image with aspect ratio [1, 2] would have ID 2
1353
+ - An image with aspect ratio [2, 1] would have ID 3
1354
+
1355
+ The id 0 is reserved for padding (i.e., no image).
1356
+
1357
+ If an image has aspect ratio [1, 2], that means it was split into 2 tiles horizontally, and its `aspect_ratio_id` would be 2.
1358
+ cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
1359
+ Cross-attention mask to control the interaction between text tokens and image tiles.
1360
+ This 4D tensor defines which image tiles each text token should attend to.
1361
+
1362
+ For each text token (in seq_length):
1363
+ - 1 indicates the token **should attend** to the corresponding image tile
1364
+ - 0 indicates the token **should not attend** to the corresponding image tile
1365
+ cross_attention_states (`torch.FloatTensor`, *optional*):
1366
+ Output of the vision model, used for cross-attention. This tensor contains the processed image features that
1367
+ the language model will attend to.
1368
+ """
1369
+ if (input_ids is None) ^ (inputs_embeds is not None):
1370
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1371
+
1372
+ if pixel_values is not None and cross_attention_states is not None:
1373
+ raise ValueError("`pixel_values` and `cross_attention_states` cannot be provided simultaneously")
1374
+
1375
+ if pixel_values is not None:
1376
+ if aspect_ratio_ids is None:
1377
+ raise ValueError("`aspect_ratio_ids` must be provided if `pixel_values` is provided")
1378
+ # get vision tokens from vision model
1379
+ vision_outputs = self.vision_model(
1380
+ pixel_values=pixel_values,
1381
+ aspect_ratio_ids=aspect_ratio_ids,
1382
+ aspect_ratio_mask=aspect_ratio_mask,
1383
+ )
1384
+ cross_attention_states = vision_outputs.last_hidden_state
1385
+ cross_attention_states = self.multi_modal_projector(cross_attention_states).reshape(
1386
+ -1, cross_attention_states.shape[-2], self.hidden_size
1387
+ )
1388
+
1389
+ if cross_attention_mask is not None:
1390
+ cross_attention_mask, full_text_row_masked_out_mask = _prepare_cross_attention_mask(
1391
+ cross_attention_mask,
1392
+ num_vision_tokens=self.vision_model.num_patches,
1393
+ dtype=self.dtype,
1394
+ )
1395
+ else:
1396
+ full_text_row_masked_out_mask = None
1397
+
1398
+ if cross_attention_mask is not None:
1399
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1400
+ seq_len = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1401
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1402
+ current_pos = torch.arange(seq_len, device=device) + past_seen_tokens
1403
+
1404
+ cross_attention_mask = cross_attention_mask[:, :, current_pos]
1405
+ full_text_row_masked_out_mask = full_text_row_masked_out_mask[:, :, current_pos]
1406
+
1407
+ outputs = self.language_model(
1408
+ input_ids=input_ids,
1409
+ attention_mask=attention_mask,
1410
+ position_ids=position_ids,
1411
+ cross_attention_states=cross_attention_states,
1412
+ cross_attention_mask=cross_attention_mask,
1413
+ full_text_row_masked_out_mask=full_text_row_masked_out_mask,
1414
+ past_key_values=past_key_values,
1415
+ use_cache=use_cache,
1416
+ inputs_embeds=inputs_embeds,
1417
+ **kwargs,
1418
+ )
1419
+
1420
+ return BaseModelOutputWithPast(
1421
+ last_hidden_state=outputs.last_hidden_state,
1422
+ past_key_values=outputs.past_key_values,
1423
+ hidden_states=outputs.hidden_states,
1424
+ attentions=outputs.attentions,
1425
+ )
1426
+
1427
+
1428
+ @auto_docstring(
1429
+ custom_intro="""
1430
+ The Mllama model which consists of a vision encoder and a language model.
1431
+ """,
1432
+ )
1433
+ class MllamaForConditionalGeneration(MllamaPreTrainedModel, GenerationMixin):
1434
+ # _tied_weights_keys = {"lm_head.weight": "model.language_moddel.embed_tokens.weight"}
1435
+
1436
+ def __init__(self, config: MllamaConfig):
1437
+ super().__init__(config)
1438
+ self.model = MllamaModel(config)
1439
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
1440
+ self.post_init()
1441
+
1442
+ @can_return_tuple
1443
+ @auto_docstring
1444
+ def forward(
1445
+ self,
1446
+ input_ids: torch.LongTensor | None = None,
1447
+ pixel_values: torch.FloatTensor | None = None,
1448
+ aspect_ratio_mask: torch.Tensor | None = None,
1449
+ aspect_ratio_ids: torch.Tensor | None = None,
1450
+ attention_mask: torch.Tensor | None = None,
1451
+ cross_attention_mask: torch.Tensor | None = None,
1452
+ cross_attention_states: torch.Tensor | None = None,
1453
+ position_ids: torch.LongTensor | None = None,
1454
+ past_key_values: Cache | None = None,
1455
+ inputs_embeds: torch.FloatTensor | None = None,
1456
+ labels: torch.LongTensor | None = None,
1457
+ use_cache: bool | None = None,
1458
+ logits_to_keep: int | torch.Tensor = 0,
1459
+ **kwargs: Unpack[TransformersKwargs],
1460
+ ) -> tuple | CausalLMOutputWithPast:
1461
+ r"""
1462
+ aspect_ratio_mask (`torch.Tensor` of shape `(batch_size, max_num_images, max_num_tiles)`, *optional*):
1463
+ Mask to avoid performing attention on padding tiles. Mask values selected in `[0, 1]`:
1464
+
1465
+ - 1 for tiles that are **not masked**,
1466
+ - 0 for tiles that are **masked**.
1467
+ aspect_ratio_ids (`torch.Tensor` of shape `(batch_size, max_num_images)`, *optional*):
1468
+ Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image.
1469
+ These ids correspond to indices in the model's list of supported aspect ratios, offset by 1.
1470
+
1471
+ For example, if the model supports aspect ratios [[1, 1], [1, 2], [2, 1]]:
1472
+ - An image with aspect ratio [1, 1] would have ID 1
1473
+ - An image with aspect ratio [1, 2] would have ID 2
1474
+ - An image with aspect ratio [2, 1] would have ID 3
1475
+
1476
+ The id 0 is reserved for padding (i.e., no image).
1477
+
1478
+ If an image has aspect ratio [1, 2], that means it was split into 2 tiles horizontally, and its `aspect_ratio_id` would be 2.
1479
+ cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
1480
+ Cross-attention mask to control the interaction between text tokens and image tiles.
1481
+ This 4D tensor defines which image tiles each text token should attend to.
1482
+
1483
+ For each text token (in seq_length):
1484
+ - 1 indicates the token **should attend** to the corresponding image tile
1485
+ - 0 indicates the token **should not attend** to the corresponding image tile
1486
+ cross_attention_states (`torch.FloatTensor`, *optional*):
1487
+ Output of the vision model, used for cross-attention. This tensor contains the processed image features that
1488
+ the language model will attend to.
1489
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1490
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1491
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1492
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1493
+
1494
+ Example:
1495
+
1496
+ ```python
1497
+ >>> from PIL import Image
1498
+ >>> import httpx
1499
+ >>> from io import BytesIO
1500
+ >>> from transformers import AutoProcessor, MllamaForConditionalGeneration
1501
+
1502
+ >>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
1503
+ >>> model = MllamaForConditionalGeneration.from_pretrained(checkpoint)
1504
+ >>> processor = AutoProcessor.from_pretrained(checkpoint)
1505
+
1506
+ >>> prompt = "<|image|>If I had to write a haiku for this one"
1507
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
1508
+ >>> with httpx.stream("GET", url) as response:
1509
+ ... image = Image.open(BytesIO(response.read()))
1510
+
1511
+ >>> inputs = processor(text=prompt, images=image, return_tensors="pt")
1512
+
1513
+ >>> # Generate
1514
+ >>> output = model.generate(**inputs, max_new_tokens=15)
1515
+
1516
+ >>> prompt_len = inputs.input_ids.shape[-1]
1517
+ >>> generated_ids = output[:, prompt_len:]
1518
+ >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
1519
+ >>> print(generated_text)
1520
+ [', it would be:.\\nA stop sign in Chinatown.\\n']
1521
+ ```
1522
+ """
1523
+ outputs = self.model(
1524
+ input_ids=input_ids,
1525
+ pixel_values=pixel_values,
1526
+ aspect_ratio_mask=aspect_ratio_mask,
1527
+ aspect_ratio_ids=aspect_ratio_ids,
1528
+ cross_attention_mask=cross_attention_mask,
1529
+ cross_attention_states=cross_attention_states,
1530
+ attention_mask=attention_mask,
1531
+ position_ids=position_ids,
1532
+ past_key_values=past_key_values,
1533
+ inputs_embeds=inputs_embeds,
1534
+ use_cache=use_cache,
1535
+ **kwargs,
1536
+ )
1537
+
1538
+ hidden_states = outputs.last_hidden_state
1539
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1540
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1541
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1542
+
1543
+ loss = None
1544
+ if labels is not None:
1545
+ loss = self.loss_function(logits, labels, self.config.text_config.vocab_size, **kwargs)
1546
+
1547
+ return CausalLMOutputWithPast(
1548
+ loss=loss,
1549
+ logits=logits,
1550
+ past_key_values=outputs.past_key_values,
1551
+ hidden_states=outputs.hidden_states,
1552
+ attentions=outputs.attentions,
1553
+ )
1554
+
1555
+ def prepare_inputs_for_generation(
1556
+ self,
1557
+ input_ids=None,
1558
+ inputs_embeds=None,
1559
+ attention_mask=None,
1560
+ position_ids=None,
1561
+ pixel_values=None,
1562
+ aspect_ratio_ids=None,
1563
+ aspect_ratio_mask=None,
1564
+ cross_attention_mask=None,
1565
+ past_key_values=None,
1566
+ use_cache=False,
1567
+ logits_to_keep=None,
1568
+ is_first_iteration=False,
1569
+ **kwargs,
1570
+ ):
1571
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
1572
+
1573
+ model_inputs = super().prepare_inputs_for_generation(
1574
+ input_ids,
1575
+ past_key_values=past_key_values,
1576
+ use_cache=use_cache,
1577
+ inputs_embeds=inputs_embeds,
1578
+ position_ids=position_ids,
1579
+ attention_mask=attention_mask,
1580
+ pixel_values=pixel_values,
1581
+ aspect_ratio_ids=aspect_ratio_ids,
1582
+ aspect_ratio_mask=aspect_ratio_mask,
1583
+ cross_attention_mask=cross_attention_mask,
1584
+ logits_to_keep=logits_to_keep,
1585
+ is_first_iteration=is_first_iteration,
1586
+ **kwargs,
1587
+ )
1588
+
1589
+ # If we're in pre-fill or cacheless decoding step, then we need pixel_values and aspect ratios
1590
+ # to compute image hidden states, otherwise they are cached within each cross attn layer
1591
+ if not is_first_iteration and use_cache:
1592
+ model_inputs["pixel_values"] = None
1593
+ model_inputs["aspect_ratio_ids"] = None
1594
+ model_inputs["aspect_ratio_mask"] = None
1595
+
1596
+ return model_inputs
1597
+
1598
+ def _update_model_kwargs_for_generation(self, outputs, model_kwargs, is_encoder_decoder, **kwargs):
1599
+ cross_attention_mask_prev = model_kwargs.get("cross_attention_mask", None)
1600
+ model_kwargs = super()._update_model_kwargs_for_generation(
1601
+ outputs=outputs,
1602
+ model_kwargs=model_kwargs,
1603
+ is_encoder_decoder=is_encoder_decoder,
1604
+ **kwargs,
1605
+ )
1606
+
1607
+ # add cross-attn mask for new token
1608
+ if cross_attention_mask_prev is not None:
1609
+ model_kwargs["cross_attention_mask"] = torch.cat(
1610
+ [cross_attention_mask_prev, cross_attention_mask_prev[:, -1:, ...]], dim=1
1611
+ )
1612
+ return model_kwargs
1613
+
1614
+
1615
+ __all__ = [
1616
+ "MllamaForConditionalGeneration",
1617
+ "MllamaForCausalLM",
1618
+ "MllamaTextModel",
1619
+ "MllamaVisionModel",
1620
+ "MllamaPreTrainedModel",
1621
+ "MllamaModel",
1622
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mllama/processing_mllama.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Processor class for Mllama."""
16
+
17
+ import numpy as np
18
+
19
+ from ...feature_extraction_utils import BatchFeature
20
+ from ...image_utils import ImageInput, make_nested_list_of_images
21
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
22
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
23
+ from ...utils import auto_docstring
24
+
25
+
26
+ class MllamaProcessorKwargs(ProcessingKwargs, total=False):
27
+ _defaults = {
28
+ "image_kwargs": {
29
+ "max_image_tiles": 4,
30
+ },
31
+ }
32
+
33
+
34
+ def get_cross_attention_token_mask(input_ids: list[int], image_token_id: int) -> list[list[int]]:
35
+ """
36
+ Generate a cross-attention token mask for image tokens in the input sequence.
37
+
38
+ This function identifies the positions of image tokens in the input sequence and creates
39
+ a mask that defines which subsequent tokens each image token should attend to.
40
+
41
+ Args:
42
+ input_ids (list[int]): A list of token ids representing the input sequence.
43
+ image_token_id (int): The id of the token used to represent images in the sequence.
44
+
45
+ Returns:
46
+ list[list[int]]: A list of [start, end] pairs, where each pair represents the range
47
+ of tokens an image token should attend to.
48
+
49
+ Notes:
50
+ - If no image tokens are present, an empty list is returned.
51
+ - For a single image token, it attends to all subsequent tokens until the end of the sequence.
52
+ - For multiple image tokens, each attends to tokens up to the next image token or the end of the sequence.
53
+ - Consecutive image tokens are treated as a group and attend to all subsequent tokens together.
54
+ """
55
+
56
+ image_token_locations = [i for i, token in enumerate(input_ids) if token == image_token_id]
57
+
58
+ if len(image_token_locations) == 0:
59
+ return []
60
+
61
+ # only one image present, unmask until end of sequence
62
+ if len(image_token_locations) == 1:
63
+ return [[image_token_locations[0], -1]]
64
+
65
+ vision_masks = [[loc1, loc2] for loc1, loc2 in zip(image_token_locations[:-1], image_token_locations[1:])]
66
+
67
+ # last image will attend to all subsequent text
68
+ vision_masks.append([image_token_locations[-1], len(input_ids)])
69
+
70
+ # if there are two or more consecutive vision tokens,
71
+ # they should all attend to all subsequent
72
+ # text present
73
+ last_mask_end = vision_masks[-1][1]
74
+ for vision_mask in vision_masks[::-1]:
75
+ if vision_mask[0] == vision_mask[1] - 1:
76
+ vision_mask[1] = last_mask_end
77
+ last_mask_end = vision_mask[1]
78
+
79
+ return vision_masks
80
+
81
+
82
+ def convert_sparse_cross_attention_mask_to_dense(
83
+ cross_attention_token_mask: list[list[list[int]]],
84
+ num_tiles: list[list[int]],
85
+ max_num_tiles: int,
86
+ length: int,
87
+ ) -> np.ndarray:
88
+ """
89
+ Convert the cross attention mask indices to a cross attention mask 4D array.
90
+
91
+ This function takes a sparse representation of cross attention masks and converts it to a dense 4D numpy array.
92
+ The sparse representation is a nested list structure that defines attention ranges for each image in each batch item.
93
+
94
+ Args:
95
+ cross_attention_token_mask (list[list[list[int]]]): A nested list structure where:
96
+ - The outer list represents the batch dimension.
97
+ - The middle list represents different images within each batch item.
98
+ - The inner list contains pairs of integers [start, end] representing token ranges for each image.
99
+ num_tiles (list[list[int]]): A nested list structure specifying the number of tiles for each image in each batch item.
100
+ max_num_tiles (int): The maximum possible number of tiles.
101
+ length (int): The total sequence length of the input.
102
+
103
+ Returns:
104
+ np.ndarray: A 4D numpy array of shape (batch_size, length, max_num_images, max_num_tiles)
105
+ The array contains `1` where attention is allowed and `0` where it is not.
106
+
107
+ Note:
108
+ - Special handling is done for cases where the end token is -1, which is interpreted as attending to the end of the sequence.
109
+ """
110
+
111
+ batch_size = len(cross_attention_token_mask)
112
+ max_num_images = max(len(masks) for masks in cross_attention_token_mask)
113
+
114
+ cross_attention_mask = np.zeros(
115
+ shape=(batch_size, length, max_num_images, max_num_tiles),
116
+ dtype=np.int64,
117
+ )
118
+
119
+ for sample_idx, (sample_masks, sample_num_tiles) in enumerate(zip(cross_attention_token_mask, num_tiles)):
120
+ for mask_idx, (locations, mask_num_tiles) in enumerate(zip(sample_masks, sample_num_tiles)):
121
+ if len(locations) == 2:
122
+ start, end = locations
123
+ end = min(end, length)
124
+ if end == -1:
125
+ end = length
126
+ cross_attention_mask[sample_idx, start:end, mask_idx, :mask_num_tiles] = 1
127
+ return cross_attention_mask
128
+
129
+
130
+ def build_string_from_input(prompt: str, bos_token: str, image_token: str) -> str:
131
+ """
132
+ Builds a string from the input prompt by adding `bos_token` if not already present.
133
+
134
+ Args:
135
+ prompt (`str`):
136
+ The input prompt string.
137
+ bos_token (`str`):
138
+ The beginning of sentence token to be added.
139
+ image_token (`str`):
140
+ The image token used to identify the start of an image sequence.
141
+
142
+ Returns:
143
+ str: The modified prompt string with the `bos_token` added if necessary.
144
+
145
+ Examples:
146
+ >>> build_string_from_input("Hello world", "<begin_of_text>", "<|image|>")
147
+ '<begin_of_text>Hello world'
148
+
149
+ >>> build_string_from_input("<|image|>Hello world", "<begin_of_text>", "<|image|>")
150
+ '<|image|><begin_of_text>Hello world'
151
+
152
+ >>> build_string_from_input("<begin_of_text>Hello world", "<begin_of_text>", "<|image|>")
153
+ '<begin_of_text>Hello world'
154
+ """
155
+
156
+ if bos_token in prompt:
157
+ return prompt
158
+
159
+ num_image_tokens_on_start = 0
160
+ while prompt.startswith(image_token):
161
+ prompt = prompt[len(image_token) :]
162
+ num_image_tokens_on_start += 1
163
+
164
+ return f"{image_token * num_image_tokens_on_start}{bos_token}{prompt}"
165
+
166
+
167
+ @auto_docstring
168
+ class MllamaProcessor(ProcessorMixin):
169
+ def __init__(self, image_processor, tokenizer, chat_template=None):
170
+ if not hasattr(tokenizer, "image_token"):
171
+ self.image_token = "<|image|>"
172
+ self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
173
+ else:
174
+ self.image_token = tokenizer.image_token
175
+ self.image_token_id = tokenizer.image_token_id
176
+
177
+ self.python_token = "<|python_tag|>"
178
+ self.python_token_id = tokenizer.convert_tokens_to_ids(self.python_token)
179
+ self.bos_token = tokenizer.bos_token
180
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
181
+
182
+ @auto_docstring
183
+ def __call__(
184
+ self,
185
+ images: ImageInput | None = None,
186
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
187
+ **kwargs: Unpack[MllamaProcessorKwargs],
188
+ ) -> BatchFeature:
189
+ r"""
190
+ Returns:
191
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
192
+
193
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
194
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
195
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
196
+ `None`).
197
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
198
+ TODO: add aspect_ratio_ids and aspect_ratio_mask and cross_attention_mask
199
+ """
200
+ if text is None and images is None:
201
+ raise ValueError("You must specify either text or images.")
202
+
203
+ output_kwargs = self._merge_kwargs(
204
+ MllamaProcessorKwargs,
205
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
206
+ **kwargs,
207
+ )
208
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
209
+
210
+ data = {}
211
+ if text is not None:
212
+ if isinstance(text, str):
213
+ text = [text]
214
+ elif not (isinstance(text, (list, tuple)) and all(isinstance(t, str) for t in text)):
215
+ raise ValueError("Invalid input text. Please provide a string, or a list of strings")
216
+ n_images_in_text = [t.count(self.image_token) for t in text]
217
+ text = [build_string_from_input(text_item, self.bos_token, self.image_token) for text_item in text]
218
+ encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
219
+ self._check_special_mm_tokens(text, encoding, modalities=["image"])
220
+ n_images_in_ids = [token_ids.count(self.image_token_id) for token_ids in encoding["input_ids"]]
221
+ data.update(encoding)
222
+
223
+ n_images_in_images = [0]
224
+ if images is not None:
225
+ images = self.image_processor.fetch_images(images)
226
+ images = make_nested_list_of_images(images)
227
+ n_images_in_images = [len(sample) for sample in images]
228
+
229
+ if text is not None:
230
+ if any(batch_img == 0 for batch_img in n_images_in_text) and not all(
231
+ batch_img == 0 for batch_img in n_images_in_text
232
+ ):
233
+ raise ValueError(
234
+ "If a batch of text is provided, there should be either no images or at least one image per sample"
235
+ )
236
+ if sum(n_images_in_text) > 0 and (
237
+ n_images_in_images != n_images_in_text or n_images_in_ids != n_images_in_images
238
+ ):
239
+ if images is None:
240
+ raise ValueError("No image were provided, but there are image tokens in the prompt")
241
+ else:
242
+ add_message = ""
243
+ if sum(n_images_in_images) == sum(n_images_in_text) and n_images_in_images != n_images_in_text:
244
+ add_message = "Make sure to pass your images as a nested list, where each sub-list holds images per batch"
245
+ elif n_images_in_ids != n_images_in_images:
246
+ add_message = "If you activated truncation with `max_length`, increase the `max_length` so image tokens aren't cropped."
247
+
248
+ raise ValueError(
249
+ f"The number of image tokens in each text ({n_images_in_text}) should be the same as the "
250
+ f"number of provided images per batch ({n_images_in_images}). {add_message}"
251
+ )
252
+
253
+ if images is not None:
254
+ image_features = self.image_processor(images, **output_kwargs["images_kwargs"])
255
+ num_tiles = image_features.pop("num_tiles")
256
+ data.update(image_features)
257
+
258
+ # Create cross attention mask
259
+ if images is not None and text is not None:
260
+ cross_attention_token_mask = [
261
+ get_cross_attention_token_mask(token_ids, self.image_token_id) for token_ids in encoding["input_ids"]
262
+ ]
263
+ cross_attention_mask = convert_sparse_cross_attention_mask_to_dense(
264
+ cross_attention_token_mask,
265
+ num_tiles=num_tiles,
266
+ max_num_tiles=self.image_processor.max_image_tiles,
267
+ length=max(len(input_ids) for input_ids in encoding["input_ids"]),
268
+ )
269
+ data["cross_attention_mask"] = cross_attention_mask
270
+
271
+ return BatchFeature(data=data, tensor_type=return_tensors)
272
+
273
+ def post_process_image_text_to_text(
274
+ self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs
275
+ ):
276
+ """
277
+ Post-process the output of the model to decode the text.
278
+
279
+ Args:
280
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
281
+ The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
282
+ or `(sequence_length,)`.
283
+ skip_special_tokens (`bool`, *optional*, defaults to `True`):
284
+ Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
285
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
286
+ Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method.
287
+ **kwargs:
288
+ Additional arguments to be passed to the tokenizer's `batch_decode method`.
289
+
290
+ Returns:
291
+ `list[str]`: The decoded text.
292
+ """
293
+ return self.tokenizer.batch_decode(
294
+ generated_outputs,
295
+ skip_special_tokens=skip_special_tokens,
296
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
297
+ **kwargs,
298
+ )
299
+
300
+ @property
301
+ def model_input_names(self):
302
+ tokenizer_input_names = self.tokenizer.model_input_names
303
+ image_processor_input_names = self.image_processor.model_input_names
304
+
305
+ # Remove `num_tiles`, it is popped and used only when processing. Make a copy of list when removing
306
+ # otherwise `self.image_processor.model_input_names` is also modified
307
+ image_processor_input_names = [name for name in image_processor_input_names if name != "num_tiles"]
308
+ return list(tokenizer_input_names + image_processor_input_names + ["cross_attention_mask"])
309
+
310
+
311
+ __all__ = ["MllamaProcessor"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/modernbert_decoder/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 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_modernbert_decoder import *
22
+ from .modeling_modernbert_decoder 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__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/owt_llmclean_qwen36_35b_articlefull_full_rev8_3gpu_resume_20260531_120957.outer.log ADDED
The diff for this file is too large to render. See raw diff
 
LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/owt_t5_cleanstream_len1024_C1_to_64_d768_l12_h12_gbs512_8gpu_1m_lr3e4_20260527_132002.log ADDED
The diff for this file is too large to render. See raw diff
 
LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_norm_stateprobadd_selfcond_ce_fast_trainlogit_mn0p9_s0p9_20260605_053046.log ADDED
The diff for this file is too large to render. See raw diff
 
LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/owt_t5_ultraclean10k_len1024_C4096_to_32768_exp_d768_l12_h12_gbs512_8gpu_40k_lr3e4_20260527_212316.log ADDED
@@ -0,0 +1,689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ W0527 21:23:17.825000 10232 torch/distributed/run.py:792]
2
+ W0527 21:23:17.825000 10232 torch/distributed/run.py:792] *****************************************
3
+ W0527 21:23:17.825000 10232 torch/distributed/run.py:792] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed.
4
+ W0527 21:23:17.825000 10232 torch/distributed/run.py:792] *****************************************
5
+ t-20260528052235-lvfnr-worker-0:10299:10299 [0] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
6
+ t-20260528052235-lvfnr-worker-0:10299:10299 [0] NCCL INFO Bootstrap: Using eth1:10.82.64.8<0>
7
+ t-20260528052235-lvfnr-worker-0:10299:10299 [0] NCCL INFO cudaDriverVersion 12080
8
+ t-20260528052235-lvfnr-worker-0:10299:10299 [0] NCCL INFO NCCL version 2.25.1+cuda12.8
9
+ t-20260528052235-lvfnr-worker-0:10299:10299 [0] NCCL INFO Comm config Blocking set to 1
10
+ t-20260528052235-lvfnr-worker-0:10306:10306 [7] NCCL INFO cudaDriverVersion 12080
11
+ t-20260528052235-lvfnr-worker-0:10306:10306 [7] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
12
+ t-20260528052235-lvfnr-worker-0:10306:10306 [7] NCCL INFO Bootstrap: Using eth1:10.82.64.8<0>
13
+ t-20260528052235-lvfnr-worker-0:10306:10306 [7] NCCL INFO NCCL version 2.25.1+cuda12.8
14
+ t-20260528052235-lvfnr-worker-0:10302:10302 [3] NCCL INFO cudaDriverVersion 12080
15
+ t-20260528052235-lvfnr-worker-0:10302:10302 [3] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
16
+ t-20260528052235-lvfnr-worker-0:10306:10306 [7] NCCL INFO Comm config Blocking set to 1
17
+ t-20260528052235-lvfnr-worker-0:10302:10302 [3] NCCL INFO Bootstrap: Using eth1:10.82.64.8<0>
18
+ t-20260528052235-lvfnr-worker-0:10302:10302 [3] NCCL INFO NCCL version 2.25.1+cuda12.8
19
+ t-20260528052235-lvfnr-worker-0:10302:10302 [3] NCCL INFO Comm config Blocking set to 1
20
+ t-20260528052235-lvfnr-worker-0:10305:10305 [6] NCCL INFO cudaDriverVersion 12080
21
+ t-20260528052235-lvfnr-worker-0:10305:10305 [6] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
22
+ t-20260528052235-lvfnr-worker-0:10305:10305 [6] NCCL INFO Bootstrap: Using eth1:10.82.64.8<0>
23
+ t-20260528052235-lvfnr-worker-0:10305:10305 [6] NCCL INFO NCCL version 2.25.1+cuda12.8
24
+ t-20260528052235-lvfnr-worker-0:10305:10305 [6] NCCL INFO Comm config Blocking set to 1
25
+ t-20260528052235-lvfnr-worker-0:10300:10300 [1] NCCL INFO cudaDriverVersion 12080
26
+ t-20260528052235-lvfnr-worker-0:10300:10300 [1] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
27
+ t-20260528052235-lvfnr-worker-0:10300:10300 [1] NCCL INFO Bootstrap: Using eth1:10.82.64.8<0>
28
+ t-20260528052235-lvfnr-worker-0:10300:10300 [1] NCCL INFO NCCL version 2.25.1+cuda12.8
29
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO NET/Plugin: Loaded net plugin NCCL RDMA Plugin v9 (v9)
30
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO NET/Plugin: Loaded collnet plugin SHARP (v9)
31
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Plugin Path : /opt/hpcx/nccl_rdma_sharp_plugin/lib/libnccl-net.so
32
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO P2P plugin v9 IBext_v9
33
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
34
+ t-20260528052235-lvfnr-worker-0:10300:10300 [1] NCCL INFO Comm config Blocking set to 1
35
+ t-20260528052235-lvfnr-worker-0:10303:10303 [4] NCCL INFO cudaDriverVersion 12080
36
+ t-20260528052235-lvfnr-worker-0:10303:10303 [4] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
37
+ t-20260528052235-lvfnr-worker-0:10303:10303 [4] NCCL INFO Bootstrap: Using eth1:10.82.64.8<0>
38
+ t-20260528052235-lvfnr-worker-0:10303:10303 [4] NCCL INFO NCCL version 2.25.1+cuda12.8
39
+ t-20260528052235-lvfnr-worker-0:10303:10303 [4] NCCL INFO Comm config Blocking set to 1
40
+ t-20260528052235-lvfnr-worker-0:10304:10304 [5] NCCL INFO cudaDriverVersion 12080
41
+ t-20260528052235-lvfnr-worker-0:10304:10304 [5] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
42
+ t-20260528052235-lvfnr-worker-0:10301:10301 [2] NCCL INFO cudaDriverVersion 12080
43
+ t-20260528052235-lvfnr-worker-0:10301:10301 [2] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
44
+ t-20260528052235-lvfnr-worker-0:10304:10304 [5] NCCL INFO Bootstrap: Using eth1:10.82.64.8<0>
45
+ t-20260528052235-lvfnr-worker-0:10301:10301 [2] NCCL INFO Bootstrap: Using eth1:10.82.64.8<0>
46
+ t-20260528052235-lvfnr-worker-0:10304:10304 [5] NCCL INFO NCCL version 2.25.1+cuda12.8
47
+ t-20260528052235-lvfnr-worker-0:10301:10301 [2] NCCL INFO NCCL version 2.25.1+cuda12.8
48
+ t-20260528052235-lvfnr-worker-0:10304:10304 [5] NCCL INFO Comm config Blocking set to 1
49
+ t-20260528052235-lvfnr-worker-0:10301:10301 [2] NCCL INFO Comm config Blocking set to 1
50
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO NCCL_IB_PCI_RELAXED_ORDERING set by environment to 1.
51
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO NET/IB : Using [0]mlx5_1:1/RoCE [1]mlx5_4:1/RoCE [2]mlx5_5:1/RoCE [3]mlx5_6:1/RoCE [4]mlx5_7:1/RoCE [5]mlx5_8:1/RoCE [6]mlx5_9:1/RoCE [7]mlx5_10:1/RoCE [RO]; OOB eth1:10.82.64.8<0>
52
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO PROFILER/Plugin: Could not find: libnccl-profiler.so.
53
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Using network IBext_v9
54
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO NET/Plugin: Loaded net plugin NCCL RDMA Plugin v9 (v9)
55
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO NET/Plugin: Loaded collnet plugin SHARP (v9)
56
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO Plugin Path : /opt/hpcx/nccl_rdma_sharp_plugin/lib/libnccl-net.so
57
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO P2P plugin v9 IBext_v9
58
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
59
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO NET/Plugin: Loaded net plugin NCCL RDMA Plugin v9 (v9)
60
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO NET/Plugin: Loaded collnet plugin SHARP (v9)
61
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO Plugin Path : /opt/hpcx/nccl_rdma_sharp_plugin/lib/libnccl-net.so
62
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO P2P plugin v9 IBext_v9
63
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
64
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO NET/Plugin: Loaded net plugin NCCL RDMA Plugin v9 (v9)
65
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO NET/Plugin: Loaded collnet plugin SHARP (v9)
66
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO Plugin Path : /opt/hpcx/nccl_rdma_sharp_plugin/lib/libnccl-net.so
67
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO P2P plugin v9 IBext_v9
68
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
69
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO NCCL_IB_PCI_RELAXED_ORDERING set by environment to 1.
70
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO NET/IB : Using [0]mlx5_1:1/RoCE [1]mlx5_4:1/RoCE [2]mlx5_5:1/RoCE [3]mlx5_6:1/RoCE [4]mlx5_7:1/RoCE [5]mlx5_8:1/RoCE [6]mlx5_9:1/RoCE [7]mlx5_10:1/RoCE [RO]; OOB eth1:10.82.64.8<0>
71
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO PROFILER/Plugin: Could not find: libnccl-profiler.so.
72
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO Using network IBext_v9
73
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO NCCL_IB_PCI_RELAXED_ORDERING set by environment to 1.
74
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO NET/IB : Using [0]mlx5_1:1/RoCE [1]mlx5_4:1/RoCE [2]mlx5_5:1/RoCE [3]mlx5_6:1/RoCE [4]mlx5_7:1/RoCE [5]mlx5_8:1/RoCE [6]mlx5_9:1/RoCE [7]mlx5_10:1/RoCE [RO]; OOB eth1:10.82.64.8<0>
75
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO PROFILER/Plugin: Could not find: libnccl-profiler.so.
76
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO Using network IBext_v9
77
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO NCCL_IB_PCI_RELAXED_ORDERING set by environment to 1.
78
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO NET/IB : Using [0]mlx5_1:1/RoCE [1]mlx5_4:1/RoCE [2]mlx5_5:1/RoCE [3]mlx5_6:1/RoCE [4]mlx5_7:1/RoCE [5]mlx5_8:1/RoCE [6]mlx5_9:1/RoCE [7]mlx5_10:1/RoCE [RO]; OOB eth1:10.82.64.8<0>
79
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO PROFILER/Plugin: Could not find: libnccl-profiler.so.
80
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO Using network IBext_v9
81
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO ncclCommInitRankConfig comm 0x95c7e40 rank 0 nranks 8 cudaDev 0 nvmlDev 0 busId 65040 commId 0x1a57b0265de3f8e1 - Init START
82
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO NET/Plugin: Loaded net plugin NCCL RDMA Plugin v9 (v9)
83
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO NET/Plugin: Loaded collnet plugin SHARP (v9)
84
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO Plugin Path : /opt/hpcx/nccl_rdma_sharp_plugin/lib/libnccl-net.so
85
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO P2P plugin v9 IBext_v9
86
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
87
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO NET/Plugin: Loaded net plugin NCCL RDMA Plugin v9 (v9)
88
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO NET/Plugin: Loaded collnet plugin SHARP (v9)
89
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO Plugin Path : /opt/hpcx/nccl_rdma_sharp_plugin/lib/libnccl-net.so
90
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO P2P plugin v9 IBext_v9
91
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
92
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO NET/Plugin: Loaded net plugin NCCL RDMA Plugin v9 (v9)
93
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO NET/Plugin: Loaded collnet plugin SHARP (v9)
94
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO Plugin Path : /opt/hpcx/nccl_rdma_sharp_plugin/lib/libnccl-net.so
95
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO P2P plugin v9 IBext_v9
96
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
97
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO NET/Plugin: Loaded net plugin NCCL RDMA Plugin v9 (v9)
98
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO NET/Plugin: Loaded collnet plugin SHARP (v9)
99
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO Plugin Path : /opt/hpcx/nccl_rdma_sharp_plugin/lib/libnccl-net.so
100
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO P2P plugin v9 IBext_v9
101
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO NCCL_SOCKET_IFNAME set by environment to eth1
102
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO ncclCommInitRankConfig comm 0xa010c30 rank 7 nranks 8 cudaDev 7 nvmlDev 7 busId 75020 commId 0x1a57b0265de3f8e1 - Init START
103
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO ncclCommInitRankConfig comm 0x8d69240 rank 3 nranks 8 cudaDev 3 nvmlDev 3 busId 6b020 commId 0x1a57b0265de3f8e1 - Init START
104
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO ncclCommInitRankConfig comm 0x919e3e0 rank 6 nranks 8 cudaDev 6 nvmlDev 6 busId 73020 commId 0x1a57b0265de3f8e1 - Init START
105
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO RAS client listening socket at ::1<28028>
106
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO NCCL_IB_PCI_RELAXED_ORDERING set by environment to 1.
107
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO NET/IB : Using [0]mlx5_1:1/RoCE [1]mlx5_4:1/RoCE [2]mlx5_5:1/RoCE [3]mlx5_6:1/RoCE [4]mlx5_7:1/RoCE [5]mlx5_8:1/RoCE [6]mlx5_9:1/RoCE [7]mlx5_10:1/RoCE [RO]; OOB eth1:10.82.64.8<0>
108
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO NCCL_IB_PCI_RELAXED_ORDERING set by environment to 1.
109
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO NET/IB : Using [0]mlx5_1:1/RoCE [1]mlx5_4:1/RoCE [2]mlx5_5:1/RoCE [3]mlx5_6:1/RoCE [4]mlx5_7:1/RoCE [5]mlx5_8:1/RoCE [6]mlx5_9:1/RoCE [7]mlx5_10:1/RoCE [RO]; OOB eth1:10.82.64.8<0>
110
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO NCCL_IB_PCI_RELAXED_ORDERING set by environment to 1.
111
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO NET/IB : Using [0]mlx5_1:1/RoCE [1]mlx5_4:1/RoCE [2]mlx5_5:1/RoCE [3]mlx5_6:1/RoCE [4]mlx5_7:1/RoCE [5]mlx5_8:1/RoCE [6]mlx5_9:1/RoCE [7]mlx5_10:1/RoCE [RO]; OOB eth1:10.82.64.8<0>
112
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO NCCL_IB_PCI_RELAXED_ORDERING set by environment to 1.
113
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO NET/IB : Using [0]mlx5_1:1/RoCE [1]mlx5_4:1/RoCE [2]mlx5_5:1/RoCE [3]mlx5_6:1/RoCE [4]mlx5_7:1/RoCE [5]mlx5_8:1/RoCE [6]mlx5_9:1/RoCE [7]mlx5_10:1/RoCE [RO]; OOB eth1:10.82.64.8<0>
114
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO PROFILER/Plugin: Could not find: libnccl-profiler.so.
115
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO Using network IBext_v9
116
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO PROFILER/Plugin: Could not find: libnccl-profiler.so.
117
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO Using network IBext_v9
118
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO PROFILER/Plugin: Could not find: libnccl-profiler.so.
119
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO Using network IBext_v9
120
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO PROFILER/Plugin: Could not find: libnccl-profiler.so.
121
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO Using network IBext_v9
122
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO ncclCommInitRankConfig comm 0xcebc1b0 rank 1 nranks 8 cudaDev 1 nvmlDev 1 busId 67020 commId 0x1a57b0265de3f8e1 - Init START
123
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO ncclCommInitRankConfig comm 0xce66c40 rank 5 nranks 8 cudaDev 5 nvmlDev 5 busId 71020 commId 0x1a57b0265de3f8e1 - Init START
124
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO RAS client listening socket at ::1<28028>
125
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO RAS client listening socket at ::1<28028>
126
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO ncclCommInitRankConfig comm 0xcec7380 rank 2 nranks 8 cudaDev 2 nvmlDev 2 busId 69020 commId 0x1a57b0265de3f8e1 - Init START
127
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO RAS client listening socket at ::1<28028>
128
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO RAS client listening socket at ::1<28028>
129
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO ncclCommInitRankConfig comm 0xc7a6880 rank 4 nranks 8 cudaDev 4 nvmlDev 4 busId 6f020 commId 0x1a57b0265de3f8e1 - Init START
130
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO RAS client listening socket at ::1<28028>
131
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO RAS client listening socket at ::1<28028>
132
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO RAS client listening socket at ::1<28028>
133
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO Bootstrap timings total 0.001228 (create 0.000020, send 0.000066, recv 0.000082, ring 0.000786, delay 0.000001)
134
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO Bootstrap timings total 0.617195 (create 0.000025, send 0.000072, recv 0.616667, ring 0.000100, delay 0.000001)
135
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO Bootstrap timings total 0.002286 (create 0.000024, send 0.000068, recv 0.001100, ring 0.000791, delay 0.000001)
136
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO Bootstrap timings total 0.000677 (create 0.000022, send 0.000070, recv 0.000166, ring 0.000115, delay 0.000001)
137
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Bootstrap timings total 0.900655 (create 0.000023, send 0.000079, recv 0.898502, ring 0.001665, delay 0.000001)
138
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO Bootstrap timings total 0.001774 (create 0.000021, send 0.000065, recv 0.000052, ring 0.000117, delay 0.000001)
139
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO Bootstrap timings total 0.604435 (create 0.000021, send 0.000065, recv 0.000060, ring 0.001248, delay 0.000001)
140
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO Bootstrap timings total 0.628573 (create 0.000023, send 0.000066, recv 0.000105, ring 0.554812, delay 0.000000)
141
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO MNNVL busId 0x69020 fabric UUID 0.0 cliqueId 0x0 state 3 healthMask 0x0
142
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO MNNVL busId 0x67020 fabric UUID 0.0 cliqueId 0x0 state 3 healthMask 0x0
143
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO MNNVL busId 0x6b020 fabric UUID 0.0 cliqueId 0x0 state 3 healthMask 0x0
144
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO MNNVL busId 0x71020 fabric UUID 0.0 cliqueId 0x0 state 3 healthMask 0x0
145
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO MNNVL busId 0x6f020 fabric UUID 0.0 cliqueId 0x0 state 3 healthMask 0x0
146
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO MNNVL busId 0x65040 fabric UUID 0.0 cliqueId 0x0 state 3 healthMask 0x0
147
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO MNNVL busId 0x73020 fabric UUID 0.0 cliqueId 0x0 state 3 healthMask 0x0
148
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO MNNVL busId 0x75020 fabric UUID 0.0 cliqueId 0x0 state 3 healthMask 0x0
149
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO NCCL_TOPO_FILE set by environment to /var/run/nvidia-topologyd/virtualTopology.xml
150
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO NCCL_TOPO_FILE set by environment to /var/run/nvidia-topologyd/virtualTopology.xml
151
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO NCCL_TOPO_FILE set by environment to /var/run/nvidia-topologyd/virtualTopology.xml
152
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO NCCL_TOPO_FILE set by environment to /var/run/nvidia-topologyd/virtualTopology.xml
153
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO NCCL_TOPO_FILE set by environment to /var/run/nvidia-topologyd/virtualTopology.xml
154
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO NCCL_TOPO_FILE set by environment to /var/run/nvidia-topologyd/virtualTopology.xml
155
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO NCCL_TOPO_FILE set by environment to /var/run/nvidia-topologyd/virtualTopology.xml
156
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO NCCL_TOPO_FILE set by environment to /var/run/nvidia-topologyd/virtualTopology.xml
157
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO Setting affinity for GPU 2 to 03ffffff,ffffffff,ffffffff
158
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO NVLS multicast support is available on dev 2
159
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO Setting affinity for GPU 5 to 0fffff,ffffffff,ffffffff,fc000000,00000000,00000000
160
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO Setting affinity for GPU 1 to 03ffffff,ffffffff,ffffffff
161
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO Setting affinity for GPU 3 to 03ffffff,ffffffff,ffffffff
162
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO NVLS multicast support is available on dev 1
163
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO NVLS multicast support is available on dev 3
164
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO NVLS multicast support is available on dev 5
165
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Setting affinity for GPU 0 to 03ffffff,ffffffff,ffffffff
166
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO Setting affinity for GPU 4 to 0fffff,ffffffff,ffffffff,fc000000,00000000,00000000
167
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO Setting affinity for GPU 7 to 0fffff,ffffffff,ffffffff,fc000000,00000000,00000000
168
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO Setting affinity for GPU 6 to 0fffff,ffffffff,ffffffff,fc000000,00000000,00000000
169
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO NVLS multicast support is available on dev 4
170
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO NVLS multicast support is available on dev 7
171
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO NVLS multicast support is available on dev 6
172
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO NVLS multicast support is available on dev 0
173
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO comm 0xa010c30 rank 7 nRanks 8 nNodes 1 localRanks 8 localRank 7 MNNVL 0
174
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO comm 0x919e3e0 rank 6 nRanks 8 nNodes 1 localRanks 8 localRank 6 MNNVL 0
175
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO comm 0xcebc1b0 rank 1 nRanks 8 nNodes 1 localRanks 8 localRank 1 MNNVL 0
176
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO comm 0xce66c40 rank 5 nRanks 8 nNodes 1 localRanks 8 localRank 5 MNNVL 0
177
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO comm 0xcec7380 rank 2 nRanks 8 nNodes 1 localRanks 8 localRank 2 MNNVL 0
178
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO comm 0xc7a6880 rank 4 nRanks 8 nNodes 1 localRanks 8 localRank 4 MNNVL 0
179
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO comm 0x95c7e40 rank 0 nRanks 8 nNodes 1 localRanks 8 localRank 0 MNNVL 0
180
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO comm 0x8d69240 rank 3 nRanks 8 nNodes 1 localRanks 8 localRank 3 MNNVL 0
181
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 00/24 : 0 1 2 3 4 5 6 7
182
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 01/24 : 0 1 2 3 4 5 6 7
183
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO Trees [0] 5/-1/-1->4->3 [1] 5/-1/-1->4->3 [2] 5/-1/-1->4->3 [3] 5/-1/-1->4->3 [4] 5/-1/-1->4->3 [5] 5/-1/-1->4->3 [6] 5/-1/-1->4->3 [7] 5/-1/-1->4->3 [8] 5/-1/-1->4->3 [9] 5/-1/-1->4->3 [10] 5/-1/-1->4->3 [11] 5/-1/-1->4->3 [12] 5/-1/-1->4->3 [13] 5/-1/-1->4->3 [14] 5/-1/-1->4->3 [15] 5/-1/-1->4->3 [16] 5/-1/-1->4->3 [17] 5/-1/-1->4->3 [18] 5/-1/-1->4->3 [19] 5/-1/-1->4->3 [20] 5/-1/-1->4->3 [21] 5/-1/-1->4->3 [22] 5/-1/-1->4->3 [23] 5/-1/-1->4->3
184
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO Trees [0] -1/-1/-1->7->6 [1] -1/-1/-1->7->6 [2] -1/-1/-1->7->6 [3] -1/-1/-1->7->6 [4] -1/-1/-1->7->6 [5] -1/-1/-1->7->6 [6] -1/-1/-1->7->6 [7] -1/-1/-1->7->6 [8] -1/-1/-1->7->6 [9] -1/-1/-1->7->6 [10] -1/-1/-1->7->6 [11] -1/-1/-1->7->6 [12] -1/-1/-1->7->6 [13] -1/-1/-1->7->6 [14] -1/-1/-1->7->6 [15] -1/-1/-1->7->6 [16] -1/-1/-1->7->6 [17] -1/-1/-1->7->6 [18] -1/-1/-1->7->6 [19] -1/-1/-1->7->6 [20] -1/-1/-1->7->6 [21] -1/-1/-1->7->6 [22] -1/-1/-1->7->6 [23] -1/-1/-1->7->6
185
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO Trees [0] 4/-1/-1->3->2 [1] 4/-1/-1->3->2 [2] 4/-1/-1->3->2 [3] 4/-1/-1->3->2 [4] 4/-1/-1->3->2 [5] 4/-1/-1->3->2 [6] 4/-1/-1->3->2 [7] 4/-1/-1->3->2 [8] 4/-1/-1->3->2 [9] 4/-1/-1->3->2 [10] 4/-1/-1->3->2 [11] 4/-1/-1->3->2 [12] 4/-1/-1->3->2 [13] 4/-1/-1->3->2 [14] 4/-1/-1->3->2 [15] 4/-1/-1->3->2 [16] 4/-1/-1->3->2 [17] 4/-1/-1->3->2 [18] 4/-1/-1->3->2 [19] 4/-1/-1->3->2 [20] 4/-1/-1->3->2 [21] 4/-1/-1->3->2 [22] 4/-1/-1->3->2 [23] 4/-1/-1->3->2
186
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO Trees [0] 2/-1/-1->1->0 [1] 2/-1/-1->1->0 [2] 2/-1/-1->1->0 [3] 2/-1/-1->1->0 [4] 2/-1/-1->1->0 [5] 2/-1/-1->1->0 [6] 2/-1/-1->1->0 [7] 2/-1/-1->1->0 [8] 2/-1/-1->1->0 [9] 2/-1/-1->1->0 [10] 2/-1/-1->1->0 [11] 2/-1/-1->1->0 [12] 2/-1/-1->1->0 [13] 2/-1/-1->1->0 [14] 2/-1/-1->1->0 [15] 2/-1/-1->1->0 [16] 2/-1/-1->1->0 [17] 2/-1/-1->1->0 [18] 2/-1/-1->1->0 [19] 2/-1/-1->1->0 [20] 2/-1/-1->1->0 [21] 2/-1/-1->1->0 [22] 2/-1/-1->1->0 [23] 2/-1/-1->1->0
187
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO Trees [0] 7/-1/-1->6->5 [1] 7/-1/-1->6->5 [2] 7/-1/-1->6->5 [3] 7/-1/-1->6->5 [4] 7/-1/-1->6->5 [5] 7/-1/-1->6->5 [6] 7/-1/-1->6->5 [7] 7/-1/-1->6->5 [8] 7/-1/-1->6->5 [9] 7/-1/-1->6->5 [10] 7/-1/-1->6->5 [11] 7/-1/-1->6->5 [12] 7/-1/-1->6->5 [13] 7/-1/-1->6->5 [14] 7/-1/-1->6->5 [15] 7/-1/-1->6->5 [16] 7/-1/-1->6->5 [17] 7/-1/-1->6->5 [18] 7/-1/-1->6->5 [19] 7/-1/-1->6->5 [20] 7/-1/-1->6->5 [21] 7/-1/-1->6->5 [22] 7/-1/-1->6->5 [23] 7/-1/-1->6->5
188
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 02/24 : 0 1 2 3 4 5 6 7
189
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO P2P Chunksize set to 524288
190
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO P2P Chunksize set to 524288
191
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO P2P Chunksize set to 524288
192
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO Trees [0] 6/-1/-1->5->4 [1] 6/-1/-1->5->4 [2] 6/-1/-1->5->4 [3] 6/-1/-1->5->4 [4] 6/-1/-1->5->4 [5] 6/-1/-1->5->4 [6] 6/-1/-1->5->4 [7] 6/-1/-1->5->4 [8] 6/-1/-1->5->4 [9] 6/-1/-1->5->4 [10] 6/-1/-1->5->4 [11] 6/-1/-1->5->4 [12] 6/-1/-1->5->4 [13] 6/-1/-1->5->4 [14] 6/-1/-1->5->4 [15] 6/-1/-1->5->4 [16] 6/-1/-1->5->4 [17] 6/-1/-1->5->4 [18] 6/-1/-1->5->4 [19] 6/-1/-1->5->4 [20] 6/-1/-1->5->4 [21] 6/-1/-1->5->4 [22] 6/-1/-1->5->4 [23] 6/-1/-1->5->4
193
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO P2P Chunksize set to 524288
194
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 03/24 : 0 1 2 3 4 5 6 7
195
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO P2P Chunksize set to 524288
196
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO Trees [0] 3/-1/-1->2->1 [1] 3/-1/-1->2->1 [2] 3/-1/-1->2->1 [3] 3/-1/-1->2->1 [4] 3/-1/-1->2->1 [5] 3/-1/-1->2->1 [6] 3/-1/-1->2->1 [7] 3/-1/-1->2->1 [8] 3/-1/-1->2->1 [9] 3/-1/-1->2->1 [10] 3/-1/-1->2->1 [11] 3/-1/-1->2->1 [12] 3/-1/-1->2->1 [13] 3/-1/-1->2->1 [14] 3/-1/-1->2->1 [15] 3/-1/-1->2->1 [16] 3/-1/-1->2->1 [17] 3/-1/-1->2->1 [18] 3/-1/-1->2->1 [19] 3/-1/-1->2->1 [20] 3/-1/-1->2->1 [21] 3/-1/-1->2->1 [22] 3/-1/-1->2->1 [23] 3/-1/-1->2->1
197
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO P2P Chunksize set to 524288
198
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 04/24 : 0 1 2 3 4 5 6 7
199
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO P2P Chunksize set to 524288
200
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 05/24 : 0 1 2 3 4 5 6 7
201
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 06/24 : 0 1 2 3 4 5 6 7
202
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 07/24 : 0 1 2 3 4 5 6 7
203
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 08/24 : 0 1 2 3 4 5 6 7
204
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 09/24 : 0 1 2 3 4 5 6 7
205
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 10/24 : 0 1 2 3 4 5 6 7
206
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 11/24 : 0 1 2 3 4 5 6 7
207
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 12/24 : 0 1 2 3 4 5 6 7
208
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 13/24 : 0 1 2 3 4 5 6 7
209
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 14/24 : 0 1 2 3 4 5 6 7
210
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 15/24 : 0 1 2 3 4 5 6 7
211
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 16/24 : 0 1 2 3 4 5 6 7
212
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 17/24 : 0 1 2 3 4 5 6 7
213
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 18/24 : 0 1 2 3 4 5 6 7
214
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 19/24 : 0 1 2 3 4 5 6 7
215
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 20/24 : 0 1 2 3 4 5 6 7
216
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 21/24 : 0 1 2 3 4 5 6 7
217
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 22/24 : 0 1 2 3 4 5 6 7
218
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Channel 23/24 : 0 1 2 3 4 5 6 7
219
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Trees [0] 1/-1/-1->0->-1 [1] 1/-1/-1->0->-1 [2] 1/-1/-1->0->-1 [3] 1/-1/-1->0->-1 [4] 1/-1/-1->0->-1 [5] 1/-1/-1->0->-1 [6] 1/-1/-1->0->-1 [7] 1/-1/-1->0->-1 [8] 1/-1/-1->0->-1 [9] 1/-1/-1->0->-1 [10] 1/-1/-1->0->-1 [11] 1/-1/-1->0->-1 [12] 1/-1/-1->0->-1 [13] 1/-1/-1->0->-1 [14] 1/-1/-1->0->-1 [15] 1/-1/-1->0->-1 [16] 1/-1/-1->0->-1 [17] 1/-1/-1->0->-1 [18] 1/-1/-1->0->-1 [19] 1/-1/-1->0->-1 [20] 1/-1/-1->0->-1 [21] 1/-1/-1->0->-1 [22] 1/-1/-1->0->-1 [23] 1/-1/-1->0->-1
220
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO P2P Chunksize set to 524288
221
+ t-20260528052235-lvfnr-worker-0:10303:10451 [4] NCCL INFO [Proxy Service] Device 4 CPU core 96
222
+ t-20260528052235-lvfnr-worker-0:10303:10452 [4] NCCL INFO [Proxy Service UDS] Device 4 CPU core 98
223
+ t-20260528052235-lvfnr-worker-0:10300:10453 [1] NCCL INFO [Proxy Service] Device 1 CPU core 60
224
+ t-20260528052235-lvfnr-worker-0:10300:10454 [1] NCCL INFO [Proxy Service UDS] Device 1 CPU core 62
225
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Check P2P Type intraNodeP2pSupport 1 directMode 0
226
+ t-20260528052235-lvfnr-worker-0:10299:10455 [0] NCCL INFO [Proxy Service] Device 0 CPU core 2
227
+ t-20260528052235-lvfnr-worker-0:10299:10456 [0] NCCL INFO [Proxy Service UDS] Device 0 CPU core 4
228
+ t-20260528052235-lvfnr-worker-0:10301:10457 [2] NCCL INFO [Proxy Service] Device 2 CPU core 70
229
+ t-20260528052235-lvfnr-worker-0:10301:10458 [2] NCCL INFO [Proxy Service UDS] Device 2 CPU core 72
230
+ t-20260528052235-lvfnr-worker-0:10306:10459 [7] NCCL INFO [Proxy Service] Device 7 CPU core 176
231
+ t-20260528052235-lvfnr-worker-0:10306:10460 [7] NCCL INFO [Proxy Service UDS] Device 7 CPU core 178
232
+ t-20260528052235-lvfnr-worker-0:10302:10461 [3] NCCL INFO [Proxy Service] Device 3 CPU core 70
233
+ t-20260528052235-lvfnr-worker-0:10302:10462 [3] NCCL INFO [Proxy Service UDS] Device 3 CPU core 72
234
+ t-20260528052235-lvfnr-worker-0:10305:10463 [6] NCCL INFO [Proxy Service] Device 6 CPU core 136
235
+ t-20260528052235-lvfnr-worker-0:10305:10464 [6] NCCL INFO [Proxy Service UDS] Device 6 CPU core 138
236
+ t-20260528052235-lvfnr-worker-0:10304:10465 [5] NCCL INFO [Proxy Service] Device 5 CPU core 92
237
+ t-20260528052235-lvfnr-worker-0:10304:10466 [5] NCCL INFO [Proxy Service UDS] Device 5 CPU core 96
238
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO threadThresholds 8/8/64 | 64/8/64 | 512 | 512
239
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO 24 coll channels, 24 collnet channels, 16 nvls channels, 32 p2p channels, 32 p2p channels per peer
240
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO threadThresholds 8/8/64 | 64/8/64 | 512 | 512
241
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO 24 coll channels, 24 collnet channels, 16 nvls channels, 32 p2p channels, 32 p2p channels per peer
242
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO threadThresholds 8/8/64 | 64/8/64 | 512 | 512
243
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO 24 coll channels, 24 collnet channels, 16 nvls channels, 32 p2p channels, 32 p2p channels per peer
244
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO CC Off, workFifoBytes 1048576
245
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO threadThresholds 8/8/64 | 64/8/64 | 512 | 512
246
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO 24 coll channels, 24 collnet channels, 16 nvls channels, 32 p2p channels, 32 p2p channels per peer
247
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO threadThresholds 8/8/64 | 64/8/64 | 512 | 512
248
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO 24 coll channels, 24 collnet channels, 16 nvls channels, 32 p2p channels, 32 p2p channels per peer
249
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO threadThresholds 8/8/64 | 64/8/64 | 512 | 512
250
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO 24 coll channels, 24 collnet channels, 16 nvls channels, 32 p2p channels, 32 p2p channels per peer
251
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO threadThresholds 8/8/64 | 64/8/64 | 512 | 512
252
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO 24 coll channels, 24 collnet channels, 16 nvls channels, 32 p2p channels, 32 p2p channels per peer
253
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO threadThresholds 8/8/64 | 64/8/64 | 512 | 512
254
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO 24 coll channels, 24 collnet channels, 16 nvls channels, 32 p2p channels, 32 p2p channels per peer
255
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v4 symbol.
256
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v4 symbol.
257
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v4 symbol.
258
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v4 symbol.
259
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v3 symbol.
260
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v4 symbol.
261
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v4 symbol.
262
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v3 symbol.
263
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v3 symbol.
264
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v4 symbol.
265
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v2 symbol, using internal tuner instead.
266
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v3 symbol.
267
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v4 symbol.
268
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v3 symbol.
269
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v3 symbol.
270
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v2 symbol, using internal tuner instead.
271
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v3 symbol.
272
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v2 symbol, using internal tuner instead.
273
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v2 symbol, using internal tuner instead.
274
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO ncclCommInitRankConfig comm 0x919e3e0 rank 6 nranks 8 cudaDev 6 nvmlDev 6 busId 73020 commId 0x1a57b0265de3f8e1 - Init COMPLETE
275
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v2 symbol, using internal tuner instead.
276
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v2 symbol, using internal tuner instead.
277
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v3 symbol.
278
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v2 symbol, using internal tuner instead.
279
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO ncclCommInitRankConfig comm 0x95c7e40 rank 0 nranks 8 cudaDev 0 nvmlDev 0 busId 65040 commId 0x1a57b0265de3f8e1 - Init COMPLETE
280
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO ncclCommInitRankConfig comm 0xa010c30 rank 7 nranks 8 cudaDev 7 nvmlDev 7 busId 75020 commId 0x1a57b0265de3f8e1 - Init COMPLETE
281
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO ncclCommInitRankConfig comm 0x8d69240 rank 3 nranks 8 cudaDev 3 nvmlDev 3 busId 6b020 commId 0x1a57b0265de3f8e1 - Init COMPLETE
282
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v2 symbol, using internal tuner instead.
283
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO ncclCommInitRankConfig comm 0xcec7380 rank 2 nranks 8 cudaDev 2 nvmlDev 2 busId 69020 commId 0x1a57b0265de3f8e1 - Init COMPLETE
284
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO ncclCommInitRankConfig comm 0xcebc1b0 rank 1 nranks 8 cudaDev 1 nvmlDev 1 busId 67020 commId 0x1a57b0265de3f8e1 - Init COMPLETE
285
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO ncclCommInitRankConfig comm 0xce66c40 rank 5 nranks 8 cudaDev 5 nvmlDev 5 busId 71020 commId 0x1a57b0265de3f8e1 - Init COMPLETE
286
+ t-20260528052235-lvfnr-worker-0:10305:10374 [6] NCCL INFO Init timings - ncclCommInitRankConfig: rank 6 nranks 8 total 2.24 (kernels 0.24, alloc 0.45, bootstrap 0.60, allgathers 0.00, topo 0.54, graphs 0.01, connections 0.36, rest 0.03)
287
+ t-20260528052235-lvfnr-worker-0:10299:10371 [0] NCCL INFO Init timings - ncclCommInitRankConfig: rank 0 nranks 8 total 2.33 (kernels 0.19, alloc 0.29, bootstrap 0.90, allgathers 0.00, topo 0.54, graphs 0.01, connections 0.38, rest 0.02)
288
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO ncclCommInitRankConfig comm 0xc7a6880 rank 4 nranks 8 cudaDev 4 nvmlDev 4 busId 6f020 commId 0x1a57b0265de3f8e1 - Init COMPLETE
289
+ t-20260528052235-lvfnr-worker-0:10302:10373 [3] NCCL INFO Init timings - ncclCommInitRankConfig: rank 3 nranks 8 total 2.26 (kernels 0.22, alloc 0.48, bootstrap 0.62, allgathers 0.00, topo 0.54, graphs 0.01, connections 0.37, rest 0.03)
290
+ t-20260528052235-lvfnr-worker-0:10306:10372 [7] NCCL INFO Init timings - ncclCommInitRankConfig: rank 7 nranks 8 total 2.26 (kernels 0.21, alloc 0.47, bootstrap 0.63, allgathers 0.00, topo 0.54, graphs 0.01, connections 0.37, rest 0.03)
291
+ t-20260528052235-lvfnr-worker-0:10301:10382 [2] NCCL INFO Init timings - ncclCommInitRankConfig: rank 2 nranks 8 total 2.10 (kernels 0.51, alloc 0.64, bootstrap 0.00, allgathers 0.00, topo 0.54, graphs 0.01, connections 0.38, rest 0.02)
292
+ t-20260528052235-lvfnr-worker-0:10300:10375 [1] NCCL INFO Init timings - ncclCommInitRankConfig: rank 1 nranks 8 total 2.13 (kernels 0.49, alloc 0.69, bootstrap 0.00, allgathers 0.00, topo 0.54, graphs 0.01, connections 0.38, rest 0.02)
293
+ t-20260528052235-lvfnr-worker-0:10304:10381 [5] NCCL INFO Init timings - ncclCommInitRankConfig: rank 5 nranks 8 total 2.10 (kernels 0.49, alloc 0.66, bootstrap 0.00, allgathers 0.00, topo 0.54, graphs 0.01, connections 0.36, rest 0.04)
294
+ t-20260528052235-lvfnr-worker-0:10303:10377 [4] NCCL INFO Init timings - ncclCommInitRankConfig: rank 4 nranks 8 total 2.12 (kernels 0.47, alloc 0.71, bootstrap 0.00, allgathers 0.00, topo 0.54, graphs 0.01, connections 0.38, rest 0.01)
295
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 00/0 : 0[0] -> 1[1] via P2P/CUMEM
296
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 01/0 : 0[0] -> 1[1] via P2P/CUMEM
297
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 02/0 : 0[0] -> 1[1] via P2P/CUMEM
298
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 03/0 : 0[0] -> 1[1] via P2P/CUMEM
299
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 04/0 : 0[0] -> 1[1] via P2P/CUMEM
300
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 05/0 : 0[0] -> 1[1] via P2P/CUMEM
301
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 06/0 : 0[0] -> 1[1] via P2P/CUMEM
302
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 07/0 : 0[0] -> 1[1] via P2P/CUMEM
303
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 08/0 : 0[0] -> 1[1] via P2P/CUMEM
304
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 09/0 : 0[0] -> 1[1] via P2P/CUMEM
305
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 00/0 : 6[6] -> 7[7] via P2P/CUMEM
306
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 00/0 : 3[3] -> 4[4] via P2P/CUMEM
307
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 10/0 : 0[0] -> 1[1] via P2P/CUMEM
308
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 00/0 : 7[7] -> 0[0] via P2P/CUMEM
309
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 01/0 : 6[6] -> 7[7] via P2P/CUMEM
310
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 01/0 : 3[3] -> 4[4] via P2P/CUMEM
311
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 02/0 : 6[6] -> 7[7] via P2P/CUMEM
312
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 02/0 : 3[3] -> 4[4] via P2P/CUMEM
313
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 03/0 : 6[6] -> 7[7] via P2P/CUMEM
314
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 03/0 : 3[3] -> 4[4] via P2P/CUMEM
315
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 04/0 : 6[6] -> 7[7] via P2P/CUMEM
316
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 04/0 : 3[3] -> 4[4] via P2P/CUMEM
317
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 05/0 : 6[6] -> 7[7] via P2P/CUMEM
318
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 05/0 : 3[3] -> 4[4] via P2P/CUMEM
319
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 00/0 : 1[1] -> 2[2] via P2P/CUMEM
320
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 06/0 : 6[6] -> 7[7] via P2P/CUMEM
321
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 06/0 : 3[3] -> 4[4] via P2P/CUMEM
322
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 07/0 : 6[6] -> 7[7] via P2P/CUMEM
323
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 11/0 : 0[0] -> 1[1] via P2P/CUMEM
324
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 08/0 : 6[6] -> 7[7] via P2P/CUMEM
325
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 07/0 : 3[3] -> 4[4] via P2P/CUMEM
326
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 01/0 : 1[1] -> 2[2] via P2P/CUMEM
327
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 09/0 : 6[6] -> 7[7] via P2P/CUMEM
328
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 08/0 : 3[3] -> 4[4] via P2P/CUMEM
329
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 02/0 : 1[1] -> 2[2] via P2P/CUMEM
330
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 10/0 : 6[6] -> 7[7] via P2P/CUMEM
331
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 01/0 : 7[7] -> 0[0] via P2P/CUMEM
332
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 11/0 : 6[6] -> 7[7] via P2P/CUMEM
333
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 02/0 : 7[7] -> 0[0] via P2P/CUMEM
334
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 12/0 : 6[6] -> 7[7] via P2P/CUMEM
335
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 03/0 : 7[7] -> 0[0] via P2P/CUMEM
336
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 13/0 : 6[6] -> 7[7] via P2P/CUMEM
337
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 04/0 : 7[7] -> 0[0] via P2P/CUMEM
338
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 14/0 : 6[6] -> 7[7] via P2P/CUMEM
339
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 05/0 : 7[7] -> 0[0] via P2P/CUMEM
340
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 15/0 : 6[6] -> 7[7] via P2P/CUMEM
341
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 12/0 : 0[0] -> 1[1] via P2P/CUMEM
342
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 09/0 : 3[3] -> 4[4] via P2P/CUMEM
343
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 13/0 : 0[0] -> 1[1] via P2P/CUMEM
344
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 10/0 : 3[3] -> 4[4] via P2P/CUMEM
345
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 00/0 : 2[2] -> 3[3] via P2P/CUMEM
346
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 14/0 : 0[0] -> 1[1] via P2P/CUMEM
347
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 00/0 : 5[5] -> 6[6] via P2P/CUMEM
348
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 11/0 : 3[3] -> 4[4] via P2P/CUMEM
349
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 01/0 : 2[2] -> 3[3] via P2P/CUMEM
350
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 15/0 : 0[0] -> 1[1] via P2P/CUMEM
351
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 00/0 : 4[4] -> 5[5] via P2P/CUMEM
352
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 03/0 : 1[1] -> 2[2] via P2P/CUMEM
353
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 01/0 : 5[5] -> 6[6] via P2P/CUMEM
354
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 12/0 : 3[3] -> 4[4] via P2P/CUMEM
355
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 02/0 : 2[2] -> 3[3] via P2P/CUMEM
356
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 16/0 : 0[0] -> 1[1] via P2P/CUMEM
357
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 01/0 : 4[4] -> 5[5] via P2P/CUMEM
358
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 04/0 : 1[1] -> 2[2] via P2P/CUMEM
359
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 02/0 : 5[5] -> 6[6] via P2P/CUMEM
360
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 13/0 : 3[3] -> 4[4] via P2P/CUMEM
361
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 03/0 : 2[2] -> 3[3] via P2P/CUMEM
362
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 17/0 : 0[0] -> 1[1] via P2P/CUMEM
363
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 02/0 : 4[4] -> 5[5] via P2P/CUMEM
364
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 05/0 : 1[1] -> 2[2] via P2P/CUMEM
365
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 03/0 : 5[5] -> 6[6] via P2P/CUMEM
366
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 14/0 : 3[3] -> 4[4] via P2P/CUMEM
367
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 04/0 : 2[2] -> 3[3] via P2P/CUMEM
368
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 18/0 : 0[0] -> 1[1] via P2P/CUMEM
369
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 06/0 : 7[7] -> 0[0] via P2P/CUMEM
370
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 03/0 : 4[4] -> 5[5] via P2P/CUMEM
371
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 16/0 : 6[6] -> 7[7] via P2P/CUMEM
372
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 04/0 : 5[5] -> 6[6] via P2P/CUMEM
373
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 06/0 : 1[1] -> 2[2] via P2P/CUMEM
374
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 15/0 : 3[3] -> 4[4] via P2P/CUMEM
375
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 05/0 : 2[2] -> 3[3] via P2P/CUMEM
376
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 19/0 : 0[0] -> 1[1] via P2P/CUMEM
377
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 04/0 : 4[4] -> 5[5] via P2P/CUMEM
378
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 07/0 : 7[7] -> 0[0] via P2P/CUMEM
379
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 17/0 : 6[6] -> 7[7] via P2P/CUMEM
380
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 05/0 : 5[5] -> 6[6] via P2P/CUMEM
381
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 16/0 : 3[3] -> 4[4] via P2P/CUMEM
382
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 07/0 : 1[1] -> 2[2] via P2P/CUMEM
383
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 06/0 : 2[2] -> 3[3] via P2P/CUMEM
384
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 20/0 : 0[0] -> 1[1] via P2P/CUMEM
385
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 05/0 : 4[4] -> 5[5] via P2P/CUMEM
386
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 08/0 : 7[7] -> 0[0] via P2P/CUMEM
387
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 18/0 : 6[6] -> 7[7] via P2P/CUMEM
388
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 06/0 : 5[5] -> 6[6] via P2P/CUMEM
389
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 17/0 : 3[3] -> 4[4] via P2P/CUMEM
390
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 08/0 : 1[1] -> 2[2] via P2P/CUMEM
391
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 07/0 : 2[2] -> 3[3] via P2P/CUMEM
392
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 21/0 : 0[0] -> 1[1] via P2P/CUMEM
393
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 06/0 : 4[4] -> 5[5] via P2P/CUMEM
394
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 19/0 : 6[6] -> 7[7] via P2P/CUMEM
395
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 09/0 : 7[7] -> 0[0] via P2P/CUMEM
396
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 07/0 : 5[5] -> 6[6] via P2P/CUMEM
397
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 18/0 : 3[3] -> 4[4] via P2P/CUMEM
398
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 09/0 : 1[1] -> 2[2] via P2P/CUMEM
399
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 08/0 : 2[2] -> 3[3] via P2P/CUMEM
400
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 22/0 : 0[0] -> 1[1] via P2P/CUMEM
401
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 07/0 : 4[4] -> 5[5] via P2P/CUMEM
402
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 20/0 : 6[6] -> 7[7] via P2P/CUMEM
403
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 10/0 : 7[7] -> 0[0] via P2P/CUMEM
404
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 08/0 : 5[5] -> 6[6] via P2P/CUMEM
405
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 19/0 : 3[3] -> 4[4] via P2P/CUMEM
406
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 10/0 : 1[1] -> 2[2] via P2P/CUMEM
407
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 09/0 : 2[2] -> 3[3] via P2P/CUMEM
408
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Channel 23/0 : 0[0] -> 1[1] via P2P/CUMEM
409
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 08/0 : 4[4] -> 5[5] via P2P/CUMEM
410
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 21/0 : 6[6] -> 7[7] via P2P/CUMEM
411
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 11/0 : 7[7] -> 0[0] via P2P/CUMEM
412
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 09/0 : 5[5] -> 6[6] via P2P/CUMEM
413
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 20/0 : 3[3] -> 4[4] via P2P/CUMEM
414
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 11/0 : 1[1] -> 2[2] via P2P/CUMEM
415
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 10/0 : 2[2] -> 3[3] via P2P/CUMEM
416
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 09/0 : 4[4] -> 5[5] via P2P/CUMEM
417
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 22/0 : 6[6] -> 7[7] via P2P/CUMEM
418
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 12/0 : 7[7] -> 0[0] via P2P/CUMEM
419
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 10/0 : 5[5] -> 6[6] via P2P/CUMEM
420
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 21/0 : 3[3] -> 4[4] via P2P/CUMEM
421
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 12/0 : 1[1] -> 2[2] via P2P/CUMEM
422
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 11/0 : 2[2] -> 3[3] via P2P/CUMEM
423
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 10/0 : 4[4] -> 5[5] via P2P/CUMEM
424
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Channel 23/0 : 6[6] -> 7[7] via P2P/CUMEM
425
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 13/0 : 7[7] -> 0[0] via P2P/CUMEM
426
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 11/0 : 5[5] -> 6[6] via P2P/CUMEM
427
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 22/0 : 3[3] -> 4[4] via P2P/CUMEM
428
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 13/0 : 1[1] -> 2[2] via P2P/CUMEM
429
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 12/0 : 2[2] -> 3[3] via P2P/CUMEM
430
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 11/0 : 4[4] -> 5[5] via P2P/CUMEM
431
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 14/0 : 7[7] -> 0[0] via P2P/CUMEM
432
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 12/0 : 5[5] -> 6[6] via P2P/CUMEM
433
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Channel 23/0 : 3[3] -> 4[4] via P2P/CUMEM
434
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 14/0 : 1[1] -> 2[2] via P2P/CUMEM
435
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 13/0 : 2[2] -> 3[3] via P2P/CUMEM
436
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 12/0 : 4[4] -> 5[5] via P2P/CUMEM
437
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 15/0 : 7[7] -> 0[0] via P2P/CUMEM
438
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 13/0 : 5[5] -> 6[6] via P2P/CUMEM
439
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 15/0 : 1[1] -> 2[2] via P2P/CUMEM
440
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 14/0 : 2[2] -> 3[3] via P2P/CUMEM
441
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 13/0 : 4[4] -> 5[5] via P2P/CUMEM
442
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 16/0 : 7[7] -> 0[0] via P2P/CUMEM
443
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 14/0 : 5[5] -> 6[6] via P2P/CUMEM
444
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 16/0 : 1[1] -> 2[2] via P2P/CUMEM
445
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 15/0 : 2[2] -> 3[3] via P2P/CUMEM
446
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 14/0 : 4[4] -> 5[5] via P2P/CUMEM
447
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 17/0 : 7[7] -> 0[0] via P2P/CUMEM
448
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 15/0 : 5[5] -> 6[6] via P2P/CUMEM
449
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 17/0 : 1[1] -> 2[2] via P2P/CUMEM
450
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 16/0 : 2[2] -> 3[3] via P2P/CUMEM
451
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 15/0 : 4[4] -> 5[5] via P2P/CUMEM
452
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 18/0 : 7[7] -> 0[0] via P2P/CUMEM
453
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 16/0 : 5[5] -> 6[6] via P2P/CUMEM
454
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 18/0 : 1[1] -> 2[2] via P2P/CUMEM
455
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 17/0 : 2[2] -> 3[3] via P2P/CUMEM
456
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 16/0 : 4[4] -> 5[5] via P2P/CUMEM
457
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 19/0 : 7[7] -> 0[0] via P2P/CUMEM
458
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 17/0 : 5[5] -> 6[6] via P2P/CUMEM
459
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 19/0 : 1[1] -> 2[2] via P2P/CUMEM
460
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 18/0 : 2[2] -> 3[3] via P2P/CUMEM
461
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 17/0 : 4[4] -> 5[5] via P2P/CUMEM
462
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 20/0 : 7[7] -> 0[0] via P2P/CUMEM
463
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 18/0 : 5[5] -> 6[6] via P2P/CUMEM
464
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 20/0 : 1[1] -> 2[2] via P2P/CUMEM
465
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 19/0 : 2[2] -> 3[3] via P2P/CUMEM
466
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 18/0 : 4[4] -> 5[5] via P2P/CUMEM
467
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 21/0 : 7[7] -> 0[0] via P2P/CUMEM
468
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 19/0 : 5[5] -> 6[6] via P2P/CUMEM
469
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 21/0 : 1[1] -> 2[2] via P2P/CUMEM
470
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 20/0 : 2[2] -> 3[3] via P2P/CUMEM
471
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 19/0 : 4[4] -> 5[5] via P2P/CUMEM
472
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 22/0 : 7[7] -> 0[0] via P2P/CUMEM
473
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 20/0 : 5[5] -> 6[6] via P2P/CUMEM
474
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 22/0 : 1[1] -> 2[2] via P2P/CUMEM
475
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 21/0 : 2[2] -> 3[3] via P2P/CUMEM
476
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 20/0 : 4[4] -> 5[5] via P2P/CUMEM
477
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Channel 23/0 : 7[7] -> 0[0] via P2P/CUMEM
478
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 21/0 : 5[5] -> 6[6] via P2P/CUMEM
479
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Channel 23/0 : 1[1] -> 2[2] via P2P/CUMEM
480
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 22/0 : 2[2] -> 3[3] via P2P/CUMEM
481
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 21/0 : 4[4] -> 5[5] via P2P/CUMEM
482
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 22/0 : 5[5] -> 6[6] via P2P/CUMEM
483
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Channel 23/0 : 2[2] -> 3[3] via P2P/CUMEM
484
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 22/0 : 4[4] -> 5[5] via P2P/CUMEM
485
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Channel 23/0 : 5[5] -> 6[6] via P2P/CUMEM
486
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Channel 23/0 : 4[4] -> 5[5] via P2P/CUMEM
487
+ t-20260528052235-lvfnr-worker-0:10305:10470 [6] NCCL INFO Connected all rings, use ring PXN 0 GDR 1
488
+ t-20260528052235-lvfnr-worker-0:10304:10474 [5] NCCL INFO Connected all rings, use ring PXN 0 GDR 1
489
+ t-20260528052235-lvfnr-worker-0:10301:10472 [2] NCCL INFO Connected all rings, use ring PXN 0 GDR 1
490
+ t-20260528052235-lvfnr-worker-0:10300:10471 [1] NCCL INFO Connected all rings, use ring PXN 0 GDR 1
491
+ t-20260528052235-lvfnr-worker-0:10299:10468 [0] NCCL INFO Connected all rings, use ring PXN 0 GDR 1
492
+ t-20260528052235-lvfnr-worker-0:10306:10467 [7] NCCL INFO Connected all rings, use ring PXN 0 GDR 1
493
+ t-20260528052235-lvfnr-worker-0:10303:10473 [4] NCCL INFO Connected all rings, use ring PXN 0 GDR 1
494
+ t-20260528052235-lvfnr-worker-0:10302:10469 [3] NCCL INFO Connected all rings, use ring PXN 0 GDR 1
495
+ {
496
+ "data_mode": "cache",
497
+ "cache_path": "cache/owt_t5_stream_pack1023_ultraclean_probe80k_rowvalid_10k_seed20260527_appendeos1.pt",
498
+ "data_path": "/e2e-data/evad-tech-vla/wanghan58/data/small_benchmarks/langflow_2604_11748/openwebtext",
499
+ "tokenizer_path": "/e2e-data/evad-tech-vla/wanghan58/models/hf/t5-small/tokenizer.json",
500
+ "text_column": "text",
501
+ "pack_len": 1023,
502
+ "append_eos": 1,
503
+ "num_workers": 0,
504
+ "shuffle_buffer": 8192,
505
+ "reject_txt": "cache/online_rejected.txt",
506
+ "out_dir": "runs/owt_t5_ultraclean10k_len1024_C4096_to_32768_exp_d768_l12_h12_gbs512_8gpu_40k_lr3e4_20260527_212316",
507
+ "subset_size": 10000,
508
+ "resume": "",
509
+ "steps": 40000,
510
+ "batch_size": 32,
511
+ "grad_accum": 2,
512
+ "lr": 0.0003,
513
+ "log_every": 50,
514
+ "save_every": 1000,
515
+ "dim": 768,
516
+ "layers": 12,
517
+ "heads": 12,
518
+ "mlp_dim": 3072,
519
+ "time_tokens": 4,
520
+ "c_min": 4096.0,
521
+ "c_max": 32768.0,
522
+ "c_schedule": "exp",
523
+ "seed": 1234
524
+ }
525
+ [data] mode=cache rows=10000 length=1024 vocab=32100 seen=80003 dropped=15766 bos=1:</s> eos=1:</s>
526
+ t-20260528052235-lvfnr-worker-0:10302:10563 [3] NCCL INFO NVLS comm 0x8d69240 headRank 3 nHeads 8 buffSize 1048576 nvlsPerRankSize 33554432 nvlsTotalSize 268435456
527
+ t-20260528052235-lvfnr-worker-0:10300:10564 [1] NCCL INFO NVLS comm 0xcebc1b0 headRank 1 nHeads 8 buffSize 1048576 nvlsPerRankSize 33554432 nvlsTotalSize 268435456
528
+ t-20260528052235-lvfnr-worker-0:10306:10565 [7] NCCL INFO NVLS comm 0xa010c30 headRank 7 nHeads 8 buffSize 1048576 nvlsPerRankSize 33554432 nvlsTotalSize 268435456
529
+ t-20260528052235-lvfnr-worker-0:10303:10566 [4] NCCL INFO NVLS comm 0xc7a6880 headRank 4 nHeads 8 buffSize 1048576 nvlsPerRankSize 33554432 nvlsTotalSize 268435456
530
+ t-20260528052235-lvfnr-worker-0:10301:10567 [2] NCCL INFO NVLS comm 0xcec7380 headRank 2 nHeads 8 buffSize 1048576 nvlsPerRankSize 33554432 nvlsTotalSize 268435456
531
+ t-20260528052235-lvfnr-worker-0:10304:10568 [5] NCCL INFO NVLS comm 0xce66c40 headRank 5 nHeads 8 buffSize 1048576 nvlsPerRankSize 33554432 nvlsTotalSize 268435456
532
+ t-20260528052235-lvfnr-worker-0:10305:10570 [6] NCCL INFO NVLS comm 0x919e3e0 headRank 6 nHeads 8 buffSize 1048576 nvlsPerRankSize 33554432 nvlsTotalSize 268435456
533
+ t-20260528052235-lvfnr-worker-0:10299:10569 [0] NCCL INFO NVLS comm 0x95c7e40 headRank 0 nHeads 8 buffSize 1048576 nvlsPerRankSize 33554432 nvlsTotalSize 268435456
534
+ step=50 loss=7.1228 {'pos0_bos_p': 0.0019045539665967226, 'pos0_bos_top1': 0, 'last_eos_p': 0.010252108797430992, 'last_eos_top1': 0}
535
+ step=100 loss=7.1434 {'pos0_bos_p': 0.00042073283111676574, 'pos0_bos_top1': 0, 'last_eos_p': 0.9972795844078064, 'last_eos_top1': 4}
536
+ step=150 loss=6.7899 {'pos0_bos_p': 0.0011103940196335316, 'pos0_bos_top1': 0, 'last_eos_p': 0.9403679966926575, 'last_eos_top1': 4}
537
+ step=200 loss=6.5186 {'pos0_bos_p': 0.0008917325758375227, 'pos0_bos_top1': 0, 'last_eos_p': 0.9825672507286072, 'last_eos_top1': 4}
538
+ step=250 loss=6.0590 {'pos0_bos_p': 0.001217335811816156, 'pos0_bos_top1': 0, 'last_eos_p': 0.9862273335456848, 'last_eos_top1': 4}
539
+ step=300 loss=6.1027 {'pos0_bos_p': 0.002536393003538251, 'pos0_bos_top1': 0, 'last_eos_p': 0.9804686307907104, 'last_eos_top1': 4}
540
+ step=350 loss=5.8705 {'pos0_bos_p': 0.001197237172164023, 'pos0_bos_top1': 0, 'last_eos_p': 0.9804034233093262, 'last_eos_top1': 4}
541
+ step=400 loss=5.7510 {'pos0_bos_p': 0.001667062402702868, 'pos0_bos_top1': 0, 'last_eos_p': 0.9864185452461243, 'last_eos_top1': 4}
542
+ step=450 loss=5.1534 {'pos0_bos_p': 0.0024044252932071686, 'pos0_bos_top1': 0, 'last_eos_p': 0.9860549569129944, 'last_eos_top1': 4}
543
+ step=500 loss=5.1372 {'pos0_bos_p': 0.001829120796173811, 'pos0_bos_top1': 0, 'last_eos_p': 0.9869738817214966, 'last_eos_top1': 4}
544
+ step=550 loss=5.2508 {'pos0_bos_p': 0.0011939660180360079, 'pos0_bos_top1': 0, 'last_eos_p': 0.9870648384094238, 'last_eos_top1': 4}
545
+ step=600 loss=4.7833 {'pos0_bos_p': 0.001596515066921711, 'pos0_bos_top1': 0, 'last_eos_p': 0.9869128465652466, 'last_eos_top1': 4}
546
+ step=650 loss=4.8124 {'pos0_bos_p': 0.001284916652366519, 'pos0_bos_top1': 0, 'last_eos_p': 0.9870219826698303, 'last_eos_top1': 4}
547
+ step=700 loss=4.6599 {'pos0_bos_p': 0.0014337411848828197, 'pos0_bos_top1': 0, 'last_eos_p': 0.9863752722740173, 'last_eos_top1': 4}
548
+ step=750 loss=4.4790 {'pos0_bos_p': 0.0012800463009625673, 'pos0_bos_top1': 0, 'last_eos_p': 0.987720787525177, 'last_eos_top1': 4}
549
+ step=800 loss=4.5593 {'pos0_bos_p': 0.0014664315385743976, 'pos0_bos_top1': 0, 'last_eos_p': 0.9885030388832092, 'last_eos_top1': 4}
550
+ step=850 loss=4.4832 {'pos0_bos_p': 0.0012145357904955745, 'pos0_bos_top1': 0, 'last_eos_p': 0.9880351424217224, 'last_eos_top1': 4}
551
+ step=900 loss=4.7124 {'pos0_bos_p': 0.0010197763331234455, 'pos0_bos_top1': 0, 'last_eos_p': 0.9898796081542969, 'last_eos_top1': 4}
552
+ step=950 loss=4.6711 {'pos0_bos_p': 0.0011980183189734817, 'pos0_bos_top1': 0, 'last_eos_p': 0.9903967380523682, 'last_eos_top1': 4}
553
+ step=1000 loss=4.3427 {'pos0_bos_p': 0.0012490765657275915, 'pos0_bos_top1': 0, 'last_eos_p': 0.9919277429580688, 'last_eos_top1': 4}
554
+ step=1050 loss=4.4249 {'pos0_bos_p': 0.0015577699523419142, 'pos0_bos_top1': 0, 'last_eos_p': 0.9943477511405945, 'last_eos_top1': 4}
555
+ step=1100 loss=4.4758 {'pos0_bos_p': 0.0007777540595270693, 'pos0_bos_top1': 0, 'last_eos_p': 0.9934155941009521, 'last_eos_top1': 4}
556
+ step=1150 loss=3.7029 {'pos0_bos_p': 0.0009281560778617859, 'pos0_bos_top1': 0, 'last_eos_p': 0.9941577911376953, 'last_eos_top1': 4}
557
+ step=1200 loss=4.6245 {'pos0_bos_p': 0.0009716648492030799, 'pos0_bos_top1': 0, 'last_eos_p': 0.9952744245529175, 'last_eos_top1': 4}
558
+ step=1250 loss=3.6213 {'pos0_bos_p': 0.0007597565418109298, 'pos0_bos_top1': 0, 'last_eos_p': 0.995770275592804, 'last_eos_top1': 4}
559
+ step=1300 loss=3.6857 {'pos0_bos_p': 0.0007579440716654062, 'pos0_bos_top1': 0, 'last_eos_p': 0.9962783455848694, 'last_eos_top1': 4}
560
+ step=1350 loss=3.8707 {'pos0_bos_p': 0.0007095331093296409, 'pos0_bos_top1': 0, 'last_eos_p': 0.99689120054245, 'last_eos_top1': 4}
561
+ step=1400 loss=3.7336 {'pos0_bos_p': 0.0008909617899917066, 'pos0_bos_top1': 0, 'last_eos_p': 0.9970274567604065, 'last_eos_top1': 4}
562
+ step=1450 loss=3.6988 {'pos0_bos_p': 0.0009782277047634125, 'pos0_bos_top1': 0, 'last_eos_p': 0.9973872303962708, 'last_eos_top1': 4}
563
+ step=1500 loss=3.5358 {'pos0_bos_p': 0.0009436120162717998, 'pos0_bos_top1': 0, 'last_eos_p': 0.9975798726081848, 'last_eos_top1': 4}
564
+ step=1550 loss=4.3268 {'pos0_bos_p': 0.0009957518195733428, 'pos0_bos_top1': 0, 'last_eos_p': 0.9976412057876587, 'last_eos_top1': 4}
565
+ step=1600 loss=3.4677 {'pos0_bos_p': 0.000908614369109273, 'pos0_bos_top1': 0, 'last_eos_p': 0.9979562759399414, 'last_eos_top1': 4}
566
+ step=1650 loss=3.5105 {'pos0_bos_p': 0.0009317692019976676, 'pos0_bos_top1': 0, 'last_eos_p': 0.998079776763916, 'last_eos_top1': 4}
567
+ step=1700 loss=3.7310 {'pos0_bos_p': 0.0010493824956938624, 'pos0_bos_top1': 0, 'last_eos_p': 0.9982014894485474, 'last_eos_top1': 4}
568
+ step=1750 loss=3.6179 {'pos0_bos_p': 0.0009264908730983734, 'pos0_bos_top1': 0, 'last_eos_p': 0.9982447624206543, 'last_eos_top1': 4}
569
+ step=1800 loss=3.7720 {'pos0_bos_p': 0.0010388639057055116, 'pos0_bos_top1': 0, 'last_eos_p': 0.9982740879058838, 'last_eos_top1': 4}
570
+ step=1850 loss=2.9854 {'pos0_bos_p': 0.0010407152585685253, 'pos0_bos_top1': 0, 'last_eos_p': 0.998422384262085, 'last_eos_top1': 4}
571
+ step=1900 loss=3.4438 {'pos0_bos_p': 0.0011615091934800148, 'pos0_bos_top1': 0, 'last_eos_p': 0.9984297156333923, 'last_eos_top1': 4}
572
+ step=1950 loss=3.0192 {'pos0_bos_p': 0.0009644241072237492, 'pos0_bos_top1': 0, 'last_eos_p': 0.9983976483345032, 'last_eos_top1': 4}
573
+ step=2000 loss=2.9811 {'pos0_bos_p': 0.0010724756866693497, 'pos0_bos_top1': 0, 'last_eos_p': 0.9983878135681152, 'last_eos_top1': 4}
574
+ step=2050 loss=2.9872 {'pos0_bos_p': 0.0007766140624880791, 'pos0_bos_top1': 0, 'last_eos_p': 0.9984954595565796, 'last_eos_top1': 4}
575
+ step=2100 loss=3.5225 {'pos0_bos_p': 0.000930797541514039, 'pos0_bos_top1': 0, 'last_eos_p': 0.9985345602035522, 'last_eos_top1': 4}
576
+ step=2150 loss=3.1885 {'pos0_bos_p': 0.000730251194909215, 'pos0_bos_top1': 0, 'last_eos_p': 0.9986714124679565, 'last_eos_top1': 4}
577
+ step=2200 loss=3.4761 {'pos0_bos_p': 0.0009825056185945868, 'pos0_bos_top1': 0, 'last_eos_p': 0.9985960125923157, 'last_eos_top1': 4}
578
+ step=2250 loss=2.9302 {'pos0_bos_p': 0.001204384258016944, 'pos0_bos_top1': 0, 'last_eos_p': 0.9987609386444092, 'last_eos_top1': 4}
579
+ step=2300 loss=3.3332 {'pos0_bos_p': 0.0009695333428680897, 'pos0_bos_top1': 0, 'last_eos_p': 0.9987534284591675, 'last_eos_top1': 4}
580
+ step=2350 loss=3.0643 {'pos0_bos_p': 0.0009657082264311612, 'pos0_bos_top1': 0, 'last_eos_p': 0.998688280582428, 'last_eos_top1': 4}
581
+ step=2400 loss=3.0399 {'pos0_bos_p': 0.0012310727033764124, 'pos0_bos_top1': 0, 'last_eos_p': 0.9988003969192505, 'last_eos_top1': 4}
582
+ step=2450 loss=3.4925 {'pos0_bos_p': 0.0008470729226246476, 'pos0_bos_top1': 0, 'last_eos_p': 0.998854398727417, 'last_eos_top1': 4}
583
+ step=2500 loss=3.2871 {'pos0_bos_p': 0.0006296156789176166, 'pos0_bos_top1': 0, 'last_eos_p': 0.9987519979476929, 'last_eos_top1': 4}
584
+ step=2550 loss=3.1758 {'pos0_bos_p': 0.0009265568223781884, 'pos0_bos_top1': 0, 'last_eos_p': 0.9988577365875244, 'last_eos_top1': 4}
585
+ step=2600 loss=2.8663 {'pos0_bos_p': 0.0008602665038779378, 'pos0_bos_top1': 0, 'last_eos_p': 0.9987666606903076, 'last_eos_top1': 4}
586
+ step=2650 loss=3.0329 {'pos0_bos_p': 0.0008244539494626224, 'pos0_bos_top1': 0, 'last_eos_p': 0.9988536834716797, 'last_eos_top1': 4}
587
+ step=2700 loss=3.4154 {'pos0_bos_p': 0.0007191206677816808, 'pos0_bos_top1': 0, 'last_eos_p': 0.998994767665863, 'last_eos_top1': 4}
588
+ step=2750 loss=3.3015 {'pos0_bos_p': 0.0007164740818552673, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991008043289185, 'last_eos_top1': 4}
589
+ step=2800 loss=2.6920 {'pos0_bos_p': 0.0008439717930741608, 'pos0_bos_top1': 0, 'last_eos_p': 0.9990654587745667, 'last_eos_top1': 4}
590
+ step=2850 loss=3.0997 {'pos0_bos_p': 0.0008432737668044865, 'pos0_bos_top1': 0, 'last_eos_p': 0.9990019202232361, 'last_eos_top1': 4}
591
+ step=2900 loss=3.0128 {'pos0_bos_p': 0.0008241361356340349, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991840720176697, 'last_eos_top1': 4}
592
+ step=2950 loss=2.3291 {'pos0_bos_p': 0.0007474969606846571, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992383718490601, 'last_eos_top1': 4}
593
+ step=3000 loss=3.3041 {'pos0_bos_p': 0.0008691821130923927, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991764426231384, 'last_eos_top1': 4}
594
+ step=3050 loss=2.6755 {'pos0_bos_p': 0.000884750799741596, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991933703422546, 'last_eos_top1': 4}
595
+ step=3100 loss=2.9095 {'pos0_bos_p': 0.0007487277616746724, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991087317466736, 'last_eos_top1': 4}
596
+ step=3150 loss=2.6376 {'pos0_bos_p': 0.0008386721601709723, 'pos0_bos_top1': 0, 'last_eos_p': 0.999219536781311, 'last_eos_top1': 4}
597
+ step=3200 loss=3.0389 {'pos0_bos_p': 0.0005033225752413273, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991424083709717, 'last_eos_top1': 4}
598
+ step=3250 loss=3.5516 {'pos0_bos_p': 0.0007498532067984343, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991549253463745, 'last_eos_top1': 4}
599
+ step=3300 loss=2.9669 {'pos0_bos_p': 0.0006075959536246955, 'pos0_bos_top1': 0, 'last_eos_p': 0.9993537068367004, 'last_eos_top1': 4}
600
+ step=3350 loss=2.8941 {'pos0_bos_p': 0.0006255818880163133, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992604851722717, 'last_eos_top1': 4}
601
+ step=3400 loss=2.4231 {'pos0_bos_p': 0.0006005432223901153, 'pos0_bos_top1': 0, 'last_eos_p': 0.9993374943733215, 'last_eos_top1': 4}
602
+ step=3450 loss=3.0347 {'pos0_bos_p': 0.000714322435669601, 'pos0_bos_top1': 0, 'last_eos_p': 0.9993426203727722, 'last_eos_top1': 4}
603
+ step=3500 loss=2.6405 {'pos0_bos_p': 0.0006911610253155231, 'pos0_bos_top1': 0, 'last_eos_p': 0.999247670173645, 'last_eos_top1': 4}
604
+ step=3550 loss=3.0160 {'pos0_bos_p': 0.0006793943466618657, 'pos0_bos_top1': 0, 'last_eos_p': 0.9993601441383362, 'last_eos_top1': 4}
605
+ step=3600 loss=2.7247 {'pos0_bos_p': 0.0006277165375649929, 'pos0_bos_top1': 0, 'last_eos_p': 0.999326229095459, 'last_eos_top1': 4}
606
+ step=3650 loss=2.6101 {'pos0_bos_p': 0.0007806556532159448, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992813467979431, 'last_eos_top1': 4}
607
+ step=3700 loss=2.7879 {'pos0_bos_p': 0.000695927650667727, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992989301681519, 'last_eos_top1': 4}
608
+ step=3750 loss=3.1240 {'pos0_bos_p': 0.0004254880186636001, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991540908813477, 'last_eos_top1': 4}
609
+ step=3800 loss=3.0976 {'pos0_bos_p': 0.0008554062806069851, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992836117744446, 'last_eos_top1': 4}
610
+ step=3850 loss=3.0993 {'pos0_bos_p': 0.0004907391266897321, 'pos0_bos_top1': 0, 'last_eos_p': 0.9993964433670044, 'last_eos_top1': 4}
611
+ step=3900 loss=2.9258 {'pos0_bos_p': 0.0006513699190691113, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992951154708862, 'last_eos_top1': 4}
612
+ step=3950 loss=3.1170 {'pos0_bos_p': 0.0007697808905504644, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992783665657043, 'last_eos_top1': 4}
613
+ step=4000 loss=2.8308 {'pos0_bos_p': 0.0004717964620795101, 'pos0_bos_top1': 0, 'last_eos_p': 0.999384880065918, 'last_eos_top1': 4}
614
+ step=4050 loss=2.8822 {'pos0_bos_p': 0.000635715841781348, 'pos0_bos_top1': 0, 'last_eos_p': 0.9994264841079712, 'last_eos_top1': 4}
615
+ step=4100 loss=3.0471 {'pos0_bos_p': 0.000768937636166811, 'pos0_bos_top1': 0, 'last_eos_p': 0.9993540644645691, 'last_eos_top1': 4}
616
+ step=4150 loss=2.7838 {'pos0_bos_p': 0.0008931310730986297, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992462396621704, 'last_eos_top1': 4}
617
+ step=4200 loss=2.7448 {'pos0_bos_p': 0.0005247585359029472, 'pos0_bos_top1': 0, 'last_eos_p': 0.9993844032287598, 'last_eos_top1': 4}
618
+ step=4250 loss=3.0325 {'pos0_bos_p': 0.0006107465014792979, 'pos0_bos_top1': 0, 'last_eos_p': 0.9994292855262756, 'last_eos_top1': 4}
619
+ step=4300 loss=2.9740 {'pos0_bos_p': 0.0006588331889361143, 'pos0_bos_top1': 0, 'last_eos_p': 0.999228835105896, 'last_eos_top1': 4}
620
+ step=4350 loss=3.0795 {'pos0_bos_p': 0.0007223390857689083, 'pos0_bos_top1': 0, 'last_eos_p': 0.999248206615448, 'last_eos_top1': 4}
621
+ step=4400 loss=2.7557 {'pos0_bos_p': 0.0009390123886987567, 'pos0_bos_top1': 0, 'last_eos_p': 0.9993976354598999, 'last_eos_top1': 4}
622
+ step=4450 loss=2.7971 {'pos0_bos_p': 0.0007036151364445686, 'pos0_bos_top1': 0, 'last_eos_p': 0.9995077848434448, 'last_eos_top1': 4}
623
+ step=4500 loss=2.5748 {'pos0_bos_p': 0.000773977255448699, 'pos0_bos_top1': 0, 'last_eos_p': 0.9993659853935242, 'last_eos_top1': 4}
624
+ step=4550 loss=2.9357 {'pos0_bos_p': 0.0008800712530501187, 'pos0_bos_top1': 0, 'last_eos_p': 0.9993867874145508, 'last_eos_top1': 4}
625
+ step=4600 loss=2.5206 {'pos0_bos_p': 0.0007377828587777913, 'pos0_bos_top1': 0, 'last_eos_p': 0.9994648098945618, 'last_eos_top1': 4}
626
+ step=4650 loss=2.7212 {'pos0_bos_p': 0.0007580575183965266, 'pos0_bos_top1': 0, 'last_eos_p': 0.9994601607322693, 'last_eos_top1': 4}
627
+ step=4700 loss=2.8740 {'pos0_bos_p': 0.0006156228482723236, 'pos0_bos_top1': 0, 'last_eos_p': 0.999264657497406, 'last_eos_top1': 4}
628
+ step=4750 loss=3.0526 {'pos0_bos_p': 0.0006342521519400179, 'pos0_bos_top1': 0, 'last_eos_p': 0.999297022819519, 'last_eos_top1': 4}
629
+ step=4800 loss=2.8730 {'pos0_bos_p': 0.000740743416827172, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992921352386475, 'last_eos_top1': 4}
630
+ step=4850 loss=2.8685 {'pos0_bos_p': 0.0006380485720001161, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992501139640808, 'last_eos_top1': 4}
631
+ step=4900 loss=2.7638 {'pos0_bos_p': 0.0005786812398582697, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991870522499084, 'last_eos_top1': 4}
632
+ step=4950 loss=2.6238 {'pos0_bos_p': 0.0006091449176892638, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991648197174072, 'last_eos_top1': 4}
633
+ step=5000 loss=2.4685 {'pos0_bos_p': 0.000684699509292841, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992815852165222, 'last_eos_top1': 4}
634
+ step=5050 loss=2.4113 {'pos0_bos_p': 0.00050110905431211, 'pos0_bos_top1': 0, 'last_eos_p': 0.999278724193573, 'last_eos_top1': 4}
635
+ step=5100 loss=2.9088 {'pos0_bos_p': 0.0005313889123499393, 'pos0_bos_top1': 0, 'last_eos_p': 0.999170184135437, 'last_eos_top1': 4}
636
+ step=5150 loss=2.5220 {'pos0_bos_p': 0.0005848270375281572, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991790652275085, 'last_eos_top1': 4}
637
+ step=5200 loss=2.5151 {'pos0_bos_p': 0.0008432670729234815, 'pos0_bos_top1': 0, 'last_eos_p': 0.9993453621864319, 'last_eos_top1': 4}
638
+ step=5250 loss=2.8306 {'pos0_bos_p': 0.0009108633967116475, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992652535438538, 'last_eos_top1': 4}
639
+ step=5300 loss=2.5167 {'pos0_bos_p': 0.0010536877671256661, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991229176521301, 'last_eos_top1': 4}
640
+ step=5350 loss=2.8203 {'pos0_bos_p': 0.0006855487590655684, 'pos0_bos_top1': 0, 'last_eos_p': 0.9993834495544434, 'last_eos_top1': 4}
641
+ step=5400 loss=2.5030 {'pos0_bos_p': 0.0006188146653585136, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992848038673401, 'last_eos_top1': 4}
642
+ step=5450 loss=2.6654 {'pos0_bos_p': 0.0006890347576700151, 'pos0_bos_top1': 0, 'last_eos_p': 0.999160647392273, 'last_eos_top1': 4}
643
+ step=5500 loss=2.3946 {'pos0_bos_p': 0.000737423135433346, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991815686225891, 'last_eos_top1': 4}
644
+ step=5550 loss=3.0131 {'pos0_bos_p': 0.0008019988308660686, 'pos0_bos_top1': 0, 'last_eos_p': 0.9990608096122742, 'last_eos_top1': 4}
645
+ step=5600 loss=2.7925 {'pos0_bos_p': 0.0005938691319897771, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991318583488464, 'last_eos_top1': 4}
646
+ step=5650 loss=2.7450 {'pos0_bos_p': 0.0006745798164047301, 'pos0_bos_top1': 0, 'last_eos_p': 0.9989751577377319, 'last_eos_top1': 4}
647
+ step=5700 loss=2.6491 {'pos0_bos_p': 0.0008223381591960788, 'pos0_bos_top1': 0, 'last_eos_p': 0.999255359172821, 'last_eos_top1': 4}
648
+ step=5750 loss=2.8562 {'pos0_bos_p': 0.0006917612627148628, 'pos0_bos_top1': 0, 'last_eos_p': 0.999447762966156, 'last_eos_top1': 4}
649
+ step=5800 loss=2.5180 {'pos0_bos_p': 0.0008420003578066826, 'pos0_bos_top1': 0, 'last_eos_p': 0.9990509152412415, 'last_eos_top1': 4}
650
+ step=5850 loss=2.8989 {'pos0_bos_p': 0.0008550017373636365, 'pos0_bos_top1': 0, 'last_eos_p': 0.9990940093994141, 'last_eos_top1': 4}
651
+ step=5900 loss=1.9623 {'pos0_bos_p': 0.0008237525471486151, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991647005081177, 'last_eos_top1': 4}
652
+ step=5950 loss=3.0246 {'pos0_bos_p': 0.0010133307659998536, 'pos0_bos_top1': 0, 'last_eos_p': 0.999256432056427, 'last_eos_top1': 4}
653
+ step=6000 loss=2.4829 {'pos0_bos_p': 0.0009167233947664499, 'pos0_bos_top1': 0, 'last_eos_p': 0.999213695526123, 'last_eos_top1': 4}
654
+ step=6050 loss=2.7540 {'pos0_bos_p': 0.000716303416993469, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991413354873657, 'last_eos_top1': 4}
655
+ step=6100 loss=3.2656 {'pos0_bos_p': 0.000814702536445111, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991452693939209, 'last_eos_top1': 4}
656
+ step=6150 loss=2.6433 {'pos0_bos_p': 0.0007208568858914077, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992269277572632, 'last_eos_top1': 4}
657
+ step=6200 loss=2.3956 {'pos0_bos_p': 0.0006785871810279787, 'pos0_bos_top1': 0, 'last_eos_p': 0.9992161989212036, 'last_eos_top1': 4}
658
+ step=6250 loss=2.4800 {'pos0_bos_p': 0.000884954642970115, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991790652275085, 'last_eos_top1': 4}
659
+ step=6300 loss=2.8687 {'pos0_bos_p': 0.0006654368480667472, 'pos0_bos_top1': 0, 'last_eos_p': 0.9989078044891357, 'last_eos_top1': 4}
660
+ step=6350 loss=2.7883 {'pos0_bos_p': 0.0007044913363642991, 'pos0_bos_top1': 0, 'last_eos_p': 0.9985566735267639, 'last_eos_top1': 4}
661
+ step=6400 loss=2.6162 {'pos0_bos_p': 0.000603503140155226, 'pos0_bos_top1': 0, 'last_eos_p': 0.9987297654151917, 'last_eos_top1': 4}
662
+ step=6450 loss=2.6558 {'pos0_bos_p': 0.0006924325134605169, 'pos0_bos_top1': 0, 'last_eos_p': 0.9990050196647644, 'last_eos_top1': 4}
663
+ step=6500 loss=2.8178 {'pos0_bos_p': 0.0008079643012024462, 'pos0_bos_top1': 0, 'last_eos_p': 0.9986687898635864, 'last_eos_top1': 4}
664
+ step=6550 loss=2.3740 {'pos0_bos_p': 0.0008527531754225492, 'pos0_bos_top1': 0, 'last_eos_p': 0.9989016056060791, 'last_eos_top1': 4}
665
+ step=6600 loss=2.5708 {'pos0_bos_p': 0.0009096905705519021, 'pos0_bos_top1': 0, 'last_eos_p': 0.9988553524017334, 'last_eos_top1': 4}
666
+ step=6650 loss=2.3440 {'pos0_bos_p': 0.0008201909367926419, 'pos0_bos_top1': 0, 'last_eos_p': 0.9989750385284424, 'last_eos_top1': 4}
667
+ step=6700 loss=2.4336 {'pos0_bos_p': 0.0008251758990809321, 'pos0_bos_top1': 0, 'last_eos_p': 0.9988362193107605, 'last_eos_top1': 4}
668
+ step=6750 loss=2.7569 {'pos0_bos_p': 0.0007772842654958367, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991196990013123, 'last_eos_top1': 4}
669
+ step=6800 loss=2.2757 {'pos0_bos_p': 0.0005473861237987876, 'pos0_bos_top1': 0, 'last_eos_p': 0.9990571141242981, 'last_eos_top1': 4}
670
+ step=6850 loss=2.6205 {'pos0_bos_p': 0.0008291201665997505, 'pos0_bos_top1': 0, 'last_eos_p': 0.9987955093383789, 'last_eos_top1': 4}
671
+ step=6900 loss=2.1564 {'pos0_bos_p': 0.0008855836349539459, 'pos0_bos_top1': 0, 'last_eos_p': 0.9991982579231262, 'last_eos_top1': 4}
672
+ step=6950 loss=2.6010 {'pos0_bos_p': 0.0006183949881233275, 'pos0_bos_top1': 0, 'last_eos_p': 0.9990167617797852, 'last_eos_top1': 4}
673
+ step=7000 loss=2.8135 {'pos0_bos_p': 0.000769881356973201, 'pos0_bos_top1': 0, 'last_eos_p': 0.9988486766815186, 'last_eos_top1': 4}
674
+ step=7050 loss=2.5095 {'pos0_bos_p': 0.0006667476845905185, 'pos0_bos_top1': 0, 'last_eos_p': 0.9989122152328491, 'last_eos_top1': 4}
675
+ step=7100 loss=2.4432 {'pos0_bos_p': 0.0008150693029165268, 'pos0_bos_top1': 0, 'last_eos_p': 0.9988364577293396, 'last_eos_top1': 4}
676
+ step=7150 loss=2.7365 {'pos0_bos_p': 0.000947561115026474, 'pos0_bos_top1': 0, 'last_eos_p': 0.9986352324485779, 'last_eos_top1': 4}
677
+ step=7200 loss=2.0627 {'pos0_bos_p': 0.0007095952169038355, 'pos0_bos_top1': 0, 'last_eos_p': 0.9989629983901978, 'last_eos_top1': 4}
678
+ step=7250 loss=2.6835 {'pos0_bos_p': 0.0006409320048987865, 'pos0_bos_top1': 0, 'last_eos_p': 0.998291552066803, 'last_eos_top1': 4}
679
+ step=7300 loss=2.3597 {'pos0_bos_p': 0.0008239856106229126, 'pos0_bos_top1': 0, 'last_eos_p': 0.9990217685699463, 'last_eos_top1': 4}
680
+ step=7350 loss=2.8695 {'pos0_bos_p': 0.0007445314549840987, 'pos0_bos_top1': 0, 'last_eos_p': 0.9984349608421326, 'last_eos_top1': 4}
681
+ step=7400 loss=2.6584 {'pos0_bos_p': 0.0008714564028196037, 'pos0_bos_top1': 0, 'last_eos_p': 0.9987302422523499, 'last_eos_top1': 4}
682
+ step=7450 loss=2.7820 {'pos0_bos_p': 0.0007681816932745278, 'pos0_bos_top1': 0, 'last_eos_p': 0.998702883720398, 'last_eos_top1': 4}
683
+ step=7500 loss=3.0568 {'pos0_bos_p': 0.0007770757074467838, 'pos0_bos_top1': 0, 'last_eos_p': 0.998542070388794, 'last_eos_top1': 4}
684
+ step=7550 loss=2.3619 {'pos0_bos_p': 0.0006897128187119961, 'pos0_bos_top1': 0, 'last_eos_p': 0.9985713958740234, 'last_eos_top1': 4}
685
+ step=7600 loss=2.0023 {'pos0_bos_p': 0.0008945409208536148, 'pos0_bos_top1': 0, 'last_eos_p': 0.998450517654419, 'last_eos_top1': 4}
686
+ step=7650 loss=3.4515 {'pos0_bos_p': 0.0008103225845843554, 'pos0_bos_top1': 0, 'last_eos_p': 0.9984140396118164, 'last_eos_top1': 4}
687
+ step=7700 loss=2.3593 {'pos0_bos_p': 0.0007089058053679764, 'pos0_bos_top1': 0, 'last_eos_p': 0.9984318614006042, 'last_eos_top1': 4}
688
+ step=7750 loss=2.8948 {'pos0_bos_p': 0.0008973771473392844, 'pos0_bos_top1': 0, 'last_eos_p': 0.99854975938797, 'last_eos_top1': 4}
689
+ step=7800 loss=2.2413 {'pos0_bos_p': 0.000924734165892005, 'pos0_bos_top1': 0, 'last_eos_p': 0.9985358715057373, 'last_eos_top1': 4}
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_082000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:effbfbb0a79df5830618842d59449f38ac90c9439be2043870d67f04c04fe987
3
+ size 515519058
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_155000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1cdcc5b38fdcbe929e9dadf44e17a0be9f2958eb6c15ffb338cc1389fcf14e69
3
+ size 515519058