codekingpro commited on
Commit
64e90e3
·
verified ·
1 Parent(s): 5035838

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/__pycache__/__init__.cpython-311.pyc +0 -0
  2. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/musicgen/__init__.py +28 -0
  3. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/musicgen/processing_musicgen.py +86 -0
  4. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/musicgen_melody/__init__.py +27 -0
  5. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/musicgen_melody/configuration_musicgen_melody.py +163 -0
  6. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/musicgen_melody/feature_extraction_musicgen_melody.py +334 -0
  7. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/musicgen_melody/modeling_musicgen_melody.py +0 -0
  8. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/musicgen_melody/processing_musicgen_melody.py +117 -0
  9. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/mvp/__init__.py +28 -0
  10. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/mvp/configuration_mvp.py +87 -0
  11. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/mvp/modeling_mvp.py +1630 -0
  12. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/myt5/__init__.py +26 -0
  13. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/myt5/tokenization_myt5.py +378 -0
  14. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nanochat/__init__.py +14 -0
  15. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nanochat/configuration_nanochat.py +81 -0
  16. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nanochat/modeling_nanochat.py +518 -0
  17. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nanochat/modular_nanochat.py +235 -0
  18. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nemotron/__init__.py +27 -0
  19. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nemotron/configuration_nemotron.py +73 -0
  20. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nemotron/modeling_nemotron.py +731 -0
  21. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nemotron_h/__init__.py +27 -0
  22. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nemotron_h/configuration_nemotron_h.py +271 -0
  23. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nemotron_h/modeling_nemotron_h.py +1231 -0
  24. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nemotron_h/modular_nemotron_h.py +531 -0
  25. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nllb/__init__.py +26 -0
  26. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nllb/tokenization_nllb.py +318 -0
  27. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nllb_moe/__init__.py +27 -0
  28. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nllb_moe/configuration_nllb_moe.py +122 -0
  29. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nllb_moe/modeling_nllb_moe.py +1143 -0
  30. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nomic_bert/__init__.py +28 -0
  31. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nomic_bert/configuration_nomic_bert.py +77 -0
  32. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nomic_bert/modeling_nomic_bert.py +721 -0
  33. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nomic_bert/modular_nomic_bert.py +299 -0
  34. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nougat/__init__.py +29 -0
  35. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nougat/configuration_nougat.py +87 -0
  36. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nougat/image_processing_nougat.py +304 -0
  37. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nougat/image_processing_pil_nougat.py +293 -0
  38. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nougat/processing_nougat.py +142 -0
  39. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nougat/tokenization_nougat.py +660 -0
  40. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nystromformer/__init__.py +27 -0
  41. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nystromformer/configuration_nystromformer.py +77 -0
  42. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nystromformer/modeling_nystromformer.py +944 -0
  43. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo/__init__.py +27 -0
  44. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo/configuration_olmo.py +92 -0
  45. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo/modeling_olmo.py +503 -0
  46. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo/modular_olmo.py +195 -0
  47. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo2/__init__.py +27 -0
  48. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo2/configuration_olmo2.py +96 -0
  49. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo2/modeling_olmo2.py +507 -0
  50. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo2/modular_olmo2.py +236 -0
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (15.2 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/musicgen/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_musicgen import *
22
+ from .modeling_musicgen import *
23
+ from .processing_musicgen import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/musicgen/processing_musicgen.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+ Text/audio processor class for MusicGen
16
+ """
17
+
18
+ from typing import Any
19
+
20
+ import numpy as np
21
+
22
+ from ...processing_utils import ProcessorMixin
23
+ from ...utils import auto_docstring, to_numpy
24
+
25
+
26
+ @auto_docstring
27
+ class MusicgenProcessor(ProcessorMixin):
28
+ def __init__(self, feature_extractor, tokenizer):
29
+ super().__init__(feature_extractor, tokenizer)
30
+
31
+ def get_decoder_prompt_ids(self, task=None, language=None, no_timestamps=True):
32
+ return self.tokenizer.get_decoder_prompt_ids(task=task, language=language, no_timestamps=no_timestamps)
33
+
34
+ @auto_docstring
35
+ def __call__(self, *args, **kwargs):
36
+ if len(args) > 0:
37
+ kwargs["audio"] = args[0]
38
+ return super().__call__(*args, **kwargs)
39
+
40
+ def batch_decode(self, *args, **kwargs):
41
+ """
42
+ This method is used to decode either batches of audio outputs from the MusicGen model, or batches of token ids
43
+ from the tokenizer. In the case of decoding token ids, this method forwards all its arguments to T5Tokenizer's
44
+ [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information.
45
+ """
46
+ audio_values = kwargs.pop("audio", None)
47
+ padding_mask = kwargs.pop("padding_mask", None)
48
+
49
+ if len(args) > 0:
50
+ audio_values = args[0]
51
+ args = args[1:]
52
+
53
+ if audio_values is not None:
54
+ return self._decode_audio(audio_values, padding_mask=padding_mask)
55
+ else:
56
+ return self.tokenizer.batch_decode(*args, **kwargs)
57
+
58
+ def _decode_audio(self, audio_values, padding_mask: Any = None) -> list[np.ndarray]:
59
+ """
60
+ This method strips any padding from the audio values to return a list of numpy audio arrays.
61
+ """
62
+ audio_values = to_numpy(audio_values)
63
+ bsz, channels, seq_len = audio_values.shape
64
+
65
+ if padding_mask is None:
66
+ return list(audio_values)
67
+
68
+ padding_mask = to_numpy(padding_mask)
69
+
70
+ # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding**
71
+ # token (so that the generated audio values are **not** treated as padded tokens)
72
+ difference = seq_len - padding_mask.shape[-1]
73
+ padding_value = 1 - self.feature_extractor.padding_value
74
+ padding_mask = np.pad(padding_mask, ((0, 0), (0, difference)), "constant", constant_values=padding_value)
75
+
76
+ audio_values = audio_values.tolist()
77
+ for i in range(bsz):
78
+ sliced_audio = np.asarray(audio_values[i])[
79
+ padding_mask[i][None, :] != self.feature_extractor.padding_value
80
+ ]
81
+ audio_values[i] = sliced_audio.reshape(channels, -1)
82
+
83
+ return audio_values
84
+
85
+
86
+ __all__ = ["MusicgenProcessor"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/musicgen_melody/__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_musicgen_melody import *
22
+ from .modeling_musicgen_melody 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__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/musicgen_melody/configuration_musicgen_melody.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Meta AI 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
+ """Musicgen Melody model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...configuration_utils import PreTrainedConfig
19
+ from ...utils import auto_docstring
20
+ from ..auto.configuration_auto import AutoConfig
21
+
22
+
23
+ @auto_docstring(checkpoint="facebook/musicgen-melody")
24
+ @strict
25
+ class MusicgenMelodyDecoderConfig(PreTrainedConfig):
26
+ r"""
27
+ audio_channels (`int`, *optional*, defaults to 1):
28
+ Number of audio channels used by the model (either mono or stereo). Stereo models generate a separate
29
+ audio stream for the left/right output channels. Mono models generate a single audio stream output.
30
+ """
31
+
32
+ model_type = "musicgen_melody_decoder"
33
+ base_config_key = "decoder_config"
34
+ keys_to_ignore_at_inference = ["past_key_values"]
35
+
36
+ vocab_size: int = 2048
37
+ max_position_embeddings: int = 2048
38
+ num_hidden_layers: int = 24
39
+ ffn_dim: int = 4096
40
+ num_attention_heads: int = 16
41
+ layerdrop: float | int = 0.0
42
+ use_cache: bool = True
43
+ activation_function: str = "gelu"
44
+ hidden_size: int = 1024
45
+ dropout: float | int = 0.1
46
+ attention_dropout: float | int = 0.0
47
+ activation_dropout: float | int = 0.0
48
+ initializer_factor: float = 0.02
49
+ scale_embedding: bool = False
50
+ num_codebooks: int = 4
51
+ audio_channels: int = 1
52
+ pad_token_id: int | None = 2048
53
+ bos_token_id: int | None = 2048
54
+ eos_token_id: int | list[int] | None = None
55
+ tie_word_embeddings: bool = False
56
+ is_decoder: bool = False
57
+ add_cross_attention: bool = False
58
+
59
+ def validate_architecture(self):
60
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
61
+ if self.audio_channels not in [1, 2]:
62
+ raise ValueError(f"Expected 1 (mono) or 2 (stereo) audio channels, got {self.audio_channels} channels.")
63
+
64
+
65
+ @auto_docstring(checkpoint="facebook/musicgen-melody")
66
+ @strict
67
+ class MusicgenMelodyConfig(PreTrainedConfig):
68
+ r"""
69
+ text_encoder (`Union[dict, `PretrainedConfig`]`):
70
+ An instance of a configuration object that defines the text encoder config.
71
+ audio_encoder (`Union[dict, `PretrainedConfig`]`):
72
+ An instance of a configuration object that defines the audio encoder config.
73
+ decoder (`Union[dict, `PretrainedConfig`]`):
74
+ An instance of a configuration object that defines the decoder config.
75
+ num_chroma (`int`, *optional*, defaults to 12):
76
+ Number of chroma bins to use.
77
+ chroma_length (`int`, *optional*, defaults to 235):
78
+ Maximum chroma duration if audio is used to condition the model. Corresponds to the maximum duration used during training.
79
+
80
+ Example:
81
+
82
+ ```python
83
+ >>> from transformers import (
84
+ ... MusicgenMelodyConfig,
85
+ ... MusicgenMelodyDecoderConfig,
86
+ ... T5Config,
87
+ ... EncodecConfig,
88
+ ... MusicgenMelodyForConditionalGeneration,
89
+ ... )
90
+
91
+ >>> # Initializing text encoder, audio encoder, and decoder model configurations
92
+ >>> text_encoder_config = T5Config()
93
+ >>> audio_encoder_config = EncodecConfig()
94
+ >>> decoder_config = MusicgenMelodyDecoderConfig()
95
+
96
+ >>> configuration = MusicgenMelodyConfig(
97
+ ... text_encoder=text_encoder_config, audio_encoder=audio_encoder_config, decoder=decoder_config
98
+ ... )
99
+
100
+ >>> # Initializing a MusicgenMelodyForConditionalGeneration (with random weights) from the facebook/musicgen-melody style configuration
101
+ >>> model = MusicgenMelodyForConditionalGeneration(configuration)
102
+
103
+ >>> # Accessing the model configuration
104
+ >>> configuration = model.config
105
+ >>> config_text_encoder = model.config.text_encoder
106
+ >>> config_audio_encoder = model.config.audio_encoder
107
+ >>> config_decoder = model.config.decoder
108
+
109
+ >>> # Saving the model, including its configuration
110
+ >>> model.save_pretrained("musicgen_melody-model")
111
+
112
+ >>> # loading model and config from pretrained folder
113
+ >>> musicgen_melody_config = MusicgenMelodyConfig.from_pretrained("musicgen_melody-model")
114
+ >>> model = MusicgenMelodyForConditionalGeneration.from_pretrained("musicgen_melody-model", config=musicgen_melody_config)
115
+ ```"""
116
+
117
+ model_type = "musicgen_melody"
118
+ sub_configs = {
119
+ "text_encoder": AutoConfig,
120
+ "audio_encoder": AutoConfig,
121
+ "decoder": MusicgenMelodyDecoderConfig,
122
+ }
123
+ has_no_defaults_at_init = True
124
+
125
+ text_encoder: dict | PreTrainedConfig = None
126
+ audio_encoder: dict | PreTrainedConfig = None
127
+ decoder: dict | PreTrainedConfig = None
128
+ num_chroma: int = 12
129
+ chroma_length: int = 235
130
+ initializer_factor: float = 0.02
131
+
132
+ def __post_init__(self, **kwargs):
133
+ if isinstance(self.text_encoder, dict):
134
+ text_encoder_model_type = self.text_encoder.pop("model_type")
135
+ self.text_encoder = AutoConfig.for_model(text_encoder_model_type, **self.text_encoder)
136
+ elif self.text_encoder is None:
137
+ raise ValueError(
138
+ f"A configuration of type {self.model_type} cannot be instantiated because text_encoder is not passed"
139
+ )
140
+
141
+ if isinstance(self.audio_encoder, dict):
142
+ audio_encoder_model_type = self.audio_encoder.pop("model_type")
143
+ self.audio_encoder = AutoConfig.for_model(audio_encoder_model_type, **self.audio_encoder)
144
+ elif self.audio_encoder is None:
145
+ raise ValueError(
146
+ f"A configuration of type {self.model_type} cannot be instantiated because audio_encoder is not passed"
147
+ )
148
+
149
+ if isinstance(self.decoder, dict):
150
+ self.decoder = MusicgenMelodyDecoderConfig(**self.decoder)
151
+ elif self.decoder is None:
152
+ self.decoder = MusicgenMelodyDecoderConfig()
153
+
154
+ self.is_encoder_decoder = True
155
+ super().__post_init__(**kwargs)
156
+
157
+ @property
158
+ # This is a property because you might want to change the codec model on the fly
159
+ def sampling_rate(self):
160
+ return self.audio_encoder.sampling_rate
161
+
162
+
163
+ __all__ = ["MusicgenMelodyConfig", "MusicgenMelodyDecoderConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/musicgen_melody/feature_extraction_musicgen_melody.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Meta AI and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Feature extractor class for Musicgen Melody
16
+ """
17
+
18
+ import copy
19
+ from typing import Any
20
+
21
+ import numpy as np
22
+
23
+ from ...audio_utils import chroma_filter_bank
24
+ from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
25
+ from ...feature_extraction_utils import BatchFeature
26
+ from ...utils import TensorType, is_torch_available, is_torchaudio_available, logging
27
+ from ...utils.import_utils import requires
28
+
29
+
30
+ if is_torch_available():
31
+ import torch
32
+
33
+ if is_torchaudio_available():
34
+ import torchaudio
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ @requires(backends=("torchaudio",))
40
+ class MusicgenMelodyFeatureExtractor(SequenceFeatureExtractor):
41
+ r"""
42
+ Constructs a MusicgenMelody feature extractor.
43
+
44
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
45
+ most of the main methods. Users should refer to this superclass for more information regarding those methods.
46
+
47
+ This class extracts chroma features from audio processed by [Demucs](https://github.com/adefossez/demucs/tree/main) or
48
+ directly from raw audio waveform.
49
+
50
+ Args:
51
+ feature_size (`int`, *optional*, defaults to 12):
52
+ The feature dimension of the extracted features.
53
+ sampling_rate (`int`, *optional*, defaults to 32000):
54
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
55
+ hop_length (`int`, *optional*, defaults to 4096):
56
+ Length of the overlapping windows for the STFT used to obtain the Mel Frequency coefficients.
57
+ chunk_length (`int`, *optional*, defaults to 30):
58
+ The maximum number of chunks of `sampling_rate` samples used to trim and pad longer or shorter audio
59
+ sequences.
60
+ n_fft (`int`, *optional*, defaults to 16384):
61
+ Size of the Fourier transform.
62
+ num_chroma (`int`, *optional*, defaults to 12):
63
+ Number of chroma bins to use.
64
+ padding_value (`float`, *optional*, defaults to 0.0):
65
+ Padding value used to pad the audio.
66
+ return_attention_mask (`bool`, *optional*, defaults to `False`):
67
+ Whether to return the attention mask. Can be overwritten when calling the feature extractor.
68
+
69
+ [What are attention masks?](../glossary#attention-mask)
70
+
71
+ <Tip>
72
+
73
+ For Whisper models, `attention_mask` should always be passed for batched inference, to avoid subtle
74
+ bugs.
75
+
76
+ </Tip>
77
+ stem_indices (`list[int]`, *optional*, defaults to `[3, 2]`):
78
+ Stem channels to extract if demucs outputs are passed.
79
+ """
80
+
81
+ model_input_names = ["input_features"]
82
+
83
+ def __init__(
84
+ self,
85
+ feature_size=12,
86
+ sampling_rate=32000,
87
+ hop_length=4096,
88
+ chunk_length=30,
89
+ n_fft=16384,
90
+ num_chroma=12,
91
+ padding_value=0.0,
92
+ return_attention_mask=False, # pad inputs to max length with silence token (zero) and no attention mask
93
+ stem_indices=[3, 2],
94
+ **kwargs,
95
+ ):
96
+ super().__init__(
97
+ feature_size=feature_size,
98
+ sampling_rate=sampling_rate,
99
+ padding_value=padding_value,
100
+ return_attention_mask=return_attention_mask,
101
+ **kwargs,
102
+ )
103
+ self.n_fft = n_fft
104
+ self.hop_length = hop_length
105
+ self.chunk_length = chunk_length
106
+ self.n_samples = chunk_length * sampling_rate
107
+ self.sampling_rate = sampling_rate
108
+ self.chroma_filters = torch.from_numpy(
109
+ chroma_filter_bank(sampling_rate=sampling_rate, num_frequency_bins=n_fft, tuning=0, num_chroma=num_chroma)
110
+ ).float()
111
+ self.spectrogram = torchaudio.transforms.Spectrogram(
112
+ n_fft=n_fft, win_length=n_fft, hop_length=hop_length, power=2, center=True, pad=0, normalized=True
113
+ )
114
+ self.stem_indices = stem_indices
115
+
116
+ def _torch_extract_fbank_features(self, waveform: torch.Tensor) -> torch.Tensor:
117
+ """
118
+ Compute the chroma spectrogram of the provided audio using the torchaudio spectrogram implementation and the librosa chroma features.
119
+ """
120
+
121
+ # if wav length is not long enough, pad it
122
+ wav_length = waveform.shape[-1]
123
+ if wav_length < self.n_fft:
124
+ pad = self.n_fft - wav_length
125
+ rest = 0 if pad % 2 == 0 else 1
126
+ waveform = torch.nn.functional.pad(waveform, (pad // 2, pad // 2 + rest), "constant", 0)
127
+
128
+ # squeeze alongside channel dimension
129
+ spec = self.spectrogram(waveform).squeeze(1)
130
+
131
+ # sum along the frequency dimension
132
+ raw_chroma = torch.einsum("cf, ...ft->...ct", self.chroma_filters, spec)
133
+
134
+ # normalise with max value
135
+ norm_chroma = torch.nn.functional.normalize(raw_chroma, p=float("inf"), dim=-2, eps=1e-6)
136
+
137
+ # transpose time and chroma dimension -> (batch, time, chroma)
138
+ norm_chroma = norm_chroma.transpose(1, 2)
139
+
140
+ # replace max value alongside chroma dimension with 1 and replace the rest with 0
141
+ idx = norm_chroma.argmax(-1, keepdim=True)
142
+ norm_chroma[:] = 0
143
+ norm_chroma.scatter_(dim=-1, index=idx, value=1)
144
+
145
+ return norm_chroma
146
+
147
+ def _extract_stem_indices(self, audio, sampling_rate=None):
148
+ """
149
+ Extracts stems from the output of the [Demucs](https://github.com/adefossez/demucs/tree/main) audio separation model,
150
+ then converts to mono-channel and resample to the feature extractor sampling rate.
151
+
152
+ Args:
153
+ audio (`torch.Tensor` of shape `(batch_size, num_stems, channel_size, audio_length)`):
154
+ The output of the Demucs model to be processed.
155
+ sampling_rate (`int`, *optional*):
156
+ Demucs sampling rate. If not specified, defaults to `44000`.
157
+ """
158
+ sampling_rate = 44000 if sampling_rate is None else sampling_rate
159
+
160
+ # extract "vocals" and "others" sources from audio encoder (demucs) output
161
+ # [batch_size, num_stems, channel_size, audio_length]
162
+ wav = audio[:, torch.tensor(self.stem_indices)]
163
+
164
+ # merge extracted stems to single waveform
165
+ wav = wav.sum(1)
166
+
167
+ # convert to mono-channel waveform
168
+ wav = wav.mean(dim=1, keepdim=True)
169
+
170
+ # resample to model sampling rate
171
+ # not equivalent to julius.resample
172
+ if sampling_rate != self.sampling_rate:
173
+ wav = torchaudio.functional.resample(
174
+ wav, sampling_rate, self.sampling_rate, rolloff=0.945, lowpass_filter_width=24
175
+ )
176
+
177
+ # [batch_size, 1, audio_length] -> [batch_size, audio_length]
178
+ wav = wav.squeeze(1)
179
+
180
+ return wav
181
+
182
+ def __call__(
183
+ self,
184
+ audio: np.ndarray | list[float] | list[np.ndarray] | list[list[float]],
185
+ truncation: bool = True,
186
+ pad_to_multiple_of: int | None = None,
187
+ return_tensors: str | TensorType | None = None,
188
+ return_attention_mask: bool | None = None,
189
+ padding: str | None = True,
190
+ max_length: int | None = None,
191
+ sampling_rate: int | None = None,
192
+ **kwargs,
193
+ ) -> BatchFeature:
194
+ """
195
+ Main method to featurize and prepare for the model one or several sequence(s).
196
+
197
+ Args:
198
+ audio (`torch.Tensor`, `np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[torch.Tensor]`, `list[list[float]]`):
199
+ The sequence or batch of sequences to be padded. Each sequence can be a torch tensor, a numpy array, a list of float
200
+ values, a list of numpy arrays, a list of torch tensors, or a list of list of float values.
201
+ If `audio` is the output of Demucs, it has to be a torch tensor of shape `(batch_size, num_stems, channel_size, audio_length)`.
202
+ Otherwise, it must be mono or stereo channel audio.
203
+ truncation (`bool`, *optional*, default to `True`):
204
+ Activates truncation to cut input sequences longer than *max_length* to *max_length*.
205
+ pad_to_multiple_of (`int`, *optional*, defaults to None):
206
+ If set will pad the sequence to a multiple of the provided value.
207
+
208
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
209
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
210
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
211
+ If set, will return tensors instead of list of python integers. Acceptable values are:
212
+
213
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
214
+ - `'np'`: Return Numpy `np.ndarray` objects.
215
+ return_attention_mask (`bool`, *optional*):
216
+ Whether to return the attention mask. If left to the default, will return the attention mask according
217
+ to the specific feature_extractor's default.
218
+
219
+ [What are attention masks?](../glossary#attention-mask)
220
+
221
+ <Tip>
222
+ For Musicgen Melody models, audio `attention_mask` is not necessary.
223
+ </Tip>
224
+
225
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
226
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
227
+ index) among:
228
+
229
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
230
+ sequence if provided).
231
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
232
+ acceptable input length for the model if that argument is not provided.
233
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
234
+ lengths).
235
+ max_length (`int`, *optional*):
236
+ Maximum length of the returned list and optionally padding length (see above).
237
+ sampling_rate (`int`, *optional*):
238
+ The sampling rate at which the `audio` input was sampled. It is strongly recommended to pass
239
+ `sampling_rate` at the forward call to prevent silent errors.
240
+ Note that if `audio` is the output of Demucs, `sampling_rate` must be the sampling rate at which Demucs operates.
241
+ """
242
+
243
+ if sampling_rate is None:
244
+ logger.warning_once(
245
+ f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
246
+ "Failing to do so can result in silent errors that might be hard to debug."
247
+ )
248
+
249
+ if isinstance(audio, torch.Tensor) and len(audio.shape) == 4:
250
+ logger.warning_once(
251
+ "`audio` is a 4-dimensional torch tensor and has thus been recognized as the output of `Demucs`. "
252
+ "If this is not the case, make sure to read Musicgen Melody docstrings and "
253
+ "to correct `audio` to get the right behaviour."
254
+ "Link to the docstrings: https://huggingface.co/docs/transformers/main/en/model_doc/musicgen_melody"
255
+ )
256
+ audio = self._extract_stem_indices(audio, sampling_rate=sampling_rate)
257
+ elif sampling_rate is not None and sampling_rate != self.sampling_rate:
258
+ audio = torchaudio.functional.resample(
259
+ audio, sampling_rate, self.sampling_rate, rolloff=0.945, lowpass_filter_width=24
260
+ )
261
+
262
+ is_batched = isinstance(audio, (np.ndarray, torch.Tensor)) and len(audio.shape) > 1
263
+ is_batched = is_batched or (
264
+ isinstance(audio, (list, tuple)) and (isinstance(audio[0], (torch.Tensor, np.ndarray, tuple, list)))
265
+ )
266
+
267
+ if is_batched and not isinstance(audio[0], torch.Tensor):
268
+ audio = [torch.tensor(speech, dtype=torch.float32).unsqueeze(-1) for speech in audio]
269
+ elif is_batched:
270
+ audio = [speech.unsqueeze(-1) for speech in audio]
271
+ elif not is_batched and not isinstance(audio, torch.Tensor):
272
+ audio = torch.tensor(audio, dtype=torch.float32).unsqueeze(-1)
273
+
274
+ if isinstance(audio[0], torch.Tensor) and audio[0].dtype is torch.float64:
275
+ audio = [speech.to(torch.float32) for speech in audio]
276
+
277
+ # always return batch
278
+ if not is_batched:
279
+ audio = [audio]
280
+
281
+ if len(audio[0].shape) == 3:
282
+ logger.warning_once(
283
+ "`audio` has been detected as a batch of stereo signals. Will be convert to mono signals. "
284
+ "If this is an undesired behaviour, make sure to read Musicgen Melody docstrings and "
285
+ "to correct `audio` to get the right behaviour."
286
+ "Link to the docstrings: https://huggingface.co/docs/transformers/main/en/model_doc/musicgen_melody"
287
+ )
288
+ # convert to mono-channel waveform
289
+ audio = [stereo.mean(dim=0) for stereo in audio]
290
+
291
+ batched_speech = BatchFeature({"input_features": audio})
292
+
293
+ padded_inputs = self.pad(
294
+ batched_speech,
295
+ padding=padding,
296
+ max_length=max_length if max_length else self.n_samples,
297
+ truncation=truncation,
298
+ pad_to_multiple_of=pad_to_multiple_of,
299
+ return_attention_mask=return_attention_mask,
300
+ return_tensors="pt",
301
+ )
302
+
303
+ input_features = self._torch_extract_fbank_features(padded_inputs["input_features"].squeeze(-1))
304
+
305
+ padded_inputs["input_features"] = input_features
306
+
307
+ if return_attention_mask:
308
+ # rescale from raw audio length to spectrogram length
309
+ padded_inputs["attention_mask"] = padded_inputs["attention_mask"][:, :: self.hop_length]
310
+
311
+ if return_tensors is not None:
312
+ padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
313
+
314
+ return padded_inputs
315
+
316
+ def to_dict(self) -> dict[str, Any]:
317
+ """
318
+ Serializes this instance to a Python dictionary. Returns:
319
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
320
+ """
321
+ output = copy.deepcopy(self.__dict__)
322
+ output["feature_extractor_type"] = self.__class__.__name__
323
+ if "mel_filters" in output:
324
+ del output["mel_filters"]
325
+ if "window" in output:
326
+ del output["window"]
327
+ if "chroma_filters" in output:
328
+ del output["chroma_filters"]
329
+ if "spectrogram" in output:
330
+ del output["spectrogram"]
331
+ return output
332
+
333
+
334
+ __all__ = ["MusicgenMelodyFeatureExtractor"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/musicgen_melody/modeling_musicgen_melody.py ADDED
The diff for this file is too large to render. See raw diff
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/musicgen_melody/processing_musicgen_melody.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Meta AI and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Text/audio processor class for MusicGen Melody
16
+ """
17
+
18
+ from typing import Any
19
+
20
+ import numpy as np
21
+
22
+ from ...processing_utils import ProcessorMixin
23
+ from ...utils import auto_docstring, to_numpy
24
+ from ...utils.import_utils import requires
25
+
26
+
27
+ @requires(backends=("torchaudio",))
28
+ @auto_docstring
29
+ class MusicgenMelodyProcessor(ProcessorMixin):
30
+ def __init__(self, feature_extractor, tokenizer):
31
+ super().__init__(feature_extractor, tokenizer)
32
+
33
+ # Copied from transformers.models.musicgen.processing_musicgen.MusicgenProcessor.get_decoder_prompt_ids
34
+ def get_decoder_prompt_ids(self, task=None, language=None, no_timestamps=True):
35
+ return self.tokenizer.get_decoder_prompt_ids(task=task, language=language, no_timestamps=no_timestamps)
36
+
37
+ @auto_docstring
38
+ def __call__(self, *args, **kwargs):
39
+ if len(args) > 0:
40
+ kwargs["audio"] = args[0]
41
+ return super().__call__(*args, **kwargs)
42
+
43
+ # Copied from transformers.models.musicgen.processing_musicgen.MusicgenProcessor.batch_decode with padding_mask->attention_mask
44
+ def batch_decode(self, *args, **kwargs):
45
+ """
46
+ This method is used to decode either batches of audio outputs from the MusicGen model, or batches of token ids
47
+ from the tokenizer. In the case of decoding token ids, this method forwards all its arguments to T5Tokenizer's
48
+ [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information.
49
+ """
50
+ audio_values = kwargs.pop("audio", None)
51
+ attention_mask = kwargs.pop("attention_mask", None)
52
+
53
+ if len(args) > 0:
54
+ audio_values = args[0]
55
+ args = args[1:]
56
+
57
+ if audio_values is not None:
58
+ return self._decode_audio(audio_values, attention_mask=attention_mask)
59
+ else:
60
+ return self.tokenizer.batch_decode(*args, **kwargs)
61
+
62
+ # Copied from transformers.models.musicgen.processing_musicgen.MusicgenProcessor._decode_audio with padding_mask->attention_mask
63
+ def _decode_audio(self, audio_values, attention_mask: Any = None) -> list[np.ndarray]:
64
+ """
65
+ This method strips any padding from the audio values to return a list of numpy audio arrays.
66
+ """
67
+ audio_values = to_numpy(audio_values)
68
+ bsz, channels, seq_len = audio_values.shape
69
+
70
+ if attention_mask is None:
71
+ return list(audio_values)
72
+
73
+ attention_mask = to_numpy(attention_mask)
74
+
75
+ # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding**
76
+ # token (so that the generated audio values are **not** treated as padded tokens)
77
+ difference = seq_len - attention_mask.shape[-1]
78
+ padding_value = 1 - self.feature_extractor.padding_value
79
+ attention_mask = np.pad(attention_mask, ((0, 0), (0, difference)), "constant", constant_values=padding_value)
80
+
81
+ audio_values = audio_values.tolist()
82
+ for i in range(bsz):
83
+ sliced_audio = np.asarray(audio_values[i])[
84
+ attention_mask[i][None, :] != self.feature_extractor.padding_value
85
+ ]
86
+ audio_values[i] = sliced_audio.reshape(channels, -1)
87
+
88
+ return audio_values
89
+
90
+ def get_unconditional_inputs(self, num_samples=1, return_tensors="pt"):
91
+ """
92
+ Helper function to get null inputs for unconditional generation, enabling the model to be used without the
93
+ feature extractor or tokenizer.
94
+
95
+ Args:
96
+ num_samples (int, *optional*):
97
+ Number of audio samples to unconditionally generate.
98
+
99
+ Example:
100
+ ```python
101
+ >>> from transformers import MusicgenMelodyForConditionalGeneration, MusicgenMelodyProcessor
102
+
103
+ >>> model = MusicgenMelodyForConditionalGeneration.from_pretrained("facebook/musicgen-melody")
104
+
105
+ >>> # get the unconditional (or 'null') inputs for the model
106
+ >>> processor = MusicgenMelodyProcessor.from_pretrained("facebook/musicgen-melody")
107
+ >>> unconditional_inputs = processor.get_unconditional_inputs(num_samples=1)
108
+
109
+ >>> audio_samples = model.generate(**unconditional_inputs, max_new_tokens=256)
110
+ ```"""
111
+ inputs = self.tokenizer([""] * num_samples, return_tensors=return_tensors, return_attention_mask=True)
112
+ inputs["attention_mask"][:] = 0
113
+
114
+ return inputs
115
+
116
+
117
+ __all__ = ["MusicgenMelodyProcessor"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/mvp/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from ..roberta.tokenization_roberta import RobertaTokenizer as MvpTokenizer
22
+ from .configuration_mvp import *
23
+ from .modeling_mvp import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/mvp/configuration_mvp.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """MVP model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...configuration_utils import PreTrainedConfig
19
+ from ...utils import auto_docstring
20
+
21
+
22
+ @auto_docstring(checkpoint="RUCAIBox/mvp")
23
+ @strict
24
+ class MvpConfig(PreTrainedConfig):
25
+ r"""
26
+ use_prompt (`bool`, *optional*, defaults to `False`):
27
+ Whether or not to use prompt.
28
+ prompt_length (`int`, *optional*, defaults to 100):
29
+ The length of prompt.
30
+ prompt_mid_dim (`int`, *optional*, defaults to 800):
31
+ Dimensionality of the "intermediate" layer in prompt.
32
+
33
+ Example:
34
+
35
+ ```python
36
+ >>> from transformers import MvpConfig, MvpModel
37
+
38
+ >>> # Initializing a MVP RUCAIBox/mvp style configuration
39
+ >>> configuration = MvpConfig()
40
+
41
+ >>> # Initializing a model (with random weights) from the RUCAIBox/mvp style configuration
42
+ >>> model = MvpModel(configuration)
43
+
44
+ >>> # Accessing the model configuration
45
+ >>> configuration = model.config
46
+ ```"""
47
+
48
+ model_type = "mvp"
49
+ keys_to_ignore_at_inference = ["past_key_values"]
50
+ attribute_map = {
51
+ "num_attention_heads": "encoder_attention_heads",
52
+ "hidden_size": "d_model",
53
+ "num_hidden_layers": "encoder_layers",
54
+ }
55
+
56
+ vocab_size: int = 50267
57
+ max_position_embeddings: int = 1024
58
+ encoder_layers: int = 12
59
+ encoder_ffn_dim: int = 4096
60
+ encoder_attention_heads: int = 16
61
+ decoder_layers: int = 12
62
+ decoder_ffn_dim: int = 4096
63
+ decoder_attention_heads: int = 16
64
+ encoder_layerdrop: float | int = 0.0
65
+ decoder_layerdrop: float | int = 0.0
66
+ activation_function: str = "gelu"
67
+ d_model: int = 1024
68
+ dropout: float | int = 0.1
69
+ attention_dropout: float | int = 0.0
70
+ activation_dropout: float | int = 0.0
71
+ init_std: float = 0.02
72
+ classifier_dropout: float | int = 0.0
73
+ scale_embedding: bool = False
74
+ use_cache: bool = True
75
+ pad_token_id: int | None = 1
76
+ bos_token_id: int | None = 0
77
+ eos_token_id: int | list[int] | None = 2
78
+ is_encoder_decoder: bool = True
79
+ decoder_start_token_id: int | None = 2
80
+ use_prompt: bool = False
81
+ prompt_length: int = 100
82
+ prompt_mid_dim: int = 800
83
+ is_decoder: bool = False
84
+ tie_word_embeddings: bool = True
85
+
86
+
87
+ __all__ = ["MvpConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/mvp/modeling_mvp.py ADDED
@@ -0,0 +1,1630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """PyTorch MVP model."""
15
+
16
+ import math
17
+
18
+ import torch
19
+ from torch import nn
20
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
21
+
22
+ from ... import initialization as init
23
+ from ...activations import ACT2FN
24
+ from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
25
+ from ...generation import GenerationMixin
26
+ from ...masking_utils import create_bidirectional_mask, create_causal_mask
27
+ from ...modeling_layers import GradientCheckpointingLayer
28
+ from ...modeling_outputs import (
29
+ BaseModelOutput,
30
+ BaseModelOutputWithPastAndCrossAttentions,
31
+ CausalLMOutputWithCrossAttentions,
32
+ Seq2SeqLMOutput,
33
+ Seq2SeqModelOutput,
34
+ Seq2SeqQuestionAnsweringModelOutput,
35
+ Seq2SeqSequenceClassifierOutput,
36
+ )
37
+ from ...modeling_utils import PreTrainedModel
38
+ from ...utils import auto_docstring, logging, torch_compilable_check
39
+ from .configuration_mvp import MvpConfig
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ # Copied from transformers.models.bart.modeling_bart.shift_tokens_right
46
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
47
+ """
48
+ Shift input ids one token to the right.
49
+ """
50
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
51
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
52
+ shifted_input_ids[:, 0] = decoder_start_token_id
53
+
54
+ if pad_token_id is None:
55
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
56
+ # replace possible -100 values in labels by `pad_token_id`
57
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
58
+
59
+ return shifted_input_ids
60
+
61
+
62
+ # Copied from transformers.models.bart.modeling_bart.BartLearnedPositionalEmbedding with Bart->Mvp
63
+ class MvpLearnedPositionalEmbedding(nn.Embedding):
64
+ """
65
+ This module learns positional embeddings up to a fixed maximum size.
66
+ """
67
+
68
+ def __init__(self, num_embeddings: int, embedding_dim: int):
69
+ # Mvp is set up so that if padding_idx is specified then offset the embedding ids by 2
70
+ # and adjust num_embeddings appropriately. Other models don't have this hack
71
+ self.offset = 2
72
+ super().__init__(num_embeddings + self.offset, embedding_dim)
73
+
74
+ def forward(
75
+ self, input_ids: torch.Tensor, past_key_values_length: int = 0, position_ids: torch.Tensor | None = None
76
+ ):
77
+ """`input_ids' shape is expected to be [bsz x seqlen]."""
78
+
79
+ if position_ids is None:
80
+ bsz, seq_len = input_ids.shape[:2]
81
+ position_ids = torch.arange(
82
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
83
+ ).expand(bsz, -1)
84
+ else:
85
+ position_ids = position_ids.unsqueeze(0)
86
+
87
+ return super().forward(position_ids + self.offset)
88
+
89
+
90
+ class MvpAttention(nn.Module):
91
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
92
+
93
+ def __init__(
94
+ self,
95
+ embed_dim: int,
96
+ num_heads: int,
97
+ dropout: float | None = 0.0,
98
+ is_decoder: bool | None = False,
99
+ bias: bool | None = True,
100
+ layer_idx: bool | None = None,
101
+ ):
102
+ super().__init__()
103
+ self.embed_dim = embed_dim
104
+ self.num_heads = num_heads
105
+ self.dropout = dropout
106
+ self.head_dim = embed_dim // num_heads
107
+
108
+ if (self.head_dim * num_heads) != self.embed_dim:
109
+ raise ValueError(
110
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
111
+ f" and `num_heads`: {num_heads})."
112
+ )
113
+ self.scaling = self.head_dim**-0.5
114
+ self.is_decoder = is_decoder
115
+ self.layer_idx = layer_idx
116
+
117
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
118
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
119
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
120
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
121
+
122
+ def forward(
123
+ self,
124
+ hidden_states: torch.Tensor,
125
+ key_value_states: torch.Tensor | None = None,
126
+ past_key_values: Cache | None = None,
127
+ attention_mask: torch.Tensor | None = None,
128
+ attn_prompt: torch.Tensor | None = None,
129
+ output_attentions: bool = False,
130
+ **kwargs,
131
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
132
+ """Input shape: Batch x Time x Channel"""
133
+
134
+ # if key_value_states are provided this layer is used as a cross-attention layer
135
+ # for the decoder
136
+ is_cross_attention = key_value_states is not None
137
+
138
+ bsz, tgt_len, _ = hidden_states.size()
139
+
140
+ # get query proj
141
+ query_states = self.q_proj(hidden_states) * self.scaling
142
+
143
+ is_updated = False
144
+ if past_key_values is not None:
145
+ if isinstance(past_key_values, EncoderDecoderCache):
146
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
147
+ if is_cross_attention:
148
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
149
+ curr_past_key_values = past_key_values.cross_attention_cache
150
+ else:
151
+ curr_past_key_values = past_key_values.self_attention_cache
152
+ else:
153
+ curr_past_key_values = past_key_values
154
+
155
+ current_states = key_value_states if is_cross_attention else hidden_states
156
+ if is_cross_attention and past_key_values is not None and is_updated:
157
+ # reuse k,v, cross_attentions
158
+ key_states = curr_past_key_values.layers[self.layer_idx].keys
159
+ value_states = curr_past_key_values.layers[self.layer_idx].values
160
+ else:
161
+ key_states = self.k_proj(current_states)
162
+ value_states = self.v_proj(current_states)
163
+ key_states = key_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
164
+ value_states = value_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
165
+
166
+ if past_key_values is not None:
167
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
168
+ key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
169
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
170
+ if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
171
+ past_key_values.is_updated[self.layer_idx] = True
172
+
173
+ if attn_prompt is not None:
174
+ key_states = torch.cat([attn_prompt[0].expand(bsz, -1, -1, -1), key_states], dim=2)
175
+ value_states = torch.cat([attn_prompt[1].expand(bsz, -1, -1, -1), value_states], dim=2)
176
+ if attention_mask is not None:
177
+ prompt_mask = torch.zeros(bsz, 1, tgt_len, attn_prompt[0].size(1)).to(attention_mask.device)
178
+ attention_mask = torch.cat([prompt_mask, attention_mask], dim=(-1))
179
+
180
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
181
+ query_states = query_states.view(bsz, tgt_len, self.num_heads, self.head_dim).transpose(1, 2)
182
+ query_states = query_states.reshape(*proj_shape)
183
+ key_states = key_states.reshape(*proj_shape)
184
+ value_states = value_states.reshape(*proj_shape)
185
+
186
+ src_len = key_states.size(1)
187
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
188
+
189
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
190
+ raise ValueError(
191
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
192
+ f" {attn_weights.size()}"
193
+ )
194
+
195
+ if attention_mask is not None:
196
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
197
+ raise ValueError(
198
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
199
+ )
200
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
201
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
202
+
203
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
204
+
205
+ if output_attentions:
206
+ # this operation is a bit awkward, but it's required to
207
+ # make sure that attn_weights keeps its gradient.
208
+ # In order to do so, attn_weights have to be reshaped
209
+ # twice and have to be reused in the following
210
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
211
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
212
+ else:
213
+ attn_weights_reshaped = None
214
+
215
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
216
+
217
+ attn_output = torch.bmm(attn_probs, value_states)
218
+
219
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
220
+ raise ValueError(
221
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
222
+ f" {attn_output.size()}"
223
+ )
224
+
225
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
226
+ attn_output = attn_output.transpose(1, 2)
227
+
228
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
229
+ # partitioned across GPUs when using tensor-parallelism.
230
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
231
+
232
+ attn_output = self.out_proj(attn_output)
233
+
234
+ return attn_output, attn_weights_reshaped
235
+
236
+
237
+ class MvpEncoderLayer(GradientCheckpointingLayer):
238
+ def __init__(self, config: MvpConfig):
239
+ super().__init__()
240
+ self.embed_dim = config.d_model
241
+ self.self_attn = MvpAttention(
242
+ embed_dim=self.embed_dim,
243
+ num_heads=config.encoder_attention_heads,
244
+ dropout=config.attention_dropout,
245
+ )
246
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
247
+ self.dropout = config.dropout
248
+ self.activation_fn = ACT2FN[config.activation_function]
249
+ self.activation_dropout = config.activation_dropout
250
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
251
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
252
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
253
+
254
+ def forward(
255
+ self,
256
+ hidden_states: torch.FloatTensor,
257
+ attention_mask: torch.FloatTensor,
258
+ self_attn_prompt: torch.FloatTensor,
259
+ output_attentions: bool | None = False,
260
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor | None]:
261
+ """
262
+ Args:
263
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
264
+ attention_mask (`torch.FloatTensor`): attention mask of size
265
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
266
+ self_attn_prompt (`torch.FloatTensor`): prompt of self attention of shape
267
+ `(2, encoder_attention_heads, pro_len, head_dim)`.
268
+ output_attentions (`bool`, *optional*):
269
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
270
+ returned tensors for more detail.
271
+ """
272
+ residual = hidden_states
273
+ hidden_states, attn_weights = self.self_attn(
274
+ hidden_states=hidden_states,
275
+ attention_mask=attention_mask,
276
+ attn_prompt=self_attn_prompt,
277
+ output_attentions=output_attentions,
278
+ )
279
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
280
+ hidden_states = residual + hidden_states
281
+ hidden_states = self.self_attn_layer_norm(hidden_states)
282
+
283
+ residual = hidden_states
284
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
285
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
286
+ hidden_states = self.fc2(hidden_states)
287
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
288
+ hidden_states = residual + hidden_states
289
+ hidden_states = self.final_layer_norm(hidden_states)
290
+
291
+ if hidden_states.dtype == torch.float16 and not torch.isfinite(hidden_states).all():
292
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
293
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
294
+
295
+ return hidden_states, attn_weights
296
+
297
+
298
+ class MvpDecoderLayer(GradientCheckpointingLayer):
299
+ def __init__(self, config: MvpConfig, layer_idx=None):
300
+ super().__init__()
301
+ self.embed_dim = config.d_model
302
+
303
+ self.self_attn = MvpAttention(
304
+ embed_dim=self.embed_dim,
305
+ num_heads=config.decoder_attention_heads,
306
+ dropout=config.attention_dropout,
307
+ is_decoder=True,
308
+ layer_idx=layer_idx,
309
+ )
310
+ self.dropout = config.dropout
311
+ self.activation_fn = ACT2FN[config.activation_function]
312
+ self.activation_dropout = config.activation_dropout
313
+
314
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
315
+ self.encoder_attn = MvpAttention(
316
+ self.embed_dim,
317
+ config.decoder_attention_heads,
318
+ dropout=config.attention_dropout,
319
+ is_decoder=True,
320
+ layer_idx=layer_idx,
321
+ )
322
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
323
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
324
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
325
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
326
+
327
+ def forward(
328
+ self,
329
+ hidden_states: torch.Tensor,
330
+ attention_mask: torch.Tensor | None = None,
331
+ encoder_hidden_states: torch.Tensor | None = None,
332
+ encoder_attention_mask: torch.Tensor | None = None,
333
+ self_attn_prompt: torch.Tensor | None = None,
334
+ cross_attn_prompt: torch.Tensor | None = None,
335
+ past_key_values: Cache | None = None,
336
+ output_attentions: bool | None = False,
337
+ use_cache: bool | None = True,
338
+ **kwargs,
339
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
340
+ """
341
+ Args:
342
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
343
+ attention_mask (`torch.FloatTensor`): attention mask of size
344
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
345
+ encoder_hidden_states (`torch.FloatTensor`):
346
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
347
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
348
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
349
+ self_attn_prompt (`torch.FloatTensor`): prompt of self attention of shape
350
+ `(2, decoder_attention_heads, pro_len, head_dim)`.
351
+ cross_attn_prompt (`torch.FloatTensor`): prompt of cross attention of shape
352
+ `(2, decoder_attention_heads, pro_len, head_dim)`.
353
+ past_key_values (`Cache`): cached past key and value projection states
354
+ output_attentions (`bool`, *optional*):
355
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
356
+ returned tensors for more detail.
357
+ """
358
+ residual = hidden_states
359
+
360
+ # Self Attention
361
+ hidden_states, self_attn_weights = self.self_attn(
362
+ hidden_states=hidden_states,
363
+ past_key_values=past_key_values,
364
+ attention_mask=attention_mask,
365
+ attn_prompt=self_attn_prompt,
366
+ output_attentions=output_attentions,
367
+ )
368
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
369
+ hidden_states = residual + hidden_states
370
+ hidden_states = self.self_attn_layer_norm(hidden_states)
371
+
372
+ # Cross-Attention Block
373
+ cross_attn_weights = None
374
+ if encoder_hidden_states is not None:
375
+ residual = hidden_states
376
+
377
+ hidden_states, cross_attn_weights = self.encoder_attn(
378
+ hidden_states=hidden_states,
379
+ key_value_states=encoder_hidden_states,
380
+ attention_mask=encoder_attention_mask,
381
+ attn_prompt=cross_attn_prompt,
382
+ past_key_values=past_key_values,
383
+ output_attentions=output_attentions,
384
+ )
385
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
386
+ hidden_states = residual + hidden_states
387
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
388
+
389
+ # Fully Connected
390
+ residual = hidden_states
391
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
392
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
393
+ hidden_states = self.fc2(hidden_states)
394
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
395
+ hidden_states = residual + hidden_states
396
+ hidden_states = self.final_layer_norm(hidden_states)
397
+
398
+ outputs = (hidden_states,)
399
+
400
+ if output_attentions:
401
+ outputs += (self_attn_weights, cross_attn_weights)
402
+
403
+ return outputs
404
+
405
+
406
+ # Copied from transformers.models.bart.modeling_bart.BartClassificationHead with Bart->MVP
407
+ class MvpClassificationHead(nn.Module):
408
+ """Head for sentence-level classification tasks."""
409
+
410
+ def __init__(
411
+ self,
412
+ input_dim: int,
413
+ inner_dim: int,
414
+ num_classes: int,
415
+ pooler_dropout: float,
416
+ ):
417
+ super().__init__()
418
+ self.dense = nn.Linear(input_dim, inner_dim)
419
+ self.dropout = nn.Dropout(p=pooler_dropout)
420
+ self.out_proj = nn.Linear(inner_dim, num_classes)
421
+
422
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
423
+ hidden_states = self.dropout(hidden_states)
424
+ hidden_states = self.dense(hidden_states)
425
+ hidden_states = torch.tanh(hidden_states)
426
+ hidden_states = self.dropout(hidden_states)
427
+ hidden_states = self.out_proj(hidden_states)
428
+ return hidden_states
429
+
430
+
431
+ class MvpPrompt(nn.Module):
432
+ """Layer-wise prompt for encoder or decoder."""
433
+
434
+ def __init__(self, config, num_layers, num_heads):
435
+ super().__init__()
436
+ self.prompt_length = config.prompt_length
437
+ self.num_layers = num_layers
438
+ self.num_heads = num_heads
439
+ self.head_dim = config.d_model // num_heads
440
+ self.dropout = nn.Dropout(p=config.dropout)
441
+ self.prompt_embedding = nn.Embedding(config.prompt_length, config.d_model)
442
+ self.prompt_trans = nn.Sequential(
443
+ nn.Linear(config.d_model, config.prompt_mid_dim),
444
+ nn.GELU(),
445
+ nn.Linear(config.prompt_mid_dim, num_layers * 2 * config.d_model),
446
+ )
447
+
448
+ def forward(self, prompt_ids: torch.Tensor) -> tuple[torch.Tensor]:
449
+ prompt = self.prompt_trans(self.prompt_embedding(prompt_ids))
450
+ prompt = prompt.view(self.prompt_length, self.num_layers * 2, self.num_heads, self.head_dim)
451
+ prompt = self.dropout(prompt)
452
+ prompt = prompt.permute([1, 2, 0, 3]).split(2)
453
+ return prompt
454
+
455
+
456
+ @auto_docstring
457
+ class MvpPreTrainedModel(PreTrainedModel):
458
+ config: MvpConfig
459
+ base_model_prefix = "model"
460
+ supports_gradient_checkpointing = True
461
+
462
+ def _init_weights(self, module):
463
+ super()._init_weights(module)
464
+ if isinstance(module, MvpForConditionalGeneration):
465
+ init.zeros_(module.final_logits_bias)
466
+
467
+ @property
468
+ def dummy_inputs(self):
469
+ pad_token = self.config.pad_token_id
470
+ input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
471
+ dummy_inputs = {
472
+ "attention_mask": input_ids.ne(pad_token),
473
+ "input_ids": input_ids,
474
+ }
475
+ return dummy_inputs
476
+
477
+
478
+ class MvpEncoder(MvpPreTrainedModel):
479
+ """
480
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
481
+ [`MvpEncoderLayer`].
482
+
483
+ Args:
484
+ config: MvpConfig
485
+ embed_tokens (nn.Embedding): output embedding
486
+ use_prompt (bool): whether to use prompt
487
+ """
488
+
489
+ def __init__(self, config: MvpConfig, embed_tokens: nn.Embedding | None = None, use_prompt: bool | None = False):
490
+ super().__init__(config)
491
+
492
+ self.dropout = config.dropout
493
+ self.layerdrop = config.encoder_layerdrop
494
+
495
+ embed_dim = config.d_model
496
+ self.padding_idx = config.pad_token_id
497
+ self.max_source_positions = config.max_position_embeddings
498
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
499
+
500
+ self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
501
+
502
+ self.embed_positions = MvpLearnedPositionalEmbedding(
503
+ config.max_position_embeddings,
504
+ embed_dim,
505
+ )
506
+ self.layers = nn.ModuleList([MvpEncoderLayer(config) for _ in range(config.encoder_layers)])
507
+ self.layernorm_embedding = nn.LayerNorm(embed_dim)
508
+
509
+ self.use_prompt = use_prompt
510
+ if use_prompt:
511
+ self.prompt_length = config.prompt_length
512
+ self.self_attn_prompt = MvpPrompt(
513
+ config,
514
+ config.encoder_layers,
515
+ config.encoder_attention_heads,
516
+ )
517
+
518
+ self.gradient_checkpointing = False
519
+ # Initialize weights and apply final processing
520
+ self.post_init()
521
+
522
+ def forward(
523
+ self,
524
+ input_ids: torch.LongTensor | None = None,
525
+ attention_mask: torch.Tensor | None = None,
526
+ inputs_embeds: torch.FloatTensor | None = None,
527
+ output_attentions: bool | None = None,
528
+ output_hidden_states: bool | None = None,
529
+ return_dict: bool | None = None,
530
+ **kwargs,
531
+ ) -> tuple | BaseModelOutput:
532
+ r"""
533
+ Args:
534
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
535
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
536
+ provide it.
537
+
538
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
539
+ [`PreTrainedTokenizer.__call__`] for details.
540
+
541
+ [What are input IDs?](../glossary#input-ids)
542
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
543
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
544
+
545
+ - 1 for tokens that are **not masked**,
546
+ - 0 for tokens that are **masked**.
547
+
548
+ [What are attention masks?](../glossary#attention-mask)
549
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
550
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
551
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
552
+ than the model's internal embedding lookup matrix.
553
+ output_attentions (`bool`, *optional*):
554
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
555
+ returned tensors for more detail.
556
+ output_hidden_states (`bool`, *optional*):
557
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
558
+ for more detail.
559
+ return_dict (`bool`, *optional*):
560
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
561
+ """
562
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
563
+ output_hidden_states = (
564
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
565
+ )
566
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
567
+
568
+ # retrieve input_ids and inputs_embeds
569
+ if input_ids is not None and inputs_embeds is not None:
570
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
571
+ elif input_ids is not None:
572
+ input = input_ids
573
+ input_shape = input.shape
574
+ input_ids = input_ids.view(-1, input_shape[-1])
575
+ elif inputs_embeds is not None:
576
+ input_shape = inputs_embeds.size()[:-1]
577
+ input = inputs_embeds[:, :, -1]
578
+ else:
579
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
580
+
581
+ if inputs_embeds is None:
582
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
583
+
584
+ embed_pos = self.embed_positions(input)
585
+
586
+ hidden_states = inputs_embeds + embed_pos
587
+ hidden_states = self.layernorm_embedding(hidden_states)
588
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
589
+
590
+ # layer-wise prompt
591
+ if self.use_prompt:
592
+ prompt_ids = torch.arange(self.prompt_length).to(self.device)
593
+ self_attn_prompt = self.self_attn_prompt(prompt_ids)
594
+
595
+ # expand attention_mask
596
+ if attention_mask is not None:
597
+ attention_mask = create_bidirectional_mask(
598
+ config=self.config,
599
+ inputs_embeds=hidden_states,
600
+ attention_mask=attention_mask,
601
+ )
602
+
603
+ encoder_states = () if output_hidden_states else None
604
+ all_attentions = () if output_attentions else None
605
+
606
+ for idx, encoder_layer in enumerate(self.layers):
607
+ if output_hidden_states:
608
+ encoder_states = encoder_states + (hidden_states,)
609
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
610
+ to_drop = False
611
+ if self.training:
612
+ dropout_probability = torch.rand([])
613
+ if dropout_probability < self.layerdrop: # skip the layer
614
+ to_drop = True
615
+
616
+ if to_drop:
617
+ layer_outputs = (None, None)
618
+ else:
619
+ layer_outputs = encoder_layer(
620
+ hidden_states,
621
+ attention_mask,
622
+ self_attn_prompt=(self_attn_prompt[idx] if self.use_prompt else None),
623
+ output_attentions=output_attentions,
624
+ )
625
+
626
+ hidden_states = layer_outputs[0]
627
+
628
+ if output_attentions:
629
+ all_attentions = all_attentions + (layer_outputs[1],)
630
+
631
+ if output_hidden_states:
632
+ encoder_states = encoder_states + (hidden_states,)
633
+
634
+ if not return_dict:
635
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
636
+ return BaseModelOutput(
637
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
638
+ )
639
+
640
+
641
+ class MvpDecoder(MvpPreTrainedModel):
642
+ """
643
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`MvpDecoderLayer`]
644
+
645
+ Args:
646
+ config: MvpConfig
647
+ embed_tokens (nn.Embedding): output embedding
648
+ use_prompt (bool): whether to use prompt
649
+ """
650
+
651
+ def __init__(self, config: MvpConfig, use_prompt: bool | None = False):
652
+ super().__init__(config)
653
+ self.dropout = config.dropout
654
+ self.layerdrop = config.decoder_layerdrop
655
+ self.padding_idx = config.pad_token_id
656
+ self.max_target_positions = config.max_position_embeddings
657
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
658
+
659
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
660
+ self.embed_positions = MvpLearnedPositionalEmbedding(
661
+ config.max_position_embeddings,
662
+ config.d_model,
663
+ )
664
+ self.layers = nn.ModuleList([MvpDecoderLayer(config, layer_idx=i) for i in range(config.decoder_layers)])
665
+ self.layernorm_embedding = nn.LayerNorm(config.d_model)
666
+
667
+ self.use_prompt = use_prompt
668
+ if use_prompt:
669
+ self.prompt_length = config.prompt_length
670
+ self.self_attn_prompt = MvpPrompt(
671
+ config,
672
+ config.decoder_layers,
673
+ config.decoder_attention_heads,
674
+ )
675
+ self.cross_attn_prompt = MvpPrompt(
676
+ config,
677
+ config.decoder_layers,
678
+ config.decoder_attention_heads,
679
+ )
680
+
681
+ self.gradient_checkpointing = False
682
+ # Initialize weights and apply final processing
683
+ self.post_init()
684
+
685
+ def forward(
686
+ self,
687
+ input_ids: torch.LongTensor | None = None,
688
+ attention_mask: torch.Tensor | None = None,
689
+ encoder_hidden_states: torch.FloatTensor | None = None,
690
+ encoder_attention_mask: torch.LongTensor | None = None,
691
+ past_key_values: Cache | None = None,
692
+ inputs_embeds: torch.FloatTensor | None = None,
693
+ use_cache: bool | None = None,
694
+ output_attentions: bool | None = None,
695
+ output_hidden_states: bool | None = None,
696
+ return_dict: bool | None = None,
697
+ **kwargs,
698
+ ) -> tuple | BaseModelOutputWithPastAndCrossAttentions:
699
+ r"""
700
+ Args:
701
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
702
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
703
+ provide it.
704
+
705
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
706
+ [`PreTrainedTokenizer.__call__`] for details.
707
+
708
+ [What are input IDs?](../glossary#input-ids)
709
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
710
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
711
+
712
+ - 1 for tokens that are **not masked**,
713
+ - 0 for tokens that are **masked**.
714
+
715
+ [What are attention masks?](../glossary#attention-mask)
716
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
717
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
718
+ of the decoder.
719
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
720
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
721
+ selected in `[0, 1]`:
722
+
723
+ - 1 for tokens that are **not masked**,
724
+ - 0 for tokens that are **masked**.
725
+
726
+ [What are attention masks?](../glossary#attention-mask)
727
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
728
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
729
+
730
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
731
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
732
+
733
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
734
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
735
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
736
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
737
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
738
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
739
+ than the model's internal embedding lookup matrix.
740
+ output_attentions (`bool`, *optional*):
741
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
742
+ returned tensors for more detail.
743
+ output_hidden_states (`bool`, *optional*):
744
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
745
+ for more detail.
746
+ return_dict (`bool`, *optional*):
747
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
748
+ """
749
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
750
+ output_hidden_states = (
751
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
752
+ )
753
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
754
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
755
+
756
+ # retrieve input_ids and inputs_embeds
757
+ if input_ids is not None and inputs_embeds is not None:
758
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
759
+ elif input_ids is not None:
760
+ input = input_ids
761
+ input_shape = input_ids.shape
762
+ input_ids = input_ids.view(-1, input_shape[-1])
763
+ elif inputs_embeds is not None:
764
+ input_shape = inputs_embeds.size()[:-1]
765
+ input = inputs_embeds[:, :, -1]
766
+ else:
767
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
768
+
769
+ if inputs_embeds is None:
770
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
771
+
772
+ if self.gradient_checkpointing and self.training:
773
+ if use_cache:
774
+ logger.warning_once(
775
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
776
+ )
777
+ use_cache = False
778
+
779
+ if use_cache and past_key_values is None:
780
+ past_key_values = (
781
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
782
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
783
+ else DynamicCache(config=self.config)
784
+ )
785
+
786
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
787
+
788
+ attention_mask = create_causal_mask(
789
+ config=self.config,
790
+ inputs_embeds=inputs_embeds,
791
+ attention_mask=attention_mask,
792
+ past_key_values=past_key_values,
793
+ )
794
+
795
+ # expand encoder attention mask
796
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
797
+ encoder_attention_mask = create_bidirectional_mask(
798
+ config=self.config,
799
+ inputs_embeds=inputs_embeds,
800
+ attention_mask=encoder_attention_mask,
801
+ encoder_hidden_states=encoder_hidden_states,
802
+ )
803
+
804
+ # embed positions
805
+ positions = self.embed_positions(input, past_key_values_length)
806
+
807
+ hidden_states = inputs_embeds + positions
808
+ hidden_states = self.layernorm_embedding(hidden_states)
809
+
810
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
811
+
812
+ # layer-wise prompt
813
+ if self.use_prompt:
814
+ prompt_ids = torch.arange(self.prompt_length).to(self.device)
815
+ self_attn_prompt = self.self_attn_prompt(prompt_ids)
816
+ cross_attn_prompt = self.cross_attn_prompt(prompt_ids)
817
+
818
+ # decoder layers
819
+ all_hidden_states = () if output_hidden_states else None
820
+ all_self_attns = () if output_attentions else None
821
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
822
+
823
+ for idx, decoder_layer in enumerate(self.layers):
824
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
825
+ if output_hidden_states:
826
+ all_hidden_states += (hidden_states,)
827
+ if self.training:
828
+ dropout_probability = torch.rand([])
829
+ if dropout_probability < self.layerdrop:
830
+ continue
831
+
832
+ layer_outputs = decoder_layer(
833
+ hidden_states,
834
+ attention_mask,
835
+ encoder_hidden_states, # as positional argument for gradient checkpointing
836
+ encoder_attention_mask=encoder_attention_mask,
837
+ self_attn_prompt=(self_attn_prompt[idx] if self.use_prompt else None),
838
+ cross_attn_prompt=(cross_attn_prompt[idx] if self.use_prompt else None),
839
+ past_key_values=past_key_values,
840
+ output_attentions=output_attentions,
841
+ use_cache=use_cache,
842
+ )
843
+ hidden_states = layer_outputs[0]
844
+ if output_attentions:
845
+ all_self_attns += (layer_outputs[1],)
846
+
847
+ if encoder_hidden_states is not None:
848
+ all_cross_attentions += (layer_outputs[2],)
849
+
850
+ # add hidden states from the last decoder layer
851
+ if output_hidden_states:
852
+ all_hidden_states += (hidden_states,)
853
+
854
+ if not return_dict:
855
+ return tuple(
856
+ v
857
+ for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns, all_cross_attentions]
858
+ if v is not None
859
+ )
860
+ return BaseModelOutputWithPastAndCrossAttentions(
861
+ last_hidden_state=hidden_states,
862
+ past_key_values=past_key_values,
863
+ hidden_states=all_hidden_states,
864
+ attentions=all_self_attns,
865
+ cross_attentions=all_cross_attentions,
866
+ )
867
+
868
+
869
+ @auto_docstring
870
+ class MvpModel(MvpPreTrainedModel):
871
+ _keys_to_ignore_on_load_unexpected = ["final_logits_bias"]
872
+ _tied_weights_keys = {
873
+ "encoder.embed_tokens.weight": "shared.weight",
874
+ "decoder.embed_tokens.weight": "shared.weight",
875
+ }
876
+
877
+ def __init__(self, config: MvpConfig):
878
+ super().__init__(config)
879
+
880
+ padding_idx, vocab_size = config.pad_token_id, config.vocab_size
881
+ self.use_prompt = config.use_prompt
882
+ self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
883
+
884
+ self.encoder = MvpEncoder(config, config.use_prompt)
885
+ self.decoder = MvpDecoder(config, config.use_prompt)
886
+
887
+ # Initialize weights and apply final processing
888
+ self.post_init()
889
+
890
+ def get_input_embeddings(self):
891
+ return self.shared
892
+
893
+ def set_input_embeddings(self, value):
894
+ self.shared = value
895
+ self.encoder.embed_tokens = self.shared
896
+ self.decoder.embed_tokens = self.shared
897
+
898
+ def set_lightweight_tuning(self):
899
+ assert self.use_prompt, "If you want to use lightweight tuning, make sure that `use_prompt=True`."
900
+
901
+ self.requires_grad_(False)
902
+ self.encoder.self_attn_prompt.requires_grad_(True)
903
+ self.decoder.self_attn_prompt.requires_grad_(True)
904
+ self.decoder.cross_attn_prompt.requires_grad_(True)
905
+
906
+ @auto_docstring
907
+ def forward(
908
+ self,
909
+ input_ids: torch.LongTensor | None = None,
910
+ attention_mask: torch.Tensor | None = None,
911
+ decoder_input_ids: torch.LongTensor | None = None,
912
+ decoder_attention_mask: torch.LongTensor | None = None,
913
+ encoder_outputs: list[torch.FloatTensor] | None = None,
914
+ past_key_values: Cache | None = None,
915
+ inputs_embeds: torch.FloatTensor | None = None,
916
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
917
+ use_cache: bool | None = None,
918
+ output_attentions: bool | None = None,
919
+ output_hidden_states: bool | None = None,
920
+ return_dict: bool | None = None,
921
+ **kwargs,
922
+ ) -> tuple | Seq2SeqModelOutput:
923
+ r"""
924
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
925
+ Indices of decoder input sequence tokens in the vocabulary.
926
+
927
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
928
+ [`PreTrainedTokenizer.__call__`] for details.
929
+
930
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
931
+
932
+ Mvp uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
933
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
934
+
935
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
936
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
937
+ for denoising pre-training following the paper.
938
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
939
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
940
+ be used by default.
941
+
942
+ If you want to change padding behavior, you should read [`modeling_mvp._prepare_decoder_attention_mask`]
943
+ and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
944
+ information on the default strategy.
945
+ """
946
+ # different to other models, Mvp automatically creates decoder_input_ids from
947
+ # input_ids if no decoder_input_ids are provided
948
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
949
+ if input_ids is None:
950
+ raise ValueError(
951
+ "If no `decoder_input_ids` or `decoder_inputs_embeds` are "
952
+ "passed, `input_ids` cannot be `None`. Please pass either "
953
+ "`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
954
+ )
955
+
956
+ decoder_input_ids = shift_tokens_right(
957
+ input_ids, self.config.pad_token_id, self.config.decoder_start_token_id
958
+ )
959
+
960
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
961
+ output_hidden_states = (
962
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
963
+ )
964
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
965
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
966
+
967
+ if encoder_outputs is None:
968
+ encoder_outputs = self.encoder(
969
+ input_ids=input_ids,
970
+ attention_mask=attention_mask,
971
+ inputs_embeds=inputs_embeds,
972
+ output_attentions=output_attentions,
973
+ output_hidden_states=output_hidden_states,
974
+ return_dict=return_dict,
975
+ )
976
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
977
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
978
+ encoder_outputs = BaseModelOutput(
979
+ last_hidden_state=encoder_outputs[0],
980
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
981
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
982
+ )
983
+
984
+ # decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)
985
+ decoder_outputs = self.decoder(
986
+ input_ids=decoder_input_ids,
987
+ attention_mask=decoder_attention_mask,
988
+ encoder_hidden_states=encoder_outputs[0],
989
+ encoder_attention_mask=attention_mask,
990
+ past_key_values=past_key_values,
991
+ inputs_embeds=decoder_inputs_embeds,
992
+ use_cache=use_cache,
993
+ output_attentions=output_attentions,
994
+ output_hidden_states=output_hidden_states,
995
+ return_dict=return_dict,
996
+ )
997
+
998
+ if not return_dict:
999
+ return decoder_outputs + encoder_outputs
1000
+
1001
+ return Seq2SeqModelOutput(
1002
+ last_hidden_state=decoder_outputs.last_hidden_state,
1003
+ past_key_values=decoder_outputs.past_key_values,
1004
+ decoder_hidden_states=decoder_outputs.hidden_states,
1005
+ decoder_attentions=decoder_outputs.attentions,
1006
+ cross_attentions=decoder_outputs.cross_attentions,
1007
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1008
+ encoder_hidden_states=encoder_outputs.hidden_states,
1009
+ encoder_attentions=encoder_outputs.attentions,
1010
+ )
1011
+
1012
+
1013
+ @auto_docstring(
1014
+ custom_intro="""
1015
+ The MVP Model with a language modeling head. Can be used for various text generation tasks.
1016
+ """
1017
+ )
1018
+ class MvpForConditionalGeneration(MvpPreTrainedModel, GenerationMixin):
1019
+ _tied_weights_keys = {
1020
+ "lm_head.weight": "model.shared.weight",
1021
+ }
1022
+
1023
+ def __init__(self, config: MvpConfig):
1024
+ super().__init__(config)
1025
+ self.model = MvpModel(config)
1026
+ self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
1027
+ self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
1028
+
1029
+ # Initialize weights and apply final processing
1030
+ self.post_init()
1031
+
1032
+ def resize_token_embeddings(
1033
+ self, new_num_tokens: int, pad_to_multiple_of: int | None = None, mean_resizing: bool = True
1034
+ ) -> nn.Embedding:
1035
+ new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
1036
+ self._resize_final_logits_bias(new_num_tokens)
1037
+ return new_embeddings
1038
+
1039
+ def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
1040
+ old_num_tokens = self.final_logits_bias.shape[-1]
1041
+ if new_num_tokens <= old_num_tokens:
1042
+ new_bias = self.final_logits_bias[:, :new_num_tokens]
1043
+ else:
1044
+ extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
1045
+ new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
1046
+ self.register_buffer("final_logits_bias", new_bias)
1047
+
1048
+ def set_lightweight_tuning(self):
1049
+ self.model.set_lightweight_tuning()
1050
+ self.lm_head.requires_grad_(False)
1051
+
1052
+ @auto_docstring
1053
+ def forward(
1054
+ self,
1055
+ input_ids: torch.LongTensor | None = None,
1056
+ attention_mask: torch.Tensor | None = None,
1057
+ decoder_input_ids: torch.LongTensor | None = None,
1058
+ decoder_attention_mask: torch.LongTensor | None = None,
1059
+ encoder_outputs: list[torch.FloatTensor] | None = None,
1060
+ past_key_values: Cache | None = None,
1061
+ inputs_embeds: torch.FloatTensor | None = None,
1062
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
1063
+ labels: torch.LongTensor | None = None,
1064
+ use_cache: bool | None = None,
1065
+ output_attentions: bool | None = None,
1066
+ output_hidden_states: bool | None = None,
1067
+ return_dict: bool | None = None,
1068
+ **kwargs,
1069
+ ) -> tuple | Seq2SeqLMOutput:
1070
+ r"""
1071
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1072
+ Indices of decoder input sequence tokens in the vocabulary.
1073
+
1074
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1075
+ [`PreTrainedTokenizer.__call__`] for details.
1076
+
1077
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
1078
+
1079
+ Mvp uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
1080
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
1081
+
1082
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
1083
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
1084
+ for denoising pre-training following the paper.
1085
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1086
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1087
+ be used by default.
1088
+
1089
+ If you want to change padding behavior, you should read [`modeling_mvp._prepare_decoder_attention_mask`]
1090
+ and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
1091
+ information on the default strategy.
1092
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1093
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1094
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1095
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1096
+
1097
+ Example of summarization:
1098
+
1099
+ Fine-tuning a model
1100
+ ```python
1101
+ >>> import torch
1102
+ >>> from transformers import AutoTokenizer, MvpForConditionalGeneration
1103
+
1104
+ >>> tokenizer = AutoTokenizer.from_pretrained("RUCAIBox/mvp")
1105
+ >>> model = MvpForConditionalGeneration.from_pretrained("RUCAIBox/mvp")
1106
+
1107
+ >>> inputs = tokenizer(
1108
+ ... "Summarize: You may want to stick it to your boss and leave your job, but don't do it if these are your reasons.",
1109
+ ... return_tensors="pt",
1110
+ ... )
1111
+ >>> labels = tokenizer("Bad Reasons To Quit Your Job", return_tensors="pt")["input_ids"]
1112
+
1113
+ >>> loss = model(**inputs, labels=labels).loss
1114
+ >>> loss.backward()
1115
+ ```
1116
+
1117
+ Inference after the model fine-tuned
1118
+ ```python
1119
+ >>> with torch.no_grad():
1120
+ ... generated_ids = model.generate(**inputs)
1121
+
1122
+ >>> generated_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
1123
+ ```
1124
+ """
1125
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1126
+
1127
+ if labels is not None:
1128
+ if use_cache:
1129
+ logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
1130
+ use_cache = False
1131
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1132
+ decoder_input_ids = shift_tokens_right(
1133
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1134
+ )
1135
+
1136
+ outputs = self.model(
1137
+ input_ids,
1138
+ attention_mask=attention_mask,
1139
+ decoder_input_ids=decoder_input_ids,
1140
+ encoder_outputs=encoder_outputs,
1141
+ decoder_attention_mask=decoder_attention_mask,
1142
+ past_key_values=past_key_values,
1143
+ inputs_embeds=inputs_embeds,
1144
+ decoder_inputs_embeds=decoder_inputs_embeds,
1145
+ use_cache=use_cache,
1146
+ output_attentions=output_attentions,
1147
+ output_hidden_states=output_hidden_states,
1148
+ return_dict=return_dict,
1149
+ )
1150
+ lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
1151
+
1152
+ masked_lm_loss = None
1153
+ if labels is not None:
1154
+ loss_fct = CrossEntropyLoss()
1155
+ masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
1156
+
1157
+ if not return_dict:
1158
+ output = (lm_logits,) + outputs[1:]
1159
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1160
+
1161
+ return Seq2SeqLMOutput(
1162
+ loss=masked_lm_loss,
1163
+ logits=lm_logits,
1164
+ past_key_values=outputs.past_key_values,
1165
+ decoder_hidden_states=outputs.decoder_hidden_states,
1166
+ decoder_attentions=outputs.decoder_attentions,
1167
+ cross_attentions=outputs.cross_attentions,
1168
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1169
+ encoder_hidden_states=outputs.encoder_hidden_states,
1170
+ encoder_attentions=outputs.encoder_attentions,
1171
+ )
1172
+
1173
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
1174
+ return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
1175
+
1176
+
1177
+ @auto_docstring(
1178
+ custom_intro="""
1179
+ Mvp model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
1180
+ tasks.
1181
+ """
1182
+ )
1183
+ class MvpForSequenceClassification(MvpPreTrainedModel):
1184
+ def __init__(self, config: MvpConfig, **kwargs):
1185
+ super().__init__(config, **kwargs)
1186
+ self.model = MvpModel(config)
1187
+ self.classification_head = MvpClassificationHead(
1188
+ config.d_model,
1189
+ config.d_model,
1190
+ config.num_labels,
1191
+ config.classifier_dropout,
1192
+ )
1193
+
1194
+ # Initialize weights and apply final processing
1195
+ self.post_init()
1196
+
1197
+ def set_lightweight_tuning(self):
1198
+ self.model.set_lightweight_tuning()
1199
+ self.classification_head.requires_grad_(False)
1200
+
1201
+ @auto_docstring
1202
+ def forward(
1203
+ self,
1204
+ input_ids: torch.LongTensor | None = None,
1205
+ attention_mask: torch.Tensor | None = None,
1206
+ decoder_input_ids: torch.LongTensor | None = None,
1207
+ decoder_attention_mask: torch.LongTensor | None = None,
1208
+ encoder_outputs: list[torch.FloatTensor] | None = None,
1209
+ inputs_embeds: torch.FloatTensor | None = None,
1210
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
1211
+ labels: torch.LongTensor | None = None,
1212
+ use_cache: bool | None = None,
1213
+ output_attentions: bool | None = None,
1214
+ output_hidden_states: bool | None = None,
1215
+ return_dict: bool | None = None,
1216
+ **kwargs,
1217
+ ) -> tuple | Seq2SeqSequenceClassifierOutput:
1218
+ r"""
1219
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1220
+ Indices of decoder input sequence tokens in the vocabulary.
1221
+
1222
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1223
+ [`PreTrainedTokenizer.__call__`] for details.
1224
+
1225
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
1226
+
1227
+ Mvp uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
1228
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
1229
+
1230
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
1231
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
1232
+ for denoising pre-training following the paper.
1233
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1234
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1235
+ be used by default.
1236
+
1237
+ If you want to change padding behavior, you should read [`modeling_mvp._prepare_decoder_attention_mask`]
1238
+ and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
1239
+ information on the default strategy.
1240
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1241
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1242
+ config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1243
+
1244
+ Example of single-label classification:
1245
+
1246
+ Fine-tuning a model on `num_labels` classes
1247
+ ```python
1248
+ >>> import torch
1249
+ >>> from transformers import AutoTokenizer, MvpForSequenceClassification
1250
+
1251
+ >>> num_labels = 2 # for example, this is a binary classification task
1252
+ >>> tokenizer = AutoTokenizer.from_pretrained("RUCAIBox/mvp")
1253
+ >>> model = MvpForSequenceClassification.from_pretrained("RUCAIBox/mvp", num_labels=num_labels)
1254
+
1255
+ >>> inputs = tokenizer("Classify: Hello, my dog is cute", return_tensors="pt")
1256
+ >>> labels = torch.tensor(1) # the real label for inputs
1257
+
1258
+ >>> loss = model(**inputs, labels=labels).loss
1259
+ >>> loss.backward()
1260
+ ```
1261
+
1262
+ Inference after the model fine-tuned
1263
+ ```python
1264
+ >>> with torch.no_grad():
1265
+ ... logits = model(**inputs).logits
1266
+
1267
+ >>> predicted_class_id = logits.argmax()
1268
+ ```
1269
+ """
1270
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1271
+ if labels is not None:
1272
+ use_cache = False
1273
+
1274
+ if input_ids is None and inputs_embeds is not None:
1275
+ raise NotImplementedError(
1276
+ f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
1277
+ )
1278
+
1279
+ outputs = self.model(
1280
+ input_ids,
1281
+ attention_mask=attention_mask,
1282
+ decoder_input_ids=decoder_input_ids,
1283
+ decoder_attention_mask=decoder_attention_mask,
1284
+ encoder_outputs=encoder_outputs,
1285
+ inputs_embeds=inputs_embeds,
1286
+ decoder_inputs_embeds=decoder_inputs_embeds,
1287
+ use_cache=use_cache,
1288
+ output_attentions=output_attentions,
1289
+ output_hidden_states=output_hidden_states,
1290
+ return_dict=return_dict,
1291
+ )
1292
+ hidden_states = outputs[0] # last hidden state
1293
+
1294
+ eos_mask = input_ids.eq(self.config.eos_token_id).to(hidden_states.device)
1295
+
1296
+ torch_compilable_check(
1297
+ torch.unique_consecutive(eos_mask.sum(1)).numel() == 1,
1298
+ "All examples must have the same number of <eos> tokens.",
1299
+ )
1300
+ sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[
1301
+ :, -1, :
1302
+ ]
1303
+ logits = self.classification_head(sentence_representation)
1304
+
1305
+ loss = None
1306
+ if labels is not None:
1307
+ if self.config.problem_type is None:
1308
+ if self.config.num_labels == 1:
1309
+ self.config.problem_type = "regression"
1310
+ elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1311
+ self.config.problem_type = "single_label_classification"
1312
+ else:
1313
+ self.config.problem_type = "multi_label_classification"
1314
+
1315
+ if self.config.problem_type == "regression":
1316
+ loss_fct = MSELoss()
1317
+ if self.config.num_labels == 1:
1318
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1319
+ else:
1320
+ loss = loss_fct(logits, labels)
1321
+ elif self.config.problem_type == "single_label_classification":
1322
+ loss_fct = CrossEntropyLoss()
1323
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1324
+ elif self.config.problem_type == "multi_label_classification":
1325
+ loss_fct = BCEWithLogitsLoss()
1326
+ loss = loss_fct(logits, labels)
1327
+ if not return_dict:
1328
+ output = (logits,) + outputs[1:]
1329
+ return ((loss,) + output) if loss is not None else output
1330
+
1331
+ return Seq2SeqSequenceClassifierOutput(
1332
+ loss=loss,
1333
+ logits=logits,
1334
+ past_key_values=outputs.past_key_values,
1335
+ decoder_hidden_states=outputs.decoder_hidden_states,
1336
+ decoder_attentions=outputs.decoder_attentions,
1337
+ cross_attentions=outputs.cross_attentions,
1338
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1339
+ encoder_hidden_states=outputs.encoder_hidden_states,
1340
+ encoder_attentions=outputs.encoder_attentions,
1341
+ )
1342
+
1343
+
1344
+ @auto_docstring
1345
+ class MvpForQuestionAnswering(MvpPreTrainedModel):
1346
+ def __init__(self, config):
1347
+ super().__init__(config)
1348
+
1349
+ config.num_labels = 2
1350
+ self.num_labels = config.num_labels
1351
+
1352
+ self.model = MvpModel(config)
1353
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1354
+
1355
+ # Initialize weights and apply final processing
1356
+ self.post_init()
1357
+
1358
+ def set_lightweight_tuning(self):
1359
+ self.model.set_lightweight_tuning()
1360
+ self.qa_outputs.requires_grad_(False)
1361
+
1362
+ @auto_docstring
1363
+ def forward(
1364
+ self,
1365
+ input_ids: torch.Tensor | None = None,
1366
+ attention_mask: torch.Tensor | None = None,
1367
+ decoder_input_ids: torch.LongTensor | None = None,
1368
+ decoder_attention_mask: torch.LongTensor | None = None,
1369
+ encoder_outputs: list[torch.FloatTensor] | None = None,
1370
+ start_positions: torch.LongTensor | None = None,
1371
+ end_positions: torch.LongTensor | None = None,
1372
+ inputs_embeds: torch.FloatTensor | None = None,
1373
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
1374
+ use_cache: bool | None = None,
1375
+ output_attentions: bool | None = None,
1376
+ output_hidden_states: bool | None = None,
1377
+ return_dict: bool | None = None,
1378
+ **kwargs,
1379
+ ) -> tuple | Seq2SeqQuestionAnsweringModelOutput:
1380
+ r"""
1381
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1382
+ Indices of decoder input sequence tokens in the vocabulary.
1383
+
1384
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1385
+ [`PreTrainedTokenizer.__call__`] for details.
1386
+
1387
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
1388
+
1389
+ Mvp uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
1390
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
1391
+
1392
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
1393
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
1394
+ for denoising pre-training following the paper.
1395
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1396
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1397
+ be used by default.
1398
+
1399
+ If you want to change padding behavior, you should read [`modeling_mvp._prepare_decoder_attention_mask`]
1400
+ and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
1401
+ information on the default strategy.
1402
+
1403
+ Example:
1404
+
1405
+ Fine-tuning a model for extrative question answering, and our model also supports generative question answering
1406
+ using `BartForConditionalGeneration`
1407
+ ```python
1408
+ >>> import torch
1409
+ >>> from transformers import AutoTokenizer, MvpForQuestionAnswering
1410
+
1411
+ >>> tokenizer = AutoTokenizer.from_pretrained("RUCAIBox/mvp")
1412
+ >>> model = MvpForQuestionAnswering.from_pretrained("RUCAIBox/mvp")
1413
+
1414
+ >>> inputs = tokenizer(
1415
+ ... "Answer the following question: Who was Jim Henson? [SEP] Jim Henson was a nice puppet",
1416
+ ... return_tensors="pt",
1417
+ ... )
1418
+ >>> target_start_index = torch.tensor([18])
1419
+ >>> target_end_index = torch.tensor([19])
1420
+
1421
+ >>> loss = model(**inputs, start_positions=target_start_index, end_positions=target_end_index).loss
1422
+ >>> loss.backward()
1423
+ ```
1424
+
1425
+ Inference after the model fine-tuned
1426
+ ```python
1427
+ >>> with torch.no_grad():
1428
+ ... outputs = model(**inputs)
1429
+
1430
+ >>> answer_start_index = outputs.start_logits.argmax()
1431
+ >>> answer_end_index = outputs.end_logits.argmax()
1432
+
1433
+ >>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
1434
+ >>> predict_answer = tokenizer.decode(predict_answer_tokens)
1435
+ ```
1436
+ """
1437
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1438
+ if start_positions is not None and end_positions is not None:
1439
+ use_cache = False
1440
+
1441
+ outputs = self.model(
1442
+ input_ids,
1443
+ attention_mask=attention_mask,
1444
+ decoder_input_ids=decoder_input_ids,
1445
+ decoder_attention_mask=decoder_attention_mask,
1446
+ encoder_outputs=encoder_outputs,
1447
+ inputs_embeds=inputs_embeds,
1448
+ decoder_inputs_embeds=decoder_inputs_embeds,
1449
+ use_cache=use_cache,
1450
+ output_attentions=output_attentions,
1451
+ output_hidden_states=output_hidden_states,
1452
+ return_dict=return_dict,
1453
+ )
1454
+
1455
+ sequence_output = outputs[0]
1456
+
1457
+ logits = self.qa_outputs(sequence_output)
1458
+ start_logits, end_logits = logits.split(1, dim=-1)
1459
+ start_logits = start_logits.squeeze(-1).contiguous()
1460
+ end_logits = end_logits.squeeze(-1).contiguous()
1461
+
1462
+ total_loss = None
1463
+ if start_positions is not None and end_positions is not None:
1464
+ # If we are on multi-GPU, split add a dimension
1465
+ if len(start_positions.size()) > 1:
1466
+ start_positions = start_positions.squeeze(-1)
1467
+ if len(end_positions.size()) > 1:
1468
+ end_positions = end_positions.squeeze(-1)
1469
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1470
+ ignored_index = start_logits.size(1)
1471
+ start_positions = start_positions.clamp(0, ignored_index)
1472
+ end_positions = end_positions.clamp(0, ignored_index)
1473
+
1474
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1475
+ start_loss = loss_fct(start_logits, start_positions)
1476
+ end_loss = loss_fct(end_logits, end_positions)
1477
+ total_loss = (start_loss + end_loss) / 2
1478
+
1479
+ if not return_dict:
1480
+ output = (
1481
+ start_logits,
1482
+ end_logits,
1483
+ ) + outputs[1:]
1484
+ return ((total_loss,) + output) if total_loss is not None else output
1485
+
1486
+ return Seq2SeqQuestionAnsweringModelOutput(
1487
+ loss=total_loss,
1488
+ start_logits=start_logits,
1489
+ end_logits=end_logits,
1490
+ past_key_values=outputs.past_key_values,
1491
+ decoder_hidden_states=outputs.decoder_hidden_states,
1492
+ decoder_attentions=outputs.decoder_attentions,
1493
+ cross_attentions=outputs.cross_attentions,
1494
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1495
+ encoder_hidden_states=outputs.encoder_hidden_states,
1496
+ encoder_attentions=outputs.encoder_attentions,
1497
+ )
1498
+
1499
+
1500
+ # Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->Mvp
1501
+ class MvpDecoderWrapper(MvpPreTrainedModel):
1502
+ """
1503
+ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
1504
+ used in combination with the [`EncoderDecoderModel`] framework.
1505
+ """
1506
+
1507
+ def __init__(self, config):
1508
+ super().__init__(config)
1509
+ self.decoder = MvpDecoder(config)
1510
+ self.post_init()
1511
+
1512
+ def forward(self, *args, **kwargs):
1513
+ return self.decoder(*args, **kwargs)
1514
+
1515
+
1516
+ class MvpForCausalLM(MvpPreTrainedModel, GenerationMixin):
1517
+ _tied_weights_keys = {"lm_head.weight": "model.decoder.embed_tokens.weight"}
1518
+
1519
+ def __init__(self, config):
1520
+ config.is_decoder = True
1521
+ config.is_encoder_decoder = False
1522
+ super().__init__(config)
1523
+ self.model = MvpDecoderWrapper(config)
1524
+
1525
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1526
+
1527
+ # Initialize weights and apply final processing
1528
+ self.post_init()
1529
+
1530
+ def get_input_embeddings(self):
1531
+ return self.model.decoder.embed_tokens
1532
+
1533
+ def set_input_embeddings(self, value):
1534
+ self.model.decoder.embed_tokens = value
1535
+
1536
+ def set_lightweight_tuning(self):
1537
+ self.model.set_lightweight_tuning()
1538
+ self.lm_head.requires_grad_(False)
1539
+
1540
+ @auto_docstring
1541
+ def forward(
1542
+ self,
1543
+ input_ids: torch.LongTensor | None = None,
1544
+ attention_mask: torch.Tensor | None = None,
1545
+ encoder_hidden_states: torch.FloatTensor | None = None,
1546
+ encoder_attention_mask: torch.FloatTensor | None = None,
1547
+ past_key_values: Cache | None = None,
1548
+ inputs_embeds: torch.FloatTensor | None = None,
1549
+ labels: torch.LongTensor | None = None,
1550
+ use_cache: bool | None = None,
1551
+ output_attentions: bool | None = None,
1552
+ output_hidden_states: bool | None = None,
1553
+ return_dict: bool | None = None,
1554
+ logits_to_keep: int | torch.Tensor = 0,
1555
+ **kwargs,
1556
+ ) -> tuple | CausalLMOutputWithCrossAttentions:
1557
+ r"""
1558
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1559
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1560
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1561
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1562
+
1563
+ Example:
1564
+
1565
+ ```python
1566
+ >>> from transformers import AutoTokenizer, MvpForCausalLM
1567
+
1568
+ >>> tokenizer = AutoTokenizer.from_pretrained("RUCAIBox/mvp")
1569
+ >>> model = MvpForCausalLM.from_pretrained("RUCAIBox/mvp")
1570
+
1571
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1572
+ >>> outputs = model(**inputs)
1573
+
1574
+ >>> logits = outputs.logits
1575
+ >>> list(logits.shape)
1576
+ [1, 8, 50267]
1577
+ ```"""
1578
+
1579
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1580
+ output_hidden_states = (
1581
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1582
+ )
1583
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1584
+
1585
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1586
+ outputs = self.model.decoder(
1587
+ input_ids=input_ids,
1588
+ attention_mask=attention_mask,
1589
+ encoder_hidden_states=encoder_hidden_states,
1590
+ encoder_attention_mask=encoder_attention_mask,
1591
+ past_key_values=past_key_values,
1592
+ inputs_embeds=inputs_embeds,
1593
+ use_cache=use_cache,
1594
+ output_attentions=output_attentions,
1595
+ output_hidden_states=output_hidden_states,
1596
+ return_dict=return_dict,
1597
+ )
1598
+
1599
+ hidden_states = outputs[0]
1600
+ # Only compute necessary logits
1601
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1602
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1603
+
1604
+ loss = None
1605
+ if labels is not None:
1606
+ loss_fct = CrossEntropyLoss()
1607
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
1608
+
1609
+ if not return_dict:
1610
+ output = (logits,) + outputs[1:]
1611
+ return (loss,) + output if loss is not None else output
1612
+
1613
+ return CausalLMOutputWithCrossAttentions(
1614
+ loss=loss,
1615
+ logits=logits,
1616
+ past_key_values=outputs.past_key_values,
1617
+ hidden_states=outputs.hidden_states,
1618
+ attentions=outputs.attentions,
1619
+ cross_attentions=outputs.cross_attentions,
1620
+ )
1621
+
1622
+
1623
+ __all__ = [
1624
+ "MvpForCausalLM",
1625
+ "MvpForConditionalGeneration",
1626
+ "MvpForQuestionAnswering",
1627
+ "MvpForSequenceClassification",
1628
+ "MvpModel",
1629
+ "MvpPreTrainedModel",
1630
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/myt5/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .tokenization_myt5 import *
22
+ else:
23
+ import sys
24
+
25
+ _file = globals()["__file__"]
26
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/myt5/tokenization_myt5.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024
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 MyT5."""
15
+
16
+ import json
17
+ import os
18
+ import warnings
19
+ from collections import defaultdict
20
+
21
+ from ...tokenization_python import AddedToken, PreTrainedTokenizer
22
+ from ...utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ VOCAB_FILES_NAMES = {"vocab_file": "byte_maps.json"}
29
+
30
+
31
+ class ByteRewriter:
32
+ """
33
+ Byte rewriter class for MyT5 tokenizer.
34
+ This class is used to rewrite bytes using a hash tree. The hash tree is constructed from a set of rewriting rules.
35
+
36
+ Args:
37
+ rewriting_rules (`str` or `dict[str, str]`):
38
+ A path to a json file containing the rewriting rules or a dictionary containing the rewriting rules.
39
+
40
+ """
41
+
42
+ LEAF = "[LEAF]"
43
+
44
+ def __init__(self, rewriting_rules: str | dict[str, str]):
45
+ if isinstance(rewriting_rules, str):
46
+ with open(rewriting_rules, "r") as f:
47
+ rewriting_rules = json.load(f)
48
+ elif not isinstance(rewriting_rules, dict):
49
+ raise TypeError(
50
+ f"rewriting_rules should be either a path to json file or a dict, got {type(rewriting_rules)}"
51
+ )
52
+
53
+ self.hash_tree = self.construct_hash_tree(rewriting_rules)
54
+ reverse_rewriting_rules = {v: k for k, v in rewriting_rules.items()}
55
+ self.reverse_hash_tree = self.construct_hash_tree(reverse_rewriting_rules)
56
+
57
+ def add_leaf(self, hash_tree: dict[str, dict | list[str]], byte_in_sequence: str, byte_out_sequence: str):
58
+ """
59
+ Add a leaf with the output byte sequence to the hash tree.
60
+ """
61
+ byte_in_list = byte_in_sequence.split(" ")
62
+ byte_out_list = byte_out_sequence.split(" ")
63
+
64
+ tree_pointer = hash_tree
65
+ for b in byte_in_list:
66
+ if b not in tree_pointer:
67
+ tree_pointer[b] = {}
68
+ tree_pointer = tree_pointer[b]
69
+
70
+ tree_pointer[self.LEAF] = byte_out_list
71
+
72
+ def construct_hash_tree(self, rewriting_rules: dict[str, str]) -> dict[str, dict | list[str]]:
73
+ """
74
+ Construct a hash tree for rewritten byte sequences.
75
+ """
76
+ hash_tree = defaultdict(dict)
77
+ for b in (f"{x:02x}" for x in range(256)):
78
+ hash_tree[b][self.LEAF] = [b]
79
+
80
+ for in_sequence, out_sequence in rewriting_rules.items():
81
+ self.add_leaf(hash_tree, in_sequence, out_sequence)
82
+
83
+ return hash_tree
84
+
85
+ def search_hash_tree(self, byte_sequence: list[str]) -> None | list[str]:
86
+ """
87
+ Search the hash tree and return the rewritten byte sequence if found.
88
+ """
89
+ tree_pointer = self.hash_tree
90
+ for b in byte_sequence:
91
+ if b in tree_pointer:
92
+ tree_pointer = tree_pointer[b]
93
+ else:
94
+ return None
95
+
96
+ return tree_pointer[self.LEAF]
97
+
98
+ def rewrite_bytes(self, in_bytes: list[str], reverse=False) -> list[str]:
99
+ """
100
+ Rewrite a sequence of bytes using the hash tree.
101
+
102
+ Args:
103
+ in_bytes (`list[str]`): A list of bytes to be rewritten.
104
+ reverse (`bool`): If True, decoding is performed with the reverse hash tree.
105
+ Returns:
106
+ `list[str]`: The rewritten byte sequence.
107
+ """
108
+ out_bytes = []
109
+ b_start = 0
110
+ b_end = 0
111
+
112
+ while b_start < len(in_bytes):
113
+ tree_pointer = self.hash_tree if not reverse else self.reverse_hash_tree
114
+ for j in range(b_start, len(in_bytes)):
115
+ b = in_bytes[j]
116
+ if b in tree_pointer:
117
+ tree_pointer = tree_pointer[b]
118
+ elif j == b_start:
119
+ cur_leaf = [b]
120
+ b_end = j
121
+ break
122
+ else:
123
+ break
124
+ if self.LEAF in tree_pointer:
125
+ cur_leaf = tree_pointer[self.LEAF]
126
+ b_end = j
127
+ out_bytes.extend(cur_leaf)
128
+ b_start = b_end + 1
129
+
130
+ return out_bytes
131
+
132
+
133
+ class MyT5Tokenizer(PreTrainedTokenizer):
134
+ """
135
+ Construct a MyT5 tokenizer.
136
+
137
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
138
+ this superclass for more information regarding those methods.
139
+
140
+ Args:
141
+ vocab_file (`str`): The file containing the byte rewriting rules.
142
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
143
+ The end of sequence token.
144
+
145
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
146
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
147
+ token instead.
148
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
149
+ The token used for padding, for example when batching sequences of different lengths.
150
+ extra_ids (`int`, *optional*, defaults to 125):
151
+ Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are
152
+ accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are
153
+ indexed from the end of the vocabulary up to beginning ("<extra_id_0>" is the last token in the vocabulary
154
+ like in ByT5 preprocessing see
155
+ [here](https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117)).
156
+ additional_special_tokens (`list[str]`, *optional*):
157
+ Additional special tokens used by the tokenizer.
158
+ """
159
+
160
+ model_input_names = ["input_ids", "attention_mask"]
161
+ vocab_files_names = VOCAB_FILES_NAMES
162
+
163
+ def __init__(
164
+ self,
165
+ vocab_file,
166
+ eos_token="</s>",
167
+ unk_token="<unk>",
168
+ pad_token="<pad>",
169
+ extra_ids=125,
170
+ additional_special_tokens=None,
171
+ **kwargs,
172
+ ) -> None:
173
+ # Add extra_ids to the special token list
174
+ if extra_ids > 0 and additional_special_tokens is None:
175
+ additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
176
+ elif extra_ids > 0 and additional_special_tokens is not None and len(additional_special_tokens) > 0:
177
+ # Check that we have the right number of extra_id special tokens
178
+ extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
179
+ if extra_tokens != extra_ids:
180
+ raise ValueError(
181
+ f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
182
+ " provided to MyT5Tokenizer. In this case the additional_special_tokens must include the"
183
+ " extra_ids tokens"
184
+ )
185
+
186
+ pad_token = AddedToken(pad_token, lstrip=True, rstrip=True) if isinstance(pad_token, str) else pad_token
187
+ eos_token = AddedToken(eos_token, lstrip=True, rstrip=True) if isinstance(eos_token, str) else eos_token
188
+ unk_token = AddedToken(unk_token, lstrip=True, rstrip=True) if isinstance(unk_token, str) else unk_token
189
+ # unk token needs to be in the vocab with correct index
190
+ self._added_tokens_decoder = {0: pad_token, 1: eos_token, 2: unk_token}
191
+ self.offset = len(self._added_tokens_decoder)
192
+ self._utf_vocab_size = 2**8 # utf is 8 bits
193
+
194
+ # Load byte maps
195
+ self.byte_maps = json.load(open(vocab_file, "r"))
196
+
197
+ self.decompose_rewriter = ByteRewriter(self.byte_maps["decompose_map"])
198
+ self.merge_rewriter = ByteRewriter(self.byte_maps["merge_map"])
199
+
200
+ super().__init__(
201
+ eos_token=eos_token,
202
+ unk_token=unk_token,
203
+ pad_token=pad_token,
204
+ extra_ids=0,
205
+ additional_special_tokens=additional_special_tokens,
206
+ **kwargs,
207
+ )
208
+
209
+ @property
210
+ def vocab_size(self):
211
+ return self._utf_vocab_size
212
+
213
+ # Copied from transformers.models.byt5.tokenization_byt5.ByT5Tokenizer.get_vocab
214
+ def get_vocab(self):
215
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.offset)}
216
+ vocab.update(self.added_tokens_encoder)
217
+ return vocab
218
+
219
+ # Copied from transformers.models.byt5.tokenization_byt5.ByT5Tokenizer.get_special_tokens_mask
220
+ def get_special_tokens_mask(
221
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
222
+ ) -> list[int]:
223
+ """
224
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
225
+ special tokens using the tokenizer `prepare_for_model` method.
226
+
227
+ Args:
228
+ token_ids_0 (`list[int]`):
229
+ List of IDs.
230
+ token_ids_1 (`list[int]`, *optional*):
231
+ Optional second list of IDs for sequence pairs.
232
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
233
+ Whether or not the token list is already formatted with special tokens for the model.
234
+
235
+ Returns:
236
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
237
+ """
238
+ if already_has_special_tokens:
239
+ return super().get_special_tokens_mask(
240
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
241
+ )
242
+
243
+ # normal case: some special tokens
244
+ if token_ids_1 is None:
245
+ return ([0] * len(token_ids_0)) + [1]
246
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
247
+
248
+ def _add_eos_if_not_present(self, token_ids: list[int]) -> list[int]:
249
+ """Do not add eos again if user already added it."""
250
+ if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
251
+ warnings.warn(
252
+ f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
253
+ " eos tokens being added."
254
+ )
255
+ return token_ids
256
+ else:
257
+ return token_ids + [self.eos_token_id]
258
+
259
+ def create_token_type_ids_from_sequences(
260
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
261
+ ) -> list[int]:
262
+ """
263
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. MyT5 does not
264
+ make use of token type ids, therefore a list of zeros is returned.
265
+
266
+ Args:
267
+ token_ids_0 (`list[int]`):
268
+ List of IDs.
269
+ token_ids_1 (`list[int]`, *optional*):
270
+ Optional second list of IDs for sequence pairs.
271
+
272
+ Returns:
273
+ `list[int]`: List of zeros.
274
+ """
275
+ eos = [self.eos_token_id]
276
+
277
+ if token_ids_1 is None:
278
+ return len(token_ids_0 + eos) * [0]
279
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
280
+
281
+ # Copied from transformers.models.byt5.tokenization_byt5.ByT5Tokenizer.build_inputs_with_special_tokens
282
+ def build_inputs_with_special_tokens(
283
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
284
+ ) -> list[int]:
285
+ """
286
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
287
+ adding special tokens. A sequence has the following format:
288
+
289
+ - single sequence: `X </s>`
290
+ - pair of sequences: `A </s> B </s>`
291
+
292
+ Args:
293
+ token_ids_0 (`list[int]`):
294
+ List of IDs to which the special tokens will be added.
295
+ token_ids_1 (`list[int]`, *optional*):
296
+ Optional second list of IDs for sequence pairs.
297
+
298
+ Returns:
299
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
300
+ """
301
+ token_ids_0 = self._add_eos_if_not_present(token_ids_0)
302
+ if token_ids_1 is None:
303
+ return token_ids_0
304
+ else:
305
+ token_ids_1 = self._add_eos_if_not_present(token_ids_1)
306
+ return token_ids_0 + token_ids_1
307
+
308
+ def _tokenize(self, text: str, **kwargs) -> list[str]:
309
+ """Take as input a string and return a list of strings (tokens) for words/sub-words.
310
+ Represents tokens in two character hex format"""
311
+
312
+ tokens = [f"{i:02x}" for i in text.encode("utf-8")]
313
+ tokens = self.morphological_encode(tokens)
314
+ return tokens
315
+
316
+ def _convert_token_to_id(self, token):
317
+ """Converts a token (str) in an id using the vocab."""
318
+
319
+ if len(token) != 2:
320
+ token_id = None
321
+ else:
322
+ token_id = int(token, 16) + self.offset
323
+
324
+ return token_id
325
+
326
+ def _convert_id_to_token(self, index):
327
+ """Converts an index (integer) in a token (str) using the vocab."""
328
+ token = f"{index - self.offset:02x}"
329
+ return token
330
+
331
+ def morphological_encode(self, indices: list[str]) -> list[str]:
332
+ # Decompose and merge morphological sequences
333
+ indices = self.decompose_rewriter.rewrite_bytes(indices, reverse=False)
334
+ indices = self.merge_rewriter.rewrite_bytes(indices, reverse=False)
335
+ return indices
336
+
337
+ def morphological_decode(self, indices: list[str]) -> list[str]:
338
+ # Demerge and compose morphological sequences
339
+ indices = self.merge_rewriter.rewrite_bytes(indices, reverse=True)
340
+ indices = self.decompose_rewriter.rewrite_bytes(indices, reverse=True)
341
+ return indices
342
+
343
+ def convert_tokens_to_string(self, tokens):
344
+ """Converts a sequence of tokens (string) in a single string."""
345
+ bstring = b""
346
+
347
+ out_tokens = []
348
+ for token in tokens:
349
+ if token in self.added_tokens_decoder:
350
+ out_tokens.append(self.added_tokens_decoder[token])
351
+ elif token in self.added_tokens_encoder:
352
+ out_tokens.append(token)
353
+ else:
354
+ out_tokens.append(token)
355
+
356
+ out_tokens = self.morphological_decode(out_tokens)
357
+ _added_tokens = set(self.added_tokens_decoder.values()) | set(self.added_tokens_encoder)
358
+ for token in out_tokens:
359
+ if token in _added_tokens:
360
+ bstring += bytes(token, "utf-8")
361
+ else:
362
+ bstring += bytes.fromhex(token)
363
+ string = bstring.decode("utf-8", errors="ignore")
364
+ return string
365
+
366
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
367
+ if os.path.isdir(save_directory):
368
+ vocab_file = os.path.join(
369
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
370
+ )
371
+ else:
372
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
373
+ with open(vocab_file, "w", encoding="utf-8") as writer:
374
+ writer.write(json.dumps(self.byte_maps, indent=2, ensure_ascii=False))
375
+ return (vocab_file,)
376
+
377
+
378
+ __all__ = ["MyT5Tokenizer"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nanochat/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING
2
+
3
+ from ...utils import _LazyModule
4
+ from ...utils.import_utils import define_import_structure
5
+
6
+
7
+ if TYPE_CHECKING:
8
+ from .configuration_nanochat import *
9
+ from .modeling_nanochat import *
10
+ else:
11
+ import sys
12
+
13
+ _file = globals()["__file__"]
14
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nanochat/configuration_nanochat.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...configuration_utils import PreTrainedConfig
19
+ from ...modeling_rope_utils import RopeParameters
20
+ from ...utils import auto_docstring
21
+
22
+
23
+ @auto_docstring(checkpoint="karpathy/nanochat-d32")
24
+ @strict
25
+ class NanoChatConfig(PreTrainedConfig):
26
+ r"""
27
+ Example:
28
+
29
+ ```python
30
+ >>> from transformers import NanoChatModel, NanoChatConfig
31
+
32
+ >>> # Initializing a NanoChat style configuration
33
+ >>> configuration = NanoChatConfig()
34
+
35
+ >>> # Initializing a model from the NanoChat style configuration
36
+ >>> model = NanoChatModel(configuration)
37
+
38
+ >>> # Accessing the model configuration
39
+ >>> configuration = model.config
40
+ ```"""
41
+
42
+ model_type = "nanochat"
43
+ keys_to_ignore_at_inference = ["past_key_values"]
44
+
45
+ base_model_tp_plan = {
46
+ "layers.*.self_attn.q_proj": "colwise",
47
+ "layers.*.self_attn.k_proj": "colwise",
48
+ "layers.*.self_attn.v_proj": "colwise",
49
+ "layers.*.self_attn.o_proj": "rowwise",
50
+ "layers.*.mlp.fc1": "colwise",
51
+ "layers.*.mlp.fc2": "rowwise",
52
+ }
53
+
54
+ vocab_size: int = 50304
55
+ hidden_size: int = 768
56
+ intermediate_size: int = 8192
57
+ num_hidden_layers: int = 12
58
+ num_attention_heads: int = 6
59
+ num_key_value_heads: int | None = None
60
+ max_position_embeddings: int = 2048
61
+ hidden_act: str = "relu2"
62
+ attention_dropout: float | int = 0.0
63
+ rms_norm_eps: float = 1e-6
64
+ initializer_range: float = 0.02
65
+ rope_parameters: RopeParameters | dict | None = None
66
+ use_cache: bool = True
67
+ final_logit_softcapping: float | None = 15.0
68
+ attention_bias: bool = False
69
+ bos_token_id: int | None = 0
70
+ eos_token_id: int | list[int] | None = 1
71
+ pad_token_id: int | None = 1
72
+ tie_word_embeddings: bool = False
73
+
74
+ def __post_init__(self, **kwargs):
75
+ if self.num_key_value_heads is None:
76
+ self.num_key_value_heads = self.num_attention_heads
77
+
78
+ super().__post_init__(**kwargs)
79
+
80
+
81
+ __all__ = ["NanoChatConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nanochat/modeling_nanochat.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/nanochat/modular_nanochat.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_nanochat.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ import math
22
+ from collections.abc import Callable
23
+ from typing import Optional
24
+
25
+ import torch
26
+ import torch.nn as nn
27
+
28
+ from ... import initialization as init
29
+ from ...activations import ACT2FN
30
+ from ...cache_utils import Cache, DynamicCache
31
+ from ...generation import GenerationMixin
32
+ from ...integrations import use_kernel_func_from_hub, use_kernelized_func
33
+ from ...masking_utils import create_causal_mask
34
+ from ...modeling_layers import GradientCheckpointingLayer
35
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
36
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
37
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
38
+ from ...processing_utils import Unpack
39
+ from ...utils import TransformersKwargs, auto_docstring
40
+ from ...utils.generic import can_return_tuple, maybe_autocast, merge_with_config_defaults
41
+ from ...utils.output_capturing import capture_outputs
42
+ from .configuration_nanochat import NanoChatConfig
43
+
44
+
45
+ class NanoChatRMSNorm(torch.nn.Module):
46
+ def __init__(self, eps: float = 1e-6):
47
+ super().__init__()
48
+ self.eps = eps
49
+
50
+ def _norm(self, x):
51
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
52
+
53
+ def forward(self, x):
54
+ return self._norm(x.float()).type_as(x)
55
+
56
+ def extra_repr(self):
57
+ return f"eps={self.eps}"
58
+
59
+
60
+ class NanoChatRotaryEmbedding(nn.Module):
61
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
62
+
63
+ def __init__(self, config: NanoChatConfig, device=None):
64
+ super().__init__()
65
+ self.max_seq_len_cached = config.max_position_embeddings
66
+ self.original_max_seq_len = config.max_position_embeddings
67
+
68
+ self.config = config
69
+
70
+ self.rope_type = self.config.rope_parameters["rope_type"]
71
+ rope_init_fn: Callable = self.compute_default_rope_parameters
72
+ if self.rope_type != "default":
73
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
74
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
75
+
76
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
77
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
78
+
79
+ @staticmethod
80
+ def compute_default_rope_parameters(
81
+ config: NanoChatConfig | None = None,
82
+ device: Optional["torch.device"] = None,
83
+ seq_len: int | None = None,
84
+ ) -> tuple["torch.Tensor", float]:
85
+ """
86
+ Computes the inverse frequencies according to the original RoPE implementation
87
+ Args:
88
+ config ([`~transformers.PreTrainedConfig`]):
89
+ The model configuration.
90
+ device (`torch.device`):
91
+ The device to use for initialization of the inverse frequencies.
92
+ seq_len (`int`, *optional*):
93
+ The current sequence length. Unused for this type of RoPE.
94
+ Returns:
95
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
96
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
97
+ """
98
+ base = config.rope_parameters["rope_theta"]
99
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
100
+
101
+ attention_factor = 1.0 # Unused in this type of RoPE
102
+
103
+ # Compute the inverse frequencies
104
+ inv_freq = 1.0 / (
105
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
106
+ )
107
+ return inv_freq, attention_factor
108
+
109
+ @torch.no_grad()
110
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
111
+ def forward(self, x, position_ids):
112
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
113
+ position_ids_expanded = position_ids[:, None, :].float()
114
+
115
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
116
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
117
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
118
+ emb = torch.cat((freqs, freqs), dim=-1)
119
+ cos = emb.cos() * self.attention_scaling
120
+ sin = emb.sin() * self.attention_scaling
121
+
122
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
123
+
124
+
125
+ @use_kernel_func_from_hub("rotary_pos_emb")
126
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
127
+ """Applies Rotary Position Embedding to the query and key tensors.
128
+
129
+ Args:
130
+ q (`torch.Tensor`): The query tensor.
131
+ k (`torch.Tensor`): The key tensor.
132
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
133
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
134
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
135
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
136
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
137
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
138
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
139
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
140
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
141
+ Returns:
142
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
143
+ """
144
+ cos = cos.unsqueeze(unsqueeze_dim)
145
+ sin = sin.unsqueeze(unsqueeze_dim)
146
+ q_embed = (q * cos) + (rotate_half(q) * sin)
147
+ k_embed = (k * cos) + (rotate_half(k) * sin)
148
+ return q_embed, k_embed
149
+
150
+
151
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
152
+ """
153
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
154
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
155
+ """
156
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
157
+ if n_rep == 1:
158
+ return hidden_states
159
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
160
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
161
+
162
+
163
+ def eager_attention_forward(
164
+ module: nn.Module,
165
+ query: torch.Tensor,
166
+ key: torch.Tensor,
167
+ value: torch.Tensor,
168
+ attention_mask: torch.Tensor | None,
169
+ scaling: float,
170
+ dropout: float = 0.0,
171
+ **kwargs: Unpack[TransformersKwargs],
172
+ ):
173
+ key_states = repeat_kv(key, module.num_key_value_groups)
174
+ value_states = repeat_kv(value, module.num_key_value_groups)
175
+
176
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
177
+ if attention_mask is not None:
178
+ attn_weights = attn_weights + attention_mask
179
+
180
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
181
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
182
+ attn_output = torch.matmul(attn_weights, value_states)
183
+ attn_output = attn_output.transpose(1, 2).contiguous()
184
+
185
+ return attn_output, attn_weights
186
+
187
+
188
+ def rotate_half(x):
189
+ """Rotates half the hidden dims of the input with flipped signs for NanoChat."""
190
+ x1 = x[..., : x.shape[-1] // 2]
191
+ x2 = x[..., x.shape[-1] // 2 :]
192
+ return torch.cat((x2, -x1), dim=-1)
193
+
194
+
195
+ @use_kernelized_func(apply_rotary_pos_emb)
196
+ class NanoChatAttention(nn.Module):
197
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
198
+
199
+ def __init__(self, config: NanoChatConfig, layer_idx: int):
200
+ super().__init__()
201
+ self.config = config
202
+ self.layer_idx = layer_idx
203
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
204
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
205
+ self.scaling = self.head_dim**-0.5
206
+ self.attention_dropout = config.attention_dropout
207
+ self.is_causal = True
208
+
209
+ self.q_proj = nn.Linear(
210
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
211
+ )
212
+ self.k_proj = nn.Linear(
213
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
214
+ )
215
+ self.v_proj = nn.Linear(
216
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
217
+ )
218
+ self.o_proj = nn.Linear(
219
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
220
+ )
221
+
222
+ self.q_norm = NanoChatRMSNorm(eps=config.rms_norm_eps)
223
+ self.k_norm = NanoChatRMSNorm(eps=config.rms_norm_eps)
224
+
225
+ def forward(
226
+ self,
227
+ hidden_states: torch.Tensor,
228
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
229
+ attention_mask: torch.Tensor | None = None,
230
+ past_key_values: Cache | None = None,
231
+ **kwargs: Unpack[TransformersKwargs],
232
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
233
+ input_shape = hidden_states.shape[:-1]
234
+ hidden_shape = (*input_shape, -1, self.head_dim)
235
+
236
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
237
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
238
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
239
+
240
+ cos, sin = position_embeddings
241
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
242
+
243
+ # RoPE -> Norm (instead of usual Norm -> RoPE)
244
+ query_states = self.q_norm(query_states)
245
+ key_states = self.k_norm(key_states)
246
+
247
+ if past_key_values is not None:
248
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
249
+
250
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
251
+ self.config._attn_implementation, eager_attention_forward
252
+ )
253
+
254
+ attn_output, attn_weights = attention_interface(
255
+ self,
256
+ query_states,
257
+ key_states,
258
+ value_states,
259
+ attention_mask,
260
+ dropout=0.0 if not self.training else self.attention_dropout,
261
+ scaling=self.scaling,
262
+ **kwargs,
263
+ )
264
+
265
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
266
+ attn_output = self.o_proj(attn_output)
267
+ return attn_output, attn_weights
268
+
269
+
270
+ class NanoChatMLP(nn.Module):
271
+ def __init__(self, config):
272
+ super().__init__()
273
+ self.config = config
274
+ self.activation_fn = ACT2FN[config.hidden_act]
275
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
276
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
277
+
278
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
279
+ hidden_states = self.fc1(hidden_states)
280
+ hidden_states = self.activation_fn(hidden_states)
281
+ hidden_states = self.fc2(hidden_states)
282
+ return hidden_states
283
+
284
+
285
+ class NanoChatDecoderLayer(GradientCheckpointingLayer):
286
+ def __init__(self, config: NanoChatConfig, layer_idx: int):
287
+ super().__init__()
288
+ self.hidden_size = config.hidden_size
289
+
290
+ self.self_attn = NanoChatAttention(config=config, layer_idx=layer_idx)
291
+
292
+ self.mlp = NanoChatMLP(config)
293
+
294
+ self.input_layernorm = NanoChatRMSNorm(eps=config.rms_norm_eps)
295
+ self.post_attention_layernorm = NanoChatRMSNorm(eps=config.rms_norm_eps)
296
+
297
+ def forward(
298
+ self,
299
+ hidden_states: torch.Tensor,
300
+ attention_mask: torch.Tensor | None = None,
301
+ position_ids: torch.LongTensor | None = None,
302
+ past_key_values: Cache | None = None,
303
+ use_cache: bool | None = False,
304
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
305
+ **kwargs: Unpack[TransformersKwargs],
306
+ ) -> torch.Tensor:
307
+ residual = hidden_states
308
+ hidden_states = self.input_layernorm(hidden_states)
309
+ # Self Attention
310
+ hidden_states, _ = self.self_attn(
311
+ hidden_states=hidden_states,
312
+ attention_mask=attention_mask,
313
+ position_ids=position_ids,
314
+ past_key_values=past_key_values,
315
+ use_cache=use_cache,
316
+ position_embeddings=position_embeddings,
317
+ **kwargs,
318
+ )
319
+ hidden_states = residual + hidden_states
320
+
321
+ # Fully Connected
322
+ residual = hidden_states
323
+ hidden_states = self.post_attention_layernorm(hidden_states)
324
+ hidden_states = self.mlp(hidden_states)
325
+ hidden_states = residual + hidden_states
326
+ return hidden_states
327
+
328
+
329
+ @auto_docstring
330
+ class NanoChatPreTrainedModel(PreTrainedModel):
331
+ config: NanoChatConfig
332
+ base_model_prefix = "model"
333
+ supports_gradient_checkpointing = True
334
+ _no_split_modules = ["NanoChatDecoderLayer"]
335
+ _skip_keys_device_placement = ["past_key_values"]
336
+ _supports_flash_attn = True
337
+ _supports_sdpa = True
338
+ _supports_flex_attn = True
339
+
340
+ _can_compile_fullgraph = True
341
+ _supports_attention_backend = True
342
+ _can_record_outputs = {
343
+ "hidden_states": NanoChatDecoderLayer,
344
+ "attentions": NanoChatAttention,
345
+ }
346
+
347
+ def _init_weights(self, module: nn.Module) -> None:
348
+ super()._init_weights(module)
349
+ if isinstance(module, NanoChatAttention):
350
+ init.normal_(
351
+ module.o_proj.weight,
352
+ mean=0.0,
353
+ std=self.config.initializer_range / math.sqrt(2 * self.config.num_hidden_layers),
354
+ )
355
+
356
+
357
+ @auto_docstring
358
+ class NanoChatModel(NanoChatPreTrainedModel):
359
+ def __init__(self, config: NanoChatConfig):
360
+ super().__init__(config)
361
+ self.padding_idx = config.pad_token_id
362
+ self.vocab_size = config.vocab_size
363
+
364
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
365
+ self.layers = nn.ModuleList(
366
+ [NanoChatDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
367
+ )
368
+
369
+ self.norm = NanoChatRMSNorm(eps=config.rms_norm_eps)
370
+ self.rotary_emb = NanoChatRotaryEmbedding(config=config)
371
+ self.gradient_checkpointing = False
372
+
373
+ # Initialize weights and apply final processing
374
+ self.post_init()
375
+
376
+ @merge_with_config_defaults
377
+ @capture_outputs
378
+ @auto_docstring
379
+ def forward(
380
+ self,
381
+ input_ids: torch.LongTensor | None = None,
382
+ attention_mask: torch.Tensor | None = None,
383
+ position_ids: torch.LongTensor | None = None,
384
+ past_key_values: Cache | None = None,
385
+ inputs_embeds: torch.FloatTensor | None = None,
386
+ use_cache: bool | None = None,
387
+ **kwargs: Unpack[TransformersKwargs],
388
+ ) -> BaseModelOutputWithPast:
389
+ if (input_ids is None) ^ (inputs_embeds is not None):
390
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
391
+
392
+ if inputs_embeds is None:
393
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
394
+
395
+ if use_cache and past_key_values is None:
396
+ past_key_values = DynamicCache(config=self.config)
397
+
398
+ if position_ids is None:
399
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
400
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
401
+ position_ids = position_ids.unsqueeze(0)
402
+
403
+ causal_mask = create_causal_mask(
404
+ config=self.config,
405
+ inputs_embeds=inputs_embeds,
406
+ attention_mask=attention_mask,
407
+ past_key_values=past_key_values,
408
+ position_ids=position_ids,
409
+ )
410
+
411
+ hidden_states = inputs_embeds
412
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
413
+
414
+ hidden_states = self.norm(hidden_states) # Additional norm before the layers
415
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
416
+ hidden_states = decoder_layer(
417
+ hidden_states,
418
+ attention_mask=causal_mask,
419
+ position_embeddings=position_embeddings,
420
+ position_ids=position_ids,
421
+ past_key_values=past_key_values,
422
+ **kwargs,
423
+ )
424
+
425
+ hidden_states = self.norm(hidden_states)
426
+ return BaseModelOutputWithPast(
427
+ last_hidden_state=hidden_states,
428
+ past_key_values=past_key_values,
429
+ )
430
+
431
+
432
+ @auto_docstring
433
+ class NanoChatForCausalLM(NanoChatPreTrainedModel, GenerationMixin):
434
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
435
+ _tp_plan = {"lm_head": "colwise_gather_output"}
436
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
437
+
438
+ def __init__(self, config):
439
+ super().__init__(config)
440
+ self.model = NanoChatModel(config)
441
+ self.vocab_size = config.vocab_size
442
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
443
+
444
+ # Initialize weights and apply final processing
445
+ self.post_init()
446
+
447
+ @can_return_tuple
448
+ @auto_docstring
449
+ def forward(
450
+ self,
451
+ input_ids: torch.LongTensor | None = None,
452
+ attention_mask: torch.Tensor | None = None,
453
+ position_ids: torch.LongTensor | None = None,
454
+ past_key_values: Cache | None = None,
455
+ inputs_embeds: torch.FloatTensor | None = None,
456
+ labels: torch.LongTensor | None = None,
457
+ use_cache: bool | None = None,
458
+ logits_to_keep: int | torch.Tensor = 0,
459
+ **kwargs: Unpack[TransformersKwargs],
460
+ ) -> CausalLMOutputWithPast:
461
+ r"""
462
+ Example:
463
+
464
+ ```python
465
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
466
+
467
+ >>> model = AutoModelForCausalLM.from_pretrained("karpathy/nanochat-d32")
468
+
469
+ >>> tokenizer = AutoTokenizer.from_pretrained("karpathy/nanochat-d32")
470
+
471
+ >>> conversation = [
472
+ {"role": "user", "content": "What is the capital of France?"},
473
+ ]
474
+
475
+ >>> inputs = tokenizer.apply_chat_template(
476
+ conversation, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
477
+ ).to(device)
478
+
479
+ >>> with torch.no_grad():
480
+ >>> outputs = model.generate(**inputs, max_new_tokens=64, do_sample=False)
481
+
482
+ >>> generated_tokens = outputs[0, inputs["input_ids"].shape[1] :]
483
+ >>> output = tokenizer.decode(generated_tokens, skip_special_tokens=True)
484
+ ```"""
485
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
486
+ outputs: BaseModelOutputWithPast = self.model(
487
+ input_ids=input_ids,
488
+ attention_mask=attention_mask,
489
+ position_ids=position_ids,
490
+ past_key_values=past_key_values,
491
+ inputs_embeds=inputs_embeds,
492
+ use_cache=use_cache,
493
+ **kwargs,
494
+ )
495
+
496
+ hidden_states = outputs.last_hidden_state
497
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
498
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
499
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
500
+ if self.config.final_logit_softcapping is not None:
501
+ logits = logits / self.config.final_logit_softcapping
502
+ logits = torch.tanh(logits)
503
+ logits = logits * self.config.final_logit_softcapping
504
+
505
+ loss = None
506
+ if labels is not None:
507
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
508
+
509
+ return CausalLMOutputWithPast(
510
+ loss=loss,
511
+ logits=logits,
512
+ past_key_values=outputs.past_key_values,
513
+ hidden_states=outputs.hidden_states,
514
+ attentions=outputs.attentions,
515
+ )
516
+
517
+
518
+ __all__ = ["NanoChatPreTrainedModel", "NanoChatModel", "NanoChatForCausalLM"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nanochat/modular_nanochat.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ from collections.abc import Callable
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from ... import initialization as init
22
+ from ...cache_utils import Cache, DynamicCache
23
+ from ...masking_utils import create_causal_mask
24
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
25
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
26
+ from ...processing_utils import Unpack
27
+ from ...utils import TransformersKwargs, auto_docstring
28
+ from ..clip.modeling_clip import CLIPMLP
29
+ from ..gemma2.modeling_gemma2 import Gemma2ForCausalLM
30
+ from ..llama.modeling_llama import (
31
+ LlamaDecoderLayer,
32
+ LlamaModel,
33
+ LlamaPreTrainedModel,
34
+ LlamaRotaryEmbedding,
35
+ apply_rotary_pos_emb,
36
+ eager_attention_forward,
37
+ )
38
+ from ..llama4.modeling_llama4 import Llama4TextL2Norm
39
+ from ..qwen3.modeling_qwen3 import Qwen3Attention
40
+ from .configuration_nanochat import NanoChatConfig
41
+
42
+
43
+ class NanoChatRMSNorm(Llama4TextL2Norm):
44
+ pass
45
+
46
+
47
+ class NanoChatRotaryEmbedding(LlamaRotaryEmbedding):
48
+ pass
49
+
50
+
51
+ def rotate_half(x):
52
+ """Rotates half the hidden dims of the input with flipped signs for NanoChat."""
53
+ x1 = x[..., : x.shape[-1] // 2]
54
+ x2 = x[..., x.shape[-1] // 2 :]
55
+ return torch.cat((x2, -x1), dim=-1)
56
+
57
+
58
+ class NanoChatAttention(Qwen3Attention):
59
+ def __init__(self, config: NanoChatConfig, layer_idx: int):
60
+ super().__init__(config, layer_idx)
61
+ del self.sliding_window
62
+ del self.layer_type
63
+
64
+ self.q_norm = NanoChatRMSNorm(eps=config.rms_norm_eps)
65
+ self.k_norm = NanoChatRMSNorm(eps=config.rms_norm_eps)
66
+
67
+ def forward(
68
+ self,
69
+ hidden_states: torch.Tensor,
70
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
71
+ attention_mask: torch.Tensor | None = None,
72
+ past_key_values: Cache | None = None,
73
+ **kwargs: Unpack[TransformersKwargs],
74
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
75
+ input_shape = hidden_states.shape[:-1]
76
+ hidden_shape = (*input_shape, -1, self.head_dim)
77
+
78
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
79
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
80
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
81
+
82
+ cos, sin = position_embeddings
83
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
84
+
85
+ # RoPE -> Norm (instead of usual Norm -> RoPE)
86
+ query_states = self.q_norm(query_states)
87
+ key_states = self.k_norm(key_states)
88
+
89
+ if past_key_values is not None:
90
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
91
+
92
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
93
+ self.config._attn_implementation, eager_attention_forward
94
+ )
95
+
96
+ attn_output, attn_weights = attention_interface(
97
+ self,
98
+ query_states,
99
+ key_states,
100
+ value_states,
101
+ attention_mask,
102
+ dropout=0.0 if not self.training else self.attention_dropout,
103
+ scaling=self.scaling,
104
+ **kwargs,
105
+ )
106
+
107
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
108
+ attn_output = self.o_proj(attn_output)
109
+ return attn_output, attn_weights
110
+
111
+
112
+ class NanoChatMLP(CLIPMLP):
113
+ def __init__(self, config):
114
+ super().__init__(config)
115
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
116
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
117
+
118
+
119
+ class NanoChatDecoderLayer(LlamaDecoderLayer):
120
+ def __init__(self, config: NanoChatConfig, layer_idx: int):
121
+ super().__init__()
122
+
123
+ self.input_layernorm = NanoChatRMSNorm(eps=config.rms_norm_eps)
124
+ self.post_attention_layernorm = NanoChatRMSNorm(eps=config.rms_norm_eps)
125
+
126
+
127
+ @auto_docstring
128
+ class NanoChatPreTrainedModel(LlamaPreTrainedModel):
129
+ def _init_weights(self, module: nn.Module) -> None:
130
+ PreTrainedModel._init_weights(self, module)
131
+ if isinstance(module, NanoChatAttention):
132
+ init.normal_(
133
+ module.o_proj.weight,
134
+ mean=0.0,
135
+ std=self.config.initializer_range / math.sqrt(2 * self.config.num_hidden_layers),
136
+ )
137
+
138
+
139
+ @auto_docstring
140
+ class NanoChatModel(LlamaModel):
141
+ def __init__(self, config: NanoChatConfig):
142
+ super().__init__(config)
143
+
144
+ self.norm = NanoChatRMSNorm(eps=config.rms_norm_eps)
145
+
146
+ def forward(
147
+ self,
148
+ input_ids: torch.LongTensor | None = None,
149
+ attention_mask: torch.Tensor | None = None,
150
+ position_ids: torch.LongTensor | None = None,
151
+ past_key_values: Cache | None = None,
152
+ inputs_embeds: torch.FloatTensor | None = None,
153
+ use_cache: bool | None = None,
154
+ **kwargs: Unpack[TransformersKwargs],
155
+ ) -> BaseModelOutputWithPast:
156
+ if (input_ids is None) ^ (inputs_embeds is not None):
157
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
158
+
159
+ if inputs_embeds is None:
160
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
161
+
162
+ if use_cache and past_key_values is None:
163
+ past_key_values = DynamicCache(config=self.config)
164
+
165
+ if position_ids is None:
166
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
167
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
168
+ position_ids = position_ids.unsqueeze(0)
169
+
170
+ causal_mask = create_causal_mask(
171
+ config=self.config,
172
+ inputs_embeds=inputs_embeds,
173
+ attention_mask=attention_mask,
174
+ past_key_values=past_key_values,
175
+ position_ids=position_ids,
176
+ )
177
+
178
+ hidden_states = inputs_embeds
179
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
180
+
181
+ hidden_states = self.norm(hidden_states) # Additional norm before the layers
182
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
183
+ hidden_states = decoder_layer(
184
+ hidden_states,
185
+ attention_mask=causal_mask,
186
+ position_embeddings=position_embeddings,
187
+ position_ids=position_ids,
188
+ past_key_values=past_key_values,
189
+ **kwargs,
190
+ )
191
+
192
+ hidden_states = self.norm(hidden_states)
193
+ return BaseModelOutputWithPast(
194
+ last_hidden_state=hidden_states,
195
+ past_key_values=past_key_values,
196
+ )
197
+
198
+
199
+ @auto_docstring
200
+ class NanoChatForCausalLM(Gemma2ForCausalLM):
201
+ _tp_plan = {"lm_head": "colwise_gather_output"}
202
+
203
+ def forward(self, **super_kwargs) -> CausalLMOutputWithPast:
204
+ r"""
205
+ Example:
206
+
207
+ ```python
208
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
209
+
210
+ >>> model = AutoModelForCausalLM.from_pretrained("karpathy/nanochat-d32")
211
+
212
+ >>> tokenizer = AutoTokenizer.from_pretrained("karpathy/nanochat-d32")
213
+
214
+ >>> conversation = [
215
+ {"role": "user", "content": "What is the capital of France?"},
216
+ ]
217
+
218
+ >>> inputs = tokenizer.apply_chat_template(
219
+ conversation, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
220
+ ).to(device)
221
+
222
+ >>> with torch.no_grad():
223
+ >>> outputs = model.generate(**inputs, max_new_tokens=64, do_sample=False)
224
+
225
+ >>> generated_tokens = outputs[0, inputs["input_ids"].shape[1] :]
226
+ >>> output = tokenizer.decode(generated_tokens, skip_special_tokens=True)
227
+ ```"""
228
+ super().forward(**super_kwargs)
229
+
230
+
231
+ __all__ = [
232
+ "NanoChatPreTrainedModel",
233
+ "NanoChatModel",
234
+ "NanoChatForCausalLM",
235
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nemotron/__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_nemotron import *
22
+ from .modeling_nemotron 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__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nemotron/configuration_nemotron.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
2
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Nemotron model configuration"""
16
+
17
+ from huggingface_hub.dataclasses import strict
18
+
19
+ from ...configuration_utils import PreTrainedConfig
20
+ from ...modeling_rope_utils import RopeParameters
21
+ from ...utils import auto_docstring
22
+
23
+
24
+ @auto_docstring(checkpoint="thhaus/nemotron3-8b")
25
+ @strict
26
+ class NemotronConfig(PreTrainedConfig):
27
+ r"""
28
+ Example:
29
+
30
+ ```python
31
+ >>> from transformers import NemotronModel, NemotronConfig
32
+
33
+ >>> # Initializing a Nemotron nemotron-15b style configuration
34
+ >>> configuration = NemotronConfig()
35
+
36
+ >>> # Initializing a model from the nemotron-15b style configuration
37
+ >>> model = NemotronModel(configuration)
38
+
39
+ >>> # Accessing the model configuration
40
+ >>> configuration = model.config
41
+ ```"""
42
+
43
+ model_type = "nemotron"
44
+ keys_to_ignore_at_inference = ["past_key_values"]
45
+
46
+ vocab_size: int = 256000
47
+ hidden_size: int = 6144
48
+ intermediate_size: int = 24576
49
+ num_hidden_layers: int = 32
50
+ num_attention_heads: int = 48
51
+ head_dim: int | None = None
52
+ num_key_value_heads: int | None = None
53
+ hidden_act: str = "relu2"
54
+ max_position_embeddings: int = 4096
55
+ initializer_range: float = 0.0134
56
+ norm_eps: float = 1e-5
57
+ use_cache: bool = True
58
+ pad_token_id: int | None = None
59
+ bos_token_id: int | None = 2
60
+ eos_token_id: int | list[int] | None = 3
61
+ tie_word_embeddings: bool = False
62
+ rope_parameters: RopeParameters | dict | None = None
63
+ attention_bias: bool = False
64
+ attention_dropout: float | int = 0.0
65
+ mlp_bias: bool = False
66
+
67
+ def __post_init__(self, **kwargs):
68
+ self.head_dim = self.head_dim if self.head_dim is not None else self.hidden_size // self.num_attention_heads
69
+ kwargs.setdefault("partial_rotary_factor", 0.5) # assign default for BC
70
+ super().__post_init__(**kwargs)
71
+
72
+
73
+ __all__ = ["NemotronConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nemotron/modeling_nemotron.py ADDED
@@ -0,0 +1,731 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
2
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch Nemotron model."""
16
+
17
+ import math
18
+ from collections.abc import Callable
19
+ from typing import Optional
20
+
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from torch import Size, Tensor, nn
24
+
25
+ from ... import initialization as init
26
+ from ...activations import ACT2FN
27
+ from ...cache_utils import Cache, DynamicCache, StaticCache
28
+ from ...generation import GenerationMixin
29
+ from ...masking_utils import create_causal_mask
30
+ from ...modeling_flash_attention_utils import _flash_attention_forward, flash_attn_supports_top_left_mask
31
+ from ...modeling_layers import (
32
+ GenericForQuestionAnswering,
33
+ GenericForSequenceClassification,
34
+ GenericForTokenClassification,
35
+ GradientCheckpointingLayer,
36
+ )
37
+ from ...modeling_outputs import (
38
+ BaseModelOutputWithPast,
39
+ CausalLMOutputWithPast,
40
+ )
41
+ from ...modeling_rope_utils import (
42
+ ROPE_INIT_FUNCTIONS,
43
+ dynamic_rope_update,
44
+ )
45
+ from ...modeling_utils import PreTrainedModel
46
+ from ...processing_utils import Unpack
47
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
48
+ from ...utils.generic import maybe_autocast, merge_with_config_defaults
49
+ from ...utils.output_capturing import capture_outputs
50
+ from .configuration_nemotron import NemotronConfig
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+
56
+ def _cast_if_autocast_enabled(device_type, *args):
57
+ if not torch.is_autocast_enabled():
58
+ return args
59
+ else:
60
+ target_dtype = torch.get_autocast_dtype(device_type)
61
+ return torch.amp.autocast_mode._cast(args, device_type, target_dtype)
62
+
63
+
64
+ class NemotronLayerNorm1P(nn.LayerNorm):
65
+ def __init__(
66
+ self,
67
+ normalized_shape: int | list[int] | Size,
68
+ eps: float = 1e-5,
69
+ elementwise_affine: bool = True,
70
+ bias: bool = True,
71
+ device=None,
72
+ dtype=None,
73
+ ):
74
+ super().__init__(normalized_shape, eps, elementwise_affine, bias, device, dtype)
75
+
76
+ def forward(self, input: Tensor) -> Tensor:
77
+ device_type = input.device.type if input.device.type != "mps" else "cpu"
78
+ args = _cast_if_autocast_enabled(
79
+ device_type, input, self.normalized_shape, self.weight + 1, self.bias, self.eps
80
+ )
81
+ with maybe_autocast(device_type=input.device.type, enabled=False):
82
+ return F.layer_norm(*args)
83
+
84
+
85
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
86
+ class NemotronRotaryEmbedding(nn.Module):
87
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
88
+
89
+ def __init__(self, config: NemotronConfig, device=None):
90
+ super().__init__()
91
+ self.max_seq_len_cached = config.max_position_embeddings
92
+ self.original_max_seq_len = config.max_position_embeddings
93
+
94
+ self.config = config
95
+
96
+ self.rope_type = self.config.rope_parameters["rope_type"]
97
+ rope_init_fn: Callable = self.compute_default_rope_parameters
98
+ if self.rope_type != "default":
99
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
100
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
101
+
102
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
103
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
104
+
105
+ @staticmethod
106
+ # Ignore copy
107
+ def compute_default_rope_parameters(
108
+ config: NemotronConfig | None = None,
109
+ device: Optional["torch.device"] = None,
110
+ seq_len: int | None = None,
111
+ ) -> tuple["torch.Tensor", float]:
112
+ """
113
+ Computes the inverse frequencies according to the original RoPE implementation
114
+ Args:
115
+ config ([`~transformers.PreTrainedConfig`]):
116
+ The model configuration.
117
+ device (`torch.device`):
118
+ The device to use for initialization of the inverse frequencies.
119
+ seq_len (`int`, *optional*):
120
+ The current sequence length. Unused for this type of RoPE.
121
+ Returns:
122
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
123
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
124
+ """
125
+ base = config.rope_parameters["rope_theta"]
126
+ partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
127
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
128
+ dim = int(head_dim * partial_rotary_factor)
129
+
130
+ attention_factor = 1.0 # Unused in this type of RoPE
131
+
132
+ # Compute the inverse frequencies
133
+ inv_freq = 1.0 / (
134
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
135
+ )
136
+ return inv_freq, attention_factor
137
+
138
+ @torch.no_grad()
139
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
140
+ def forward(self, x, position_ids):
141
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
142
+ position_ids_expanded = position_ids[:, None, :].float()
143
+
144
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
145
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
146
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
147
+ emb = torch.cat((freqs, freqs), dim=-1)
148
+ cos = emb.cos() * self.attention_scaling
149
+ sin = emb.sin() * self.attention_scaling
150
+
151
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
152
+
153
+
154
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
155
+ def rotate_half(x):
156
+ """Rotates half the hidden dims of the input."""
157
+ x1 = x[..., : x.shape[-1] // 2]
158
+ x2 = x[..., x.shape[-1] // 2 :]
159
+ return torch.cat((-x2, x1), dim=-1)
160
+
161
+
162
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
163
+ """Applies Rotary Position Embedding to the query and key tensors.
164
+
165
+ Args:
166
+ q (`torch.Tensor`): The query tensor.
167
+ k (`torch.Tensor`): The key tensor.
168
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
169
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
170
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
171
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
172
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
173
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
174
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
175
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
176
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
177
+ Returns:
178
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
179
+ """
180
+ cos = cos.unsqueeze(unsqueeze_dim)
181
+ sin = sin.unsqueeze(unsqueeze_dim)
182
+
183
+ rot_dim = cos.shape[-1]
184
+ # If q_pass/k_pass is empty, rotary pos embedding is applied to all tensor q/k
185
+ q, q_pass = q[..., :rot_dim], q[..., rot_dim:]
186
+ k, k_pass = k[..., :rot_dim], k[..., rot_dim:]
187
+
188
+ q_embed = (q * cos) + (rotate_half(q) * sin)
189
+ k_embed = (k * cos) + (rotate_half(k) * sin)
190
+ return torch.cat((q_embed, q_pass), dim=-1), torch.cat((k_embed, k_pass), dim=-1)
191
+
192
+
193
+ class NemotronMLP(nn.Module):
194
+ def __init__(self, config):
195
+ super().__init__()
196
+ self.config = config
197
+ self.hidden_size = config.hidden_size
198
+ self.intermediate_size = config.intermediate_size
199
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
200
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
201
+ self.act_fn = ACT2FN[config.hidden_act]
202
+
203
+ def forward(self, x):
204
+ return self.down_proj(self.act_fn(self.up_proj(x)))
205
+
206
+
207
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
208
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
209
+ """
210
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
211
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
212
+ """
213
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
214
+ if n_rep == 1:
215
+ return hidden_states
216
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
217
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
218
+
219
+
220
+ class NemotronAttention(nn.Module):
221
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
222
+
223
+ def __init__(self, config: NemotronConfig, layer_idx: int | None = None):
224
+ super().__init__()
225
+ self.config = config
226
+ self.layer_idx = layer_idx
227
+ if layer_idx is None:
228
+ logger.warning_once(
229
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
230
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
231
+ "when creating this class."
232
+ )
233
+
234
+ self.attention_dropout = config.attention_dropout
235
+ self.hidden_size = config.hidden_size
236
+ self.num_heads = config.num_attention_heads
237
+ self.head_dim = config.head_dim
238
+ self.num_key_value_heads = config.num_key_value_heads
239
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
240
+ self.max_position_embeddings = config.max_position_embeddings
241
+
242
+ self.partial_rotary_factor = config.rope_parameters["partial_rotary_factor"]
243
+ self.is_causal = True
244
+ self.rotary_emb = NemotronRotaryEmbedding(config=config)
245
+
246
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
247
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
248
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
249
+ self.o_proj = nn.Linear(self.head_dim * self.num_heads, self.hidden_size, bias=config.attention_bias)
250
+
251
+ def forward(
252
+ self,
253
+ hidden_states: torch.Tensor,
254
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
255
+ attention_mask: torch.Tensor | None = None,
256
+ position_ids: torch.LongTensor | None = None,
257
+ past_key_values: Cache | None = None,
258
+ output_attentions: bool = False,
259
+ use_cache: bool = False,
260
+ **kwargs,
261
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
262
+ bsz, q_len, _ = hidden_states.size()
263
+
264
+ query_states = self.q_proj(hidden_states)
265
+ key_states = self.k_proj(hidden_states)
266
+ value_states = self.v_proj(hidden_states)
267
+
268
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
269
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
270
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
271
+
272
+ cos, sin = position_embeddings
273
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
274
+
275
+ if past_key_values is not None:
276
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
277
+
278
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
279
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
280
+
281
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
282
+
283
+ if attention_mask is not None:
284
+ attn_weights = attn_weights + attention_mask
285
+
286
+ # upcast attention to fp32
287
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
288
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
289
+ attn_output = torch.matmul(attn_weights, value_states)
290
+
291
+ attn_output = attn_output.transpose(1, 2).contiguous()
292
+
293
+ attn_output = attn_output.reshape(bsz, q_len, -1)
294
+
295
+ attn_output = self.o_proj(attn_output)
296
+
297
+ return attn_output, attn_weights
298
+
299
+
300
+ # NO LONGER EXIST Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
301
+ # TODO cyril: modular
302
+ class NemotronFlashAttention2(NemotronAttention):
303
+ """
304
+ Nemotron flash attention module. This module inherits from `NemotronAttention` as the weights of the module stays
305
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
306
+ flash attention and deal with padding tokens in case the input contains any of them.
307
+ """
308
+
309
+ def __init__(self, *args, **kwargs):
310
+ super().__init__(*args, **kwargs)
311
+
312
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
313
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
314
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
315
+ self._flash_attn_uses_top_left_mask = flash_attn_supports_top_left_mask()
316
+
317
+ def forward(
318
+ self,
319
+ hidden_states: torch.Tensor,
320
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
321
+ attention_mask: torch.LongTensor | None = None,
322
+ position_ids: torch.LongTensor | None = None,
323
+ past_key_values: Cache | None = None,
324
+ output_attentions: bool = False,
325
+ use_cache: bool = False,
326
+ **kwargs,
327
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
328
+ if isinstance(past_key_values, StaticCache):
329
+ raise ValueError(
330
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
331
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
332
+ )
333
+
334
+ bsz, q_len, _ = hidden_states.size()
335
+
336
+ query_states = self.q_proj(hidden_states)
337
+ key_states = self.k_proj(hidden_states)
338
+ value_states = self.v_proj(hidden_states)
339
+
340
+ # Flash attention requires the input to have the shape
341
+ # batch_size x seq_length x head_dim x hidden_dim
342
+ # therefore we just need to keep the original shape
343
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
344
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
345
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
346
+
347
+ cos, sin = position_embeddings
348
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
349
+
350
+ if past_key_values is not None:
351
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
352
+
353
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
354
+ # to be able to avoid many of these transpose/reshape/view.
355
+ query_states = query_states.transpose(1, 2)
356
+ key_states = key_states.transpose(1, 2)
357
+ value_states = value_states.transpose(1, 2)
358
+
359
+ dropout_rate = self.attention_dropout if self.training else 0.0
360
+
361
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
362
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
363
+ # cast them back in the correct dtype just to be sure everything works as expected.
364
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
365
+ # in fp32. (NemotronRMSNorm handles it correctly)
366
+
367
+ input_dtype = query_states.dtype
368
+ device_type = query_states.device.type if query_states.device.type != "mps" else "cpu"
369
+ if input_dtype == torch.float32:
370
+ if torch.is_autocast_enabled():
371
+ target_dtype = torch.get_autocast_dtype(device_type)
372
+ # Handle the case where the model is quantized
373
+ elif hasattr(self.config, "_is_quantized"):
374
+ target_dtype = self.config.dtype
375
+ else:
376
+ target_dtype = self.q_proj.weight.dtype
377
+
378
+ logger.warning_once(
379
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
380
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
381
+ f" {target_dtype}."
382
+ )
383
+
384
+ query_states = query_states.to(target_dtype)
385
+ key_states = key_states.to(target_dtype)
386
+ value_states = value_states.to(target_dtype)
387
+
388
+ attn_output = _flash_attention_forward(
389
+ query_states,
390
+ key_states,
391
+ value_states,
392
+ attention_mask,
393
+ q_len,
394
+ position_ids=position_ids,
395
+ dropout=dropout_rate,
396
+ sliding_window=getattr(self, "sliding_window", None),
397
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
398
+ is_causal=self.is_causal,
399
+ )
400
+
401
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
402
+ attn_output = self.o_proj(attn_output)
403
+
404
+ return attn_output, None
405
+
406
+
407
+ # NO LONGER EXIST Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
408
+ # TODO cyril: modular
409
+ class NemotronSdpaAttention(NemotronAttention):
410
+ """
411
+ Nemotron attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
412
+ `NemotronAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
413
+ SDPA API.
414
+ """
415
+
416
+ def forward(
417
+ self,
418
+ hidden_states: torch.Tensor,
419
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
420
+ attention_mask: torch.Tensor | None = None,
421
+ position_ids: torch.LongTensor | None = None,
422
+ past_key_values: Cache | None = None,
423
+ output_attentions: bool = False,
424
+ use_cache: bool = False,
425
+ **kwargs,
426
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
427
+ if output_attentions:
428
+ logger.warning_once(
429
+ f"{self.__class__.__name__} does not support `output_attentions=True`. The returned attention weights will "
430
+ "be `None`. If you want to get attention weights, please set `attn_implementation='eager'` when loading the model."
431
+ )
432
+ bsz, q_len, _ = hidden_states.size()
433
+
434
+ query_states = self.q_proj(hidden_states)
435
+ key_states = self.k_proj(hidden_states)
436
+ value_states = self.v_proj(hidden_states)
437
+
438
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
439
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
440
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
441
+
442
+ cos, sin = position_embeddings
443
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
444
+
445
+ if past_key_values is not None:
446
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
447
+
448
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
449
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
450
+
451
+ causal_mask = attention_mask
452
+ if attention_mask is not None:
453
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
454
+
455
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
456
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
457
+ is_causal = causal_mask is None and q_len > 1
458
+
459
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
460
+ query_states,
461
+ key_states,
462
+ value_states,
463
+ attn_mask=causal_mask,
464
+ dropout_p=self.attention_dropout if self.training else 0.0,
465
+ is_causal=is_causal,
466
+ )
467
+
468
+ attn_output = attn_output.transpose(1, 2).contiguous()
469
+ attn_output = attn_output.view(bsz, q_len, -1)
470
+
471
+ attn_output = self.o_proj(attn_output)
472
+
473
+ return attn_output, None
474
+
475
+
476
+ NEMOTRON_ATTENTION_CLASSES = {
477
+ "eager": NemotronAttention,
478
+ "flash_attention_2": NemotronFlashAttention2,
479
+ "sdpa": NemotronSdpaAttention,
480
+ }
481
+
482
+
483
+ # copied from transformers.models.llama.modeling_llama.LlamaDecoderLayer with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
484
+ # no longer copied after attention refactors
485
+ class NemotronDecoderLayer(GradientCheckpointingLayer):
486
+ # Ignore copy
487
+ def __init__(self, config: NemotronConfig, layer_idx: int):
488
+ super().__init__()
489
+ self.hidden_size = config.hidden_size
490
+
491
+ self.self_attn = NEMOTRON_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
492
+
493
+ self.mlp = NemotronMLP(config)
494
+ self.input_layernorm = NemotronLayerNorm1P(config.hidden_size, eps=config.norm_eps)
495
+ self.post_attention_layernorm = NemotronLayerNorm1P(config.hidden_size, eps=config.norm_eps)
496
+
497
+ def forward(
498
+ self,
499
+ hidden_states: torch.Tensor,
500
+ attention_mask: torch.Tensor | None = None,
501
+ position_ids: torch.LongTensor | None = None,
502
+ past_key_values: Cache | None = None,
503
+ use_cache: bool | None = False,
504
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
505
+ **kwargs,
506
+ ) -> torch.Tensor:
507
+ residual = hidden_states
508
+
509
+ hidden_states = self.input_layernorm(hidden_states)
510
+
511
+ # Self Attention
512
+ hidden_states, _ = self.self_attn(
513
+ hidden_states=hidden_states,
514
+ attention_mask=attention_mask,
515
+ position_ids=position_ids,
516
+ past_key_values=past_key_values,
517
+ use_cache=use_cache,
518
+ position_embeddings=position_embeddings,
519
+ )
520
+
521
+ hidden_states = residual + hidden_states
522
+
523
+ # Fully Connected
524
+ residual = hidden_states
525
+ hidden_states = self.post_attention_layernorm(hidden_states)
526
+ hidden_states = self.mlp(hidden_states)
527
+ hidden_states = residual + hidden_states
528
+
529
+ return hidden_states
530
+
531
+
532
+ @auto_docstring
533
+ class NemotronPreTrainedModel(PreTrainedModel):
534
+ config: NemotronConfig
535
+ base_model_prefix = "model"
536
+ supports_gradient_checkpointing = True
537
+ _no_split_modules = ["NemotronDecoderLayer"]
538
+ _skip_keys_device_placement = ["past_key_values"]
539
+ _supports_flash_attn = True
540
+ _supports_sdpa = True
541
+
542
+ _can_compile_fullgraph = True
543
+ _can_record_outputs = {
544
+ "hidden_states": NemotronDecoderLayer,
545
+ "attentions": NemotronAttention,
546
+ }
547
+
548
+ @torch.no_grad()
549
+ def _init_weights(self, module):
550
+ super()._init_weights(module)
551
+ if isinstance(module, NemotronLayerNorm1P):
552
+ init.ones_(module.weight)
553
+ init.zeros_(module.bias)
554
+
555
+
556
+ @auto_docstring
557
+ class NemotronModel(NemotronPreTrainedModel):
558
+ """
559
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`NemotronDecoderLayer`]
560
+
561
+ Args:
562
+ config: NemotronConfig
563
+ """
564
+
565
+ def __init__(self, config: NemotronConfig):
566
+ super().__init__(config)
567
+ self.padding_idx = config.pad_token_id
568
+ self.vocab_size = config.vocab_size
569
+
570
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
571
+ self.layers = nn.ModuleList(
572
+ [NemotronDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
573
+ )
574
+ self.norm = NemotronLayerNorm1P(config.hidden_size, eps=config.norm_eps)
575
+ self.rotary_emb = NemotronRotaryEmbedding(config=config)
576
+ self.gradient_checkpointing = False
577
+
578
+ # Initialize weights and apply final processing
579
+ self.post_init()
580
+
581
+ @merge_with_config_defaults
582
+ @capture_outputs
583
+ @auto_docstring
584
+ def forward(
585
+ self,
586
+ input_ids: torch.LongTensor | None = None,
587
+ attention_mask: torch.Tensor | None = None,
588
+ position_ids: torch.LongTensor | None = None,
589
+ past_key_values: Cache | None = None,
590
+ inputs_embeds: torch.FloatTensor | None = None,
591
+ use_cache: bool | None = None,
592
+ **kwargs: Unpack[TransformersKwargs],
593
+ ) -> BaseModelOutputWithPast:
594
+ if (input_ids is None) ^ (inputs_embeds is not None):
595
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
596
+
597
+ if use_cache and past_key_values is None:
598
+ past_key_values = DynamicCache(config=self.config)
599
+
600
+ if inputs_embeds is None:
601
+ inputs_embeds = self.embed_tokens(input_ids)
602
+
603
+ if position_ids is None:
604
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
605
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
606
+ position_ids = position_ids.unsqueeze(0)
607
+
608
+ causal_mask = create_causal_mask(
609
+ config=self.config,
610
+ inputs_embeds=inputs_embeds,
611
+ attention_mask=attention_mask,
612
+ past_key_values=past_key_values,
613
+ position_ids=position_ids,
614
+ )
615
+
616
+ hidden_states = inputs_embeds
617
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
618
+
619
+ for decoder_layer in self.layers:
620
+ hidden_states = decoder_layer(
621
+ hidden_states,
622
+ attention_mask=causal_mask,
623
+ position_ids=position_ids,
624
+ past_key_values=past_key_values,
625
+ use_cache=use_cache,
626
+ position_embeddings=position_embeddings,
627
+ **kwargs,
628
+ )
629
+
630
+ hidden_states = self.norm(hidden_states)
631
+
632
+ return BaseModelOutputWithPast(
633
+ last_hidden_state=hidden_states,
634
+ past_key_values=past_key_values,
635
+ )
636
+
637
+
638
+ # TODO: re-enable check: Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
639
+ class NemotronForCausalLM(NemotronPreTrainedModel, GenerationMixin):
640
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
641
+
642
+ def __init__(self, config):
643
+ super().__init__(config)
644
+ self.model = NemotronModel(config)
645
+ self.vocab_size = config.vocab_size
646
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
647
+
648
+ # Initialize weights and apply final processing
649
+ self.post_init()
650
+
651
+ @can_return_tuple
652
+ @auto_docstring
653
+ def forward(
654
+ self,
655
+ input_ids: torch.LongTensor | None = None,
656
+ attention_mask: torch.Tensor | None = None,
657
+ position_ids: torch.LongTensor | None = None,
658
+ past_key_values: Cache | None = None,
659
+ inputs_embeds: torch.FloatTensor | None = None,
660
+ labels: torch.LongTensor | None = None,
661
+ use_cache: bool | None = None,
662
+ logits_to_keep: int | torch.Tensor = 0,
663
+ **kwargs: Unpack[TransformersKwargs],
664
+ ) -> CausalLMOutputWithPast:
665
+ r"""
666
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
667
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
668
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
669
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
670
+
671
+ Example:
672
+
673
+ ```python
674
+ >>> from transformers import AutoTokenizer, NemotronForCausalLM
675
+
676
+ >>> model = NemotronForCausalLM.from_pretrained("thhaus/nemotron3-8b")
677
+ >>> tokenizer = AutoTokenizer.from_pretrained("thhaus/nemotron3-8b")
678
+
679
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
680
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
681
+
682
+ >>> # Generate
683
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
684
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
685
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
686
+ ```"""
687
+ outputs: BaseModelOutputWithPast = self.model(
688
+ input_ids=input_ids,
689
+ attention_mask=attention_mask,
690
+ position_ids=position_ids,
691
+ past_key_values=past_key_values,
692
+ inputs_embeds=inputs_embeds,
693
+ use_cache=use_cache,
694
+ **kwargs,
695
+ )
696
+
697
+ hidden_states = outputs.last_hidden_state
698
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
699
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
700
+
701
+ loss = None
702
+ if labels is not None:
703
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
704
+
705
+ return CausalLMOutputWithPast(
706
+ loss=loss,
707
+ logits=logits,
708
+ past_key_values=outputs.past_key_values,
709
+ hidden_states=outputs.hidden_states,
710
+ attentions=outputs.attentions,
711
+ )
712
+
713
+
714
+ class NemotronForSequenceClassification(GenericForSequenceClassification, NemotronPreTrainedModel): ...
715
+
716
+
717
+ class NemotronForQuestionAnswering(GenericForQuestionAnswering, NemotronPreTrainedModel):
718
+ base_model_prefix = "transformer"
719
+
720
+
721
+ class NemotronForTokenClassification(GenericForTokenClassification, NemotronPreTrainedModel): ...
722
+
723
+
724
+ __all__ = [
725
+ "NemotronForQuestionAnswering",
726
+ "NemotronForCausalLM",
727
+ "NemotronModel",
728
+ "NemotronPreTrainedModel",
729
+ "NemotronForSequenceClassification",
730
+ "NemotronForTokenClassification",
731
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nemotron_h/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 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_nemotron_h import *
22
+ from .modeling_nemotron_h 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__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nemotron_h/configuration_nemotron_h.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-2025 NVIDIA Corporation 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
+ """NemotronH model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...configuration_utils import PreTrainedConfig
19
+ from ...utils import auto_docstring, logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ @auto_docstring(checkpoint="nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16")
26
+ @strict
27
+ class NemotronHConfig(PreTrainedConfig):
28
+ r"""
29
+ layers_block_type (`list`, *optional*):
30
+ Explicit list of layer types for each layer. Each element must be one of: "mlp", "mamba", "attention", or "moe".
31
+ The number of layers is determined by the length of this list.
32
+ num_logits_to_keep (`int`, *optional*, defaults to 1):
33
+ Number of prompt logits to calculate during generation. If `None`, all logits will be calculated.
34
+ use_mamba_kernels (`bool`, *optional*, defaults to `True`):
35
+ Flag indicating whether or not to use the fast mamba kernels.
36
+ ssm_state_size (`int`, *optional*, defaults to 128):
37
+ The dimension of the mamba state space latents.
38
+ mamba_hidden_act (`str`, *optional*, defaults to `"silu"`):
39
+ The non-linear activation function in the Mamba layers.
40
+ n_groups (`int`, *optional*, defaults to 8):
41
+ Number of groups for the evolution matrices of the Mamba layers.
42
+ expand (`int`, *optional*, defaults to 2):
43
+ Expanding factor used to determine the intermediate size in the Mamba layers.
44
+ use_conv_bias (`bool`, *optional*, defaults to `True`):
45
+ Whether or not to use bias in the convolution layer of the Mamba mixer block.
46
+ chunk_size (`int`, *optional*, defaults to 128):
47
+ Size of the chunks that will comprise the sequence in the Mamba layers.
48
+ mamba_ssm_cache_dtype (`str`, *optional*, defaults to `"float32"`):
49
+ Data type for Mamba SSM cache states.
50
+ moe_shared_expert_intermediate_size (`int`, *optional*, defaults to 7688):
51
+ Dimension of the MLP representations in shared experts.
52
+ moe_latent_size (`int`, *optional*):
53
+ Latent size for MoE expert projections. If `None`, uses `hidden_size`.
54
+ moe_shared_expert_overlap (`bool`, *optional*, defaults to `True`):
55
+ Whether shared experts overlap with routed experts.
56
+ n_group (`int`, *optional*, defaults to 1):
57
+ Number of groups for expert routing.
58
+ num_nextn_predict_layers (`int`, *optional*, defaults to 0):
59
+ Number of additional layers for multi-token prediction. If 0, multi-token prediction is disabled.
60
+ mtp_layers_block_type (`list`, *optional*, defaults to `['attention', 'moe']`):
61
+ Explicit list of layer types for multi-token prediction layers when `num_nextn_predict_layers` > 0.
62
+ use_bias (`bool`, *optional*, defaults to `False`):
63
+ Whether to use bias in the model.
64
+ residual_in_fp32 (`bool`, *optional*, defaults to `False`):
65
+ Whether or not residuals should be in `float32`.
66
+ rescale_prenorm_residual (`bool`, *optional*, defaults to `True`):
67
+ Whether to rescale the pre-normalization residual connections.
68
+
69
+ ```python
70
+ >>> from transformers import NemotronHModel, NemotronHConfig
71
+
72
+ >>> # Initializing a NemotronH configuration
73
+ >>> configuration = NemotronHConfig()
74
+
75
+ >>> # Initializing a model (with random weights) from the configuration
76
+ >>> model = NemotronHModel(configuration)
77
+
78
+ >>> # Accessing the model configuration
79
+ >>> configuration = model.config
80
+ ```
81
+ """
82
+
83
+ model_type = "nemotron_h"
84
+ attribute_map = {"layer_types": "layers_block_type"}
85
+ keys_to_ignore_at_inference = ["past_key_values"]
86
+
87
+ vocab_size: int = 131072
88
+ hidden_size: int = 4096
89
+ layers_block_type: list[str] | None = None
90
+ tie_word_embeddings: bool = False
91
+ use_cache: bool = True
92
+ num_logits_to_keep: int = 1
93
+ pad_token_id: int | None = 0
94
+ bos_token_id: int | None = 1
95
+ eos_token_id: int | list[int] | None = 2
96
+ num_attention_heads: int = 32
97
+ num_key_value_heads: int = 8
98
+ head_dim: int = 128
99
+ max_position_embeddings: int = 4096
100
+ attention_bias: bool = False
101
+ attention_dropout: float | int = 0.0
102
+ sliding_window: int | None = None
103
+ intermediate_size: int = 21504
104
+ mlp_hidden_act: str = "relu2"
105
+ mlp_bias: bool = False
106
+ use_mamba_kernels: bool = True
107
+ ssm_state_size: int = 128
108
+ mamba_num_heads: int = 128
109
+ mamba_head_dim: int = 64
110
+ mamba_hidden_act: str = "silu"
111
+ n_groups: int = 8
112
+ conv_kernel: int = 4
113
+ expand: int = 2
114
+ time_step_min: float = 0.001
115
+ time_step_max: float = 0.1
116
+ time_step_limit: list[float] | tuple[float, ...] = (0.0, float("inf"))
117
+ time_step_floor: float = 1e-4
118
+ use_conv_bias: bool = True
119
+ chunk_size: int = 128
120
+ mamba_proj_bias: bool = False
121
+ mamba_ssm_cache_dtype: str = "float32"
122
+ n_routed_experts: int = 8
123
+ n_shared_experts: int = 1
124
+ moe_intermediate_size: int = 7688
125
+ moe_shared_expert_intermediate_size: int = 7688
126
+ moe_latent_size: int | None = None
127
+ moe_shared_expert_overlap: bool = True
128
+ num_experts_per_tok: int = 2
129
+ routed_scaling_factor: float | int = 1.0
130
+ n_group: int = 1
131
+ topk_group: int = 1
132
+ norm_topk_prob: bool = True
133
+ num_nextn_predict_layers: int = 0
134
+ mtp_layers_block_type: list[str] | None = None
135
+ use_bias: bool = False
136
+ initializer_range: float = 0.02
137
+ layer_norm_epsilon: float = 1e-5
138
+ residual_in_fp32: bool = False
139
+ hidden_dropout: float | int = 0.0
140
+ rescale_prenorm_residual: bool = True
141
+
142
+ def __post_init__(self, **kwargs):
143
+ # Backward compatibility; configs expect different names for these fields when init
144
+ # but they have to be re-names when creating/saving the config.
145
+ self.n_groups = kwargs.pop("mamba_n_groups") if "mamba_n_groups" in kwargs else self.n_groups
146
+ self.conv_kernel = kwargs.pop("mamba_d_conv") if "mamba_d_conv" in kwargs else self.conv_kernel
147
+ self.expand = kwargs.pop("mamba_expand") if "mamba_expand" in kwargs else self.expand
148
+ self.time_step_min = kwargs.pop("mamba_dt_min") if "mamba_dt_min" in kwargs else self.time_step_min
149
+ self.time_step_max = kwargs.pop("mamba_dt_max") if "mamba_dt_max" in kwargs else self.time_step_max
150
+ self.time_step_limit = kwargs.pop("mamba_dt_limit") if "mamba_dt_limit" in kwargs else self.time_step_limit
151
+ self.time_step_floor = (
152
+ kwargs.pop("mamba_dt_init_floor") if "mamba_dt_init_floor" in kwargs else self.time_step_floor
153
+ )
154
+ self.use_conv_bias = kwargs.pop("mamba_conv_bias") if "mamba_conv_bias" in kwargs else self.use_conv_bias
155
+ self.chunk_size = kwargs.pop("mamba_chunk_size") if "mamba_chunk_size" in kwargs else self.chunk_size
156
+
157
+ # Backward compatibility: convert hybrid_override_pattern to layers_block_type
158
+ # Always pop hybrid_override_pattern from kwargs to prevent it from being set as an attribute
159
+ if "hybrid_override_pattern" in kwargs:
160
+ pattern = kwargs.pop("hybrid_override_pattern")
161
+ if self.layer_types is None:
162
+ self.layer_types = self._pattern_to_list(pattern)
163
+ elif self.layer_types is None:
164
+ # Default layers_block_type if not provided
165
+ self.layer_types = ["mamba", "moe", "attention", "mlp"]
166
+
167
+ # Note: num_hidden_layers is deprecated and ignored if layers_block_type is explicitly provided
168
+ # It's only kept for backward compatibility when loading old configs
169
+ if self.num_hidden_layers is not None:
170
+ # Warn if num_hidden_layers is provided but doesn't match layers_block_type
171
+ if len(self.layer_types) != self.num_hidden_layers:
172
+ logger.warning(
173
+ f"num_hidden_layers ({self.num_hidden_layers}) is deprecated and doesn't match "
174
+ f"layer_types length ({len(self.layer_types)}). Using layers_block_type length."
175
+ )
176
+
177
+ # Backward compatibility: convert mtp_hybrid_override_pattern to mtp_layers_block_type
178
+ # Always pop mtp_hybrid_override_pattern from kwargs to prevent it from being set as an attribute
179
+ if self.mtp_layers_block_type is None:
180
+ self.mtp_layers_block_type = ["attention", "moe"]
181
+
182
+ if "mtp_hybrid_override_pattern" in kwargs:
183
+ pattern = kwargs.pop("mtp_hybrid_override_pattern")
184
+ if self.mtp_layers_block_type == ["attention", "moe"]:
185
+ self.mtp_layers_block_type = self._pattern_to_list(pattern)
186
+
187
+ # for backward compatibility
188
+ if self.num_key_value_heads is None:
189
+ self.num_key_value_heads = self.num_attention_heads
190
+
191
+ super().__post_init__(**kwargs)
192
+
193
+ @staticmethod
194
+ def validate_layer_type(self):
195
+ """
196
+ Validate layers_block_type list.
197
+ """
198
+ if not isinstance(self.layer_types, list):
199
+ raise ValueError(f"`layers_block_type` must be a list of strings. Got type: {type(self.layer_types)}")
200
+
201
+ valid_types = {"mamba", "attention", "moe", "mlp"}
202
+ if not all(block_type in valid_types for block_type in self.layer_types):
203
+ invalid = set(self.layer_types) - valid_types
204
+ raise ValueError(f"`layers_block_type` contains invalid types: {invalid}. Must be one of: {valid_types}")
205
+
206
+ if self.num_nextn_predict_layers > 0:
207
+ if self.mtp_layers_block_type is None:
208
+ raise ValueError(
209
+ "mtp_layers_block_type is required when num_nextn_predict_layers > 0. "
210
+ "Please provide an explicit list of layer types for MTP layers. "
211
+ "Example: mtp_layers_block_type=['attention', 'moe']"
212
+ )
213
+
214
+ if not isinstance(self.mtp_layers_block_type, list):
215
+ raise ValueError(
216
+ f"`mtp_layers_block_type` must be a list of strings. Got type: {type(self.mtp_layers_block_type)}"
217
+ )
218
+
219
+ if not all(block_type in valid_types for block_type in self.mtp_layers_block_type):
220
+ invalid = set(self.mtp_layers_block_type) - valid_types
221
+ raise ValueError(
222
+ f"`mtp_layers_block_type` contains invalid types: {invalid}. Must be one of: {valid_types}"
223
+ )
224
+
225
+ @property
226
+ def num_hidden_layers(self) -> int:
227
+ """
228
+ Number of hidden layers derived from the length of layers_block_type.
229
+ This property replaces the deprecated num_hidden_layers parameter.
230
+ """
231
+ return len(self.layers_block_type)
232
+
233
+ @num_hidden_layers.setter
234
+ def num_hidden_layers(self, value):
235
+ """
236
+ Setter for backward compatibility when loading configs.
237
+ The value is ignored since num_hidden_layers is computed from layers_block_type.
238
+ """
239
+ # Ignore the value - num_hidden_layers is always derived from layers_block_type
240
+ pass
241
+
242
+ @property
243
+ def hybrid_override_pattern(self) -> str:
244
+ """
245
+ Backward compatibility property.
246
+ Returns the pattern string representation of layers_block_type.
247
+ """
248
+ return self._list_to_pattern(self.layers_block_type)
249
+
250
+ @property
251
+ def mtp_hybrid_override_pattern(self) -> str:
252
+ """
253
+ Backward compatibility property.
254
+ Returns the pattern string representation of mtp_layers_block_type.
255
+ """
256
+ return self._list_to_pattern(self.mtp_layers_block_type)
257
+
258
+ @staticmethod
259
+ def _list_to_pattern(layers_list: list) -> str:
260
+ """Convert list of layer types back to pattern string (for backward compatibility)."""
261
+ reverse_mapping = {"mamba": "M", "moe": "E", "attention": "*", "mlp": "-"}
262
+ return "".join(reverse_mapping[layer_type] for layer_type in layers_list)
263
+
264
+ @staticmethod
265
+ def _pattern_to_list(pattern: str) -> list:
266
+ """Convert pattern string to list of layer types (for backward compatibility)."""
267
+ pattern_mapping = {"M": "mamba", "E": "moe", "*": "attention", "-": "mlp"}
268
+ return [pattern_mapping[char] for char in pattern]
269
+
270
+
271
+ __all__ = ["NemotronHConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nemotron_h/modeling_nemotron_h.py ADDED
@@ -0,0 +1,1231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/nemotron_h/modular_nemotron_h.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_nemotron_h.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
8
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+
23
+ import math
24
+ from collections.abc import Callable
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ from torch import nn
29
+
30
+ from ... import initialization as init
31
+ from ...activations import ACT2FN
32
+ from ...cache_utils import Cache, DynamicCache
33
+ from ...generation import GenerationMixin
34
+ from ...integrations import (
35
+ lazy_load_kernel,
36
+ use_experts_implementation,
37
+ use_kernel_forward_from_hub,
38
+ use_kernel_func_from_hub,
39
+ use_kernelized_func,
40
+ )
41
+ from ...masking_utils import create_causal_mask
42
+ from ...modeling_layers import GradientCheckpointingLayer
43
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
44
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
45
+ from ...models.zamba2.modeling_zamba2 import Zamba2RMSNormGated
46
+ from ...processing_utils import Unpack
47
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
48
+ from ...utils.generic import merge_with_config_defaults
49
+ from ...utils.import_utils import resolve_internal_import
50
+ from ...utils.output_capturing import capture_outputs
51
+ from .configuration_nemotron_h import NemotronHConfig
52
+
53
+
54
+ logger = logging.get_logger(__name__)
55
+
56
+
57
+ # Helper methods for segment sum computation
58
+
59
+
60
+ def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
61
+ """
62
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
63
+
64
+ Assumes that we only have tensors of either size 4 or 3
65
+ """
66
+ pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
67
+
68
+ return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
69
+
70
+
71
+ def reshape_into_chunks(input_tensor, pad_size, chunk_size):
72
+ """
73
+ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
74
+ simultaneously splitting it into chunk sequences.
75
+
76
+ Assumes that we only have tensors of either size 4 or 3
77
+ """
78
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
79
+ input_tensor = pad_tensor_by_size(input_tensor, pad_size)
80
+
81
+ if len(input_tensor.shape) == 3:
82
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
83
+ return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
84
+ else:
85
+ # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size]
86
+ return input_tensor.reshape(
87
+ input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
88
+ )
89
+
90
+
91
+ def segment_sum(input_tensor):
92
+ """
93
+ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
94
+ """
95
+ chunk_size = input_tensor.size(-1)
96
+ # 1. expand input tensor to have an additional dimension and repeat along that dimension
97
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
98
+ input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
99
+ # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
100
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
101
+ input_tensor = input_tensor.masked_fill(~mask, 0)
102
+ # 3. compute actual cumsum
103
+ tensor_segsum = torch.cumsum(input_tensor, dim=-2)
104
+
105
+ # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
106
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
107
+ tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
108
+ return tensor_segsum
109
+
110
+
111
+ is_fast_path_available = False
112
+
113
+
114
+ class NemotronHMamba2Mixer(nn.Module):
115
+ """
116
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
117
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
118
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
119
+ and is why Mamba is called **selective** state spaces)
120
+ """
121
+
122
+ def __init__(self, config: NemotronHConfig, layer_idx: int | None = None):
123
+ super().__init__()
124
+ self.config = config
125
+ self.hidden_size = config.hidden_size
126
+ self.ssm_state_size = config.ssm_state_size
127
+ self.conv_kernel_size = config.conv_kernel
128
+ self.intermediate_size = config.mamba_num_heads * config.mamba_head_dim
129
+ self.layer_idx = layer_idx
130
+ self.use_conv_bias = config.use_conv_bias
131
+ self.activation = config.mamba_hidden_act
132
+ self.act = ACT2FN[config.mamba_hidden_act]
133
+ self.use_mem_eff_path = True
134
+
135
+ self.n_groups = config.n_groups
136
+ self.head_dim = config.mamba_head_dim
137
+ self.num_heads = config.mamba_num_heads
138
+ self.chunk_size = config.chunk_size
139
+
140
+ self.time_step_limit = config.time_step_limit
141
+ self.time_step_min = config.time_step_min
142
+ self.time_step_max = config.time_step_max
143
+
144
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
145
+
146
+ self.conv1d = nn.Conv1d(
147
+ in_channels=self.conv_dim,
148
+ out_channels=self.conv_dim,
149
+ bias=config.use_conv_bias,
150
+ kernel_size=self.conv_kernel_size,
151
+ groups=self.conv_dim,
152
+ padding=self.conv_kernel_size - 1,
153
+ )
154
+
155
+ # projection of the input hidden states
156
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
157
+
158
+ self.in_proj = nn.Linear(
159
+ self.hidden_size,
160
+ projection_size,
161
+ bias=config.use_bias,
162
+ )
163
+ # selective projection used to make dt, B and C input dependent
164
+
165
+ # time step projection (discretization)
166
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
167
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
168
+
169
+ # S4D real initialization. These are not discretized!
170
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
171
+ A = torch.arange(1, self.num_heads + 1)
172
+ self.A_log = nn.Parameter(torch.log(A))
173
+
174
+ self.norm = Zamba2RMSNormGated(
175
+ self.intermediate_size, group_size=self.intermediate_size // self.n_groups, eps=config.layer_norm_epsilon
176
+ )
177
+ self.D = nn.Parameter(torch.ones(self.num_heads))
178
+
179
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
180
+
181
+ global causal_conv1d_update, causal_conv1d_fn
182
+ global selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
183
+ global is_fast_path_available
184
+
185
+ if config.use_mamba_kernels:
186
+ causal_conv1d = lazy_load_kernel("causal-conv1d")
187
+ causal_conv1d_update = getattr(causal_conv1d, "causal_conv1d_update", None)
188
+ causal_conv1d_fn = getattr(causal_conv1d, "causal_conv1d_fn", None)
189
+
190
+ mamba_ssm = lazy_load_kernel("mamba-ssm")
191
+ selective_state_update = resolve_internal_import(
192
+ mamba_ssm, chained_path="ops.triton.selective_state_update.selective_state_update"
193
+ )
194
+ mamba_chunk_scan_combined = resolve_internal_import(
195
+ mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_chunk_scan_combined"
196
+ )
197
+ mamba_split_conv1d_scan_combined = resolve_internal_import(
198
+ mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_split_conv1d_scan_combined"
199
+ )
200
+
201
+ is_fast_path_available = all(
202
+ (
203
+ selective_state_update,
204
+ mamba_chunk_scan_combined,
205
+ mamba_split_conv1d_scan_combined,
206
+ causal_conv1d_fn,
207
+ causal_conv1d_update,
208
+ )
209
+ )
210
+ else:
211
+ causal_conv1d_update = None
212
+ causal_conv1d_fn = None
213
+ selective_state_update = None
214
+ mamba_chunk_scan_combined = None
215
+ mamba_split_conv1d_scan_combined = None
216
+ is_fast_path_available = False
217
+
218
+ if getattr(config, "use_mamba_kernels", True) and not is_fast_path_available:
219
+ logger.warning_once(
220
+ "The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
221
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
222
+ " https://github.com/Dao-AILab/causal-conv1d"
223
+ )
224
+
225
+ def cuda_kernels_forward(
226
+ self,
227
+ hidden_states: torch.Tensor,
228
+ cache_params: Cache | None = None,
229
+ attention_mask: torch.Tensor | None = None,
230
+ ):
231
+ # set up dimensions for reshapes later
232
+
233
+ batch_size, seq_len, _ = hidden_states.shape
234
+ groups_time_state_size = self.n_groups * self.ssm_state_size
235
+ d_to_remove = 2 * self.intermediate_size + 2 * self.n_groups * self.ssm_state_size + self.num_heads
236
+
237
+ # getting projected states from cache if it exists
238
+ if cache_params is not None and cache_params.has_previous_state(self.layer_idx):
239
+ in_projected_states = self.in_proj(hidden_states.squeeze(1)) # (B 2D)
240
+ d_mlp = (in_projected_states.shape[-1] - d_to_remove) // 2
241
+ split_projection_dim = [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads]
242
+ _, _, gate, hidden_states_B_C, dt = torch.split(in_projected_states, split_projection_dim, dim=-1)
243
+
244
+ hidden_states_B_C = causal_conv1d_update(
245
+ hidden_states_B_C,
246
+ cache_params.layers[self.layer_idx].conv_states,
247
+ self.conv1d.weight.squeeze(1),
248
+ self.conv1d.bias,
249
+ self.activation,
250
+ )
251
+
252
+ hidden_states, B, C = torch.split(
253
+ hidden_states_B_C,
254
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
255
+ dim=-1,
256
+ )
257
+ A = -torch.exp(self.A_log.float()) # (nheads,)
258
+
259
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
260
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
261
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
262
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
263
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
264
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
265
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
266
+ hidden_states = selective_state_update(
267
+ cache_params.layers[self.layer_idx].recurrent_states,
268
+ hidden_states_reshaped,
269
+ dt,
270
+ A,
271
+ B,
272
+ C,
273
+ D,
274
+ z=None,
275
+ dt_bias=dt_bias,
276
+ dt_softplus=True,
277
+ )
278
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
279
+ hidden_states = self.norm(hidden_states, gate)
280
+ out = self.out_proj(hidden_states)[:, None, ...]
281
+ # if no cache is found, calling the kernel
282
+ else:
283
+ if attention_mask is not None and not torch.all(attention_mask == 1):
284
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
285
+ dtype = hidden_states.dtype
286
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
287
+ # 1. Gated MLP's linear projection
288
+ projected_states = self.in_proj(hidden_states)
289
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
290
+ dt_limit_kwargs = {} if self.time_step_limit is None else {"dt_limit": self.time_step_limit}
291
+ if attention_mask is not None:
292
+ input_not_masked = torch.all(attention_mask == 1)
293
+ else:
294
+ input_not_masked = True
295
+
296
+ if self.use_mem_eff_path and self.training and cache_params is None and input_not_masked:
297
+ out, ssm_state = mamba_split_conv1d_scan_combined(
298
+ projected_states,
299
+ self.conv1d.weight.squeeze(1),
300
+ self.conv1d.bias,
301
+ self.dt_bias,
302
+ A,
303
+ D=self.D,
304
+ chunk_size=self.chunk_size,
305
+ seq_idx=None,
306
+ activation=self.activation,
307
+ rmsnorm_weight=self.norm.weight,
308
+ rmsnorm_eps=self.norm.variance_epsilon,
309
+ outproj_weight=self.out_proj.weight,
310
+ outproj_bias=self.out_proj.bias,
311
+ headdim=self.head_dim,
312
+ ngroups=self.n_groups,
313
+ norm_before_gate=False,
314
+ return_final_states=True,
315
+ **dt_limit_kwargs,
316
+ )
317
+
318
+ else:
319
+ gate, hidden_states_B_C, time_step = torch.split(
320
+ projected_states,
321
+ [self.intermediate_size, self.conv_dim, self.num_heads],
322
+ dim=-1,
323
+ )
324
+
325
+ # 1D Convolution
326
+ if cache_params is not None:
327
+ hidden_states_B_C_t = hidden_states_B_C.transpose(1, 2)
328
+ conv_state = nn.functional.pad(
329
+ hidden_states_B_C_t, (self.conv_kernel_size - hidden_states_B_C_t.shape[-1], 0)
330
+ )
331
+ conv_state = cache_params.update_conv_state(conv_state, self.layer_idx)
332
+ if causal_conv1d_fn is None or self.activation not in ["silu", "swish"]:
333
+ hidden_states_B_C = self.act(
334
+ self.conv1d(hidden_states_B_C.transpose(1, 2)).transpose(1, 2)[:, :seq_len]
335
+ ) # (B, L, self.d_inner + 2 * ngroups * d_state)
336
+ else:
337
+ hidden_states_B_C = causal_conv1d_fn(
338
+ x=hidden_states_B_C.transpose(1, 2),
339
+ weight=self.conv1d.weight.squeeze(1),
340
+ bias=self.conv1d.bias,
341
+ activation=self.activation,
342
+ ).transpose(1, 2)[:, :seq_len]
343
+ hidden_states, B, C = torch.split(
344
+ hidden_states_B_C,
345
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
346
+ dim=-1,
347
+ )
348
+ if attention_mask is not None and not torch.all(attention_mask == 1):
349
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
350
+ dtype = hidden_states.dtype
351
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
352
+ scan_output, ssm_state = mamba_chunk_scan_combined(
353
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
354
+ time_step,
355
+ A,
356
+ B.view(batch_size, seq_len, self.n_groups, -1),
357
+ C.view(batch_size, seq_len, self.n_groups, -1),
358
+ chunk_size=self.chunk_size,
359
+ D=self.D,
360
+ z=None,
361
+ seq_idx=None,
362
+ return_final_states=True,
363
+ dt_bias=self.dt_bias,
364
+ dt_softplus=True,
365
+ **dt_limit_kwargs,
366
+ )
367
+ if ssm_state is not None and cache_params is not None:
368
+ cache_params.update_recurrent_state(ssm_state, self.layer_idx)
369
+ scan_output = scan_output.view(batch_size, seq_len, -1)
370
+ # Multiply "gate" branch and apply extra normalization layer
371
+ scan_output = self.norm(scan_output, gate)
372
+ out = self.out_proj(scan_output)
373
+ return out
374
+
375
+ # fmt: off
376
+ def torch_forward(self, input_states, cache_params: Cache | None=None, attention_mask: torch.Tensor | None = None):
377
+ batch_size, seq_len, _ = input_states.shape
378
+ dtype = input_states.dtype
379
+ # Gated MLP's linear projection
380
+ if cache_params is not None and cache_params.has_previous_state(self.layer_idx):
381
+ projected_states = self.in_proj(input_states)
382
+ else:
383
+ if attention_mask is not None:
384
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
385
+ input_states = (input_states * attention_mask[:, :, None]).to(dtype)
386
+ projected_states = self.in_proj(input_states)
387
+ d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size- self.num_heads) // 2
388
+ _, _, gate, hidden_states, dt = projected_states.split(
389
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
390
+ )
391
+ hidden_states = hidden_states.transpose(1, 2)
392
+
393
+ use_precomputed_state = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
394
+
395
+ # Convolution sequence transformation
396
+ if use_precomputed_state:
397
+ conv_state = cache_params.update_conv_state(hidden_states, self.layer_idx)
398
+ hidden_states = torch.sum(conv_state * self.conv1d.weight[:, 0, :], dim=-1)
399
+ if self.use_conv_bias:
400
+ hidden_states += self.conv1d.bias
401
+ hidden_states = self.act(hidden_states).to(dtype)[:, None, ...] # [batch, 1, intermediate_size] : decoding
402
+ else:
403
+ if cache_params is not None:
404
+ conv_state = nn.functional.pad(
405
+ hidden_states,
406
+ (self.conv_kernel_size - hidden_states.shape[-1], 0)
407
+ )
408
+ conv_state = cache_params.update_conv_state(conv_state, self.layer_idx)
409
+
410
+ hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len].transpose(1, 2))
411
+ if attention_mask is not None:
412
+ dtype = hidden_states.dtype
413
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
414
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
415
+
416
+ hidden_states, B, C = torch.split(hidden_states, [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size], dim=-1)
417
+ A = -torch.exp(self.A_log.float()) # [num_heads]
418
+ if use_precomputed_state:
419
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
420
+ # for batched generation
421
+ dt = dt[:, None, ...] if dt.ndim == 2 else dt[:, 0, :][:, None, ...]
422
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
423
+ # [num_heads] -> [num_heads, head_dim]
424
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
425
+
426
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
427
+ dt = torch.clamp(dt, self.time_step_min) #, self.time_step_max)
428
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
429
+ # [bsz, num_heads, head_dim, state_size]
430
+ dA = torch.exp(dt[..., None] * A)
431
+
432
+ # Discretize B
433
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
434
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
435
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
436
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
437
+ B = B.reshape(batch_size, -1, B.shape[-1])
438
+ # [bsz, num_heads, head_dim, state_size]
439
+ dB = dt[..., None] * B[..., None, :]
440
+
441
+ # Discretize x into dB
442
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
443
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
444
+ dBx = dB * hidden_states[..., None]
445
+
446
+ # State calculation
447
+ ssm_states = cache_params.layers[self.layer_idx].recurrent_states.clone()
448
+ ssm_states = ssm_states * dA + dBx
449
+ ssm_states = cache_params.update_recurrent_state(ssm_states, self.layer_idx)
450
+
451
+ # Subsequent output
452
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
453
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
454
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
455
+ C = C.reshape(batch_size, -1, C.shape[-1])
456
+ # [bsz, num_heads, head_dim]
457
+
458
+ ssm_states = ssm_states.to(C.dtype) # Shape: [b, h, d, n]
459
+ # Reshape ssm_states to merge the first two dimensions
460
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
461
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
462
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
463
+ y = y.view(batch_size, self.num_heads, self.head_dim)
464
+
465
+ # D skip connection
466
+ # [num_heads] -> [num_heads, head_dim]
467
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
468
+ y = (y + hidden_states * D).to(y.dtype)
469
+
470
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
471
+ y = y.reshape(batch_size, -1)[:, None, ...]
472
+ else:
473
+ # begin ssd naive implementation without einsums
474
+ dt = nn.functional.softplus(dt + self.dt_bias)
475
+ dt = torch.clamp(dt, self.time_step_min)
476
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
477
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
478
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
479
+ B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
480
+ C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
481
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
482
+
483
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
484
+
485
+ # Discretize x and A
486
+ hidden_states = hidden_states * dt[..., None]
487
+ A = A.to(hidden_states.dtype) * dt
488
+
489
+ # Rearrange into blocks/chunks
490
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
491
+
492
+
493
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
494
+ A = A.permute(0, 3, 1, 2)
495
+ A_cumsum = torch.cumsum(A, dim=-1)
496
+
497
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
498
+ # This is the analog of a causal mask
499
+ L = torch.exp(segment_sum(A))
500
+
501
+ # First, contraction of C and B to get G (attention-weights like)
502
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, : ,:] # shape: (b, c, l, s, h, n)
503
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
504
+
505
+
506
+ # Step 2: Compute M, equivalent to applying attention mask to weights
507
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
508
+ M = M_intermediate.sum(dim=-1)
509
+
510
+ # Step 3: Compute Y_diag (apply to values)
511
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(3)
512
+
513
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
514
+
515
+ decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
516
+ B_decay_contraction = B * decay_states.permute(0, 2, 3, 1)[..., None]
517
+ # permute back B * decay states
518
+ states = (B_decay_contraction.permute(0, 1, 3, 2, 4)[..., None] * hidden_states.permute(0, 1, 3, 2, 4)[..., None, :]).sum(dim=3).permute(0, 1, 2, 4, 3)
519
+ previous_states = torch.zeros_like(states[:, :1])
520
+ states = torch.cat([previous_states, states], dim=1)
521
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
522
+
523
+ states_permuted = states.permute(0, 2, 1, 3, 4)
524
+ result = (decay_chunk[..., None, None] * states_permuted[:, :, None, ...]).sum(dim=2)
525
+ new_states = result.permute(0, 2, 1, 3, 4)
526
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
527
+
528
+ # Compute state -> output conversion per chunk
529
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
530
+ state_decay_out = torch.exp(A_cumsum)
531
+ # compute Yoff
532
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
533
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
534
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
535
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
536
+
537
+ y = Y_diag + Y_off
538
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
539
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
540
+
541
+ y = y + D_residual
542
+ # Cutting off padded chunks
543
+ if pad_size > 0:
544
+ y = y[:, :seq_len, :, :]
545
+ y = y.reshape(batch_size, seq_len, -1)
546
+ if ssm_state is not None and cache_params is not None:
547
+ cache_params.update_recurrent_state(ssm_state, self.layer_idx)
548
+
549
+ scan_output = self.norm(y, gate)
550
+
551
+ # end ssd naive
552
+
553
+ # 4. Final linear projection
554
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
555
+ return contextualized_states
556
+ # fmt: on
557
+
558
+ def forward(
559
+ self,
560
+ hidden_states,
561
+ cache_params: Cache | None = None,
562
+ attention_mask: torch.Tensor | None = None,
563
+ **kwargs,
564
+ ):
565
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type and not is_torchdynamo_compiling():
566
+ # Use cuda stream to avoid NaN when using multiple GPUs, which is caused by multi-GPU synchronization issue.
567
+ # Mamba might launch on the default cuda stream that not strictly respect the current Pytorch cuda stream.
568
+ # This leads to kernel reading uninitialized memory before the data transfer is complete.
569
+ with torch.cuda.stream(torch.cuda.default_stream(hidden_states.device)):
570
+ return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
571
+
572
+ return self.torch_forward(hidden_states, cache_params, attention_mask)
573
+
574
+
575
+ @use_kernel_forward_from_hub("RMSNorm")
576
+ class NemotronHRMSNorm(nn.Module):
577
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
578
+ """
579
+ NemotronHRMSNorm is equivalent to T5LayerNorm
580
+ """
581
+ super().__init__()
582
+ self.weight = nn.Parameter(torch.ones(hidden_size))
583
+ self.variance_epsilon = eps
584
+
585
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
586
+ input_dtype = hidden_states.dtype
587
+ hidden_states = hidden_states.to(torch.float32)
588
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
589
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
590
+ return self.weight * hidden_states.to(input_dtype)
591
+
592
+ def extra_repr(self):
593
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
594
+
595
+
596
+ class NemotronHMLP(nn.Module):
597
+ def __init__(self, config, intermediate_size=None, **kwargs):
598
+ super().__init__()
599
+ self.config = config
600
+ self.hidden_size = config.hidden_size
601
+ self.intermediate_size = intermediate_size or config.intermediate_size
602
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
603
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
604
+ self.act_fn = ACT2FN[config.mlp_hidden_act]
605
+
606
+ def forward(self, x):
607
+ return self.down_proj(self.act_fn(self.up_proj(x)))
608
+
609
+
610
+ @use_experts_implementation(has_gate=False)
611
+ class NemotronHExperts(nn.Module):
612
+ """
613
+ Collection of expert weights stored as 3D tensors.
614
+
615
+ **Architecture Note**: Unlike Mixtral or DeepSeek which use gated MLPs,
616
+ NemotronH uses a standard MLP architecture with only up_proj and down_proj
617
+ """
618
+
619
+ def __init__(self, config):
620
+ super().__init__()
621
+ self.num_experts = config.n_routed_experts
622
+ self.hidden_dim = config.hidden_size
623
+ self.intermediate_dim = config.moe_intermediate_size
624
+
625
+ # Determine input/output dimension based on whether latent projection is used
626
+ input_dim = config.moe_latent_size if config.moe_latent_size is not None else config.hidden_size
627
+
628
+ # All expert weights stored as 3D tensors: (num_experts, out_dim, in_dim)
629
+ # up_proj: (num_experts, intermediate_dim, input_dim)
630
+ self.up_proj = nn.Parameter(torch.empty(self.num_experts, self.intermediate_dim, input_dim))
631
+ # down_proj: (num_experts, input_dim, intermediate_dim)
632
+ self.down_proj = nn.Parameter(torch.empty(self.num_experts, input_dim, self.intermediate_dim))
633
+
634
+ self.act_fn = ACT2FN[config.mlp_hidden_act]
635
+
636
+ def forward(self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor):
637
+ final_hidden_states = torch.zeros_like(hidden_states, dtype=top_k_weights.dtype)
638
+
639
+ # Create expert mask to identify which tokens go to which experts
640
+ with torch.no_grad():
641
+ expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
642
+ expert_mask = expert_mask.permute(2, 1, 0) # (num_experts, num_experts_per_tok, num_tokens)
643
+ # Only iterate over experts that have at least one token assigned
644
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero().squeeze(-1)
645
+
646
+ for expert_idx in expert_hit:
647
+ expert_idx = expert_idx.item()
648
+ # Find which tokens are routed to this expert
649
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
650
+
651
+ if token_idx.numel() == 0:
652
+ continue
653
+
654
+ # Get input for this expert
655
+ current_state = hidden_states[token_idx]
656
+
657
+ # Expert computation: down_proj(act_fn(up_proj(x)))
658
+ # No gating mechanism unlike Mixtral which uses: down_proj(act_fn(gate_proj(x)) * up_proj(x))
659
+ current_hidden_states = torch.nn.functional.linear(current_state, self.up_proj[expert_idx])
660
+ current_hidden_states = self.act_fn(current_hidden_states)
661
+ current_hidden_states = torch.nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
662
+
663
+ # Apply routing weights
664
+ current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
665
+
666
+ # Accumulate into final output
667
+ final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
668
+
669
+ return final_hidden_states.to(hidden_states.dtype)
670
+
671
+
672
+ class NemotronHMoE(nn.Module):
673
+ """
674
+ Mixture-of-Experts (MoE) module for NemotronH.
675
+
676
+ Unique architectures:
677
+ - Uses non-gated MLP experts (NemotronHExperts) instead of gated experts
678
+ - Adds optional latent projection for computational efficiency
679
+ """
680
+
681
+ def __init__(self, config, layer_idx: int | None = None):
682
+ super().__init__()
683
+ self.config = config
684
+
685
+ # Replace with NemotronH-specific experts (non-gated MLP architecture)
686
+ self.experts = NemotronHExperts(config)
687
+ self.gate = NemotronHTopkRouter(config)
688
+
689
+ # Override shared_experts to use NemotronHMLP with correct intermediate size
690
+ self.shared_experts = NemotronHMLP(config=config, intermediate_size=config.moe_shared_expert_intermediate_size)
691
+ self.n_routed_experts = config.n_routed_experts
692
+ self.n_group = config.n_group
693
+ self.topk_group = config.topk_group
694
+ self.norm_topk_prob = config.norm_topk_prob
695
+ self.routed_scaling_factor = config.routed_scaling_factor
696
+ self.top_k = config.num_experts_per_tok
697
+
698
+ # NemotronH-specific latent projection layers
699
+ if config.moe_latent_size is not None:
700
+ self.fc1_latent_proj = nn.Linear(config.hidden_size, config.moe_latent_size, bias=config.mlp_bias)
701
+ self.fc2_latent_proj = nn.Linear(config.moe_latent_size, config.hidden_size, bias=config.mlp_bias)
702
+ else:
703
+ self.fc1_latent_proj = nn.Identity()
704
+ self.fc2_latent_proj = nn.Identity()
705
+
706
+ def route_tokens_to_experts(self, router_logits):
707
+ router_logits = router_logits.sigmoid()
708
+ router_logits_for_choice = router_logits + self.gate.e_score_correction_bias
709
+ group_scores = (
710
+ router_logits_for_choice.view(-1, self.n_group, self.n_routed_experts // self.n_group)
711
+ .topk(2, dim=-1)[0]
712
+ .sum(dim=-1)
713
+ )
714
+ group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
715
+ group_mask = torch.zeros_like(group_scores)
716
+ group_mask.scatter_(1, group_idx, 1)
717
+ score_mask = (
718
+ group_mask.unsqueeze(-1)
719
+ .expand(-1, self.n_group, self.n_routed_experts // self.n_group)
720
+ .reshape(-1, self.n_routed_experts)
721
+ )
722
+ scores_for_choice = router_logits_for_choice.masked_fill(~score_mask.bool(), float("-inf"))
723
+ topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
724
+ topk_weights = router_logits.gather(1, topk_indices)
725
+ if self.norm_topk_prob:
726
+ denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
727
+ topk_weights /= denominator
728
+ topk_weights = topk_weights * self.routed_scaling_factor
729
+ return topk_indices, topk_weights
730
+
731
+ def forward(self, hidden_states):
732
+ residuals = hidden_states
733
+ orig_shape = hidden_states.shape
734
+ router_logits = self.gate(hidden_states)
735
+ topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
736
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
737
+
738
+ # NemotronH-specific: latent projection
739
+ hidden_states = self.fc1_latent_proj(hidden_states)
740
+ hidden_states = self.experts(hidden_states, topk_indices, topk_weights)
741
+ hidden_states = self.fc2_latent_proj(hidden_states)
742
+
743
+ hidden_states = hidden_states.view(*orig_shape)
744
+ hidden_states = hidden_states + self.shared_experts(residuals)
745
+ return hidden_states
746
+
747
+
748
+ class NemotronHTopkRouter(nn.Module):
749
+ def __init__(self, config):
750
+ super().__init__()
751
+ self.config = config
752
+ self.n_routed_experts = config.n_routed_experts
753
+
754
+ self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size)))
755
+ self.register_buffer("e_score_correction_bias", torch.zeros(self.n_routed_experts))
756
+
757
+ def forward(self, hidden_states):
758
+ hidden_states = hidden_states.view(-1, self.config.hidden_size)
759
+ router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
760
+ return router_logits
761
+
762
+
763
+ def rotate_half(x):
764
+ """Rotates half the hidden dims of the input."""
765
+ x1 = x[..., : x.shape[-1] // 2]
766
+ x2 = x[..., x.shape[-1] // 2 :]
767
+ return torch.cat((-x2, x1), dim=-1)
768
+
769
+
770
+ @use_kernel_func_from_hub("rotary_pos_emb")
771
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
772
+ """Applies Rotary Position Embedding to the query and key tensors.
773
+
774
+ Args:
775
+ q (`torch.Tensor`): The query tensor.
776
+ k (`torch.Tensor`): The key tensor.
777
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
778
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
779
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
780
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
781
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
782
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
783
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
784
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
785
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
786
+ Returns:
787
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
788
+ """
789
+ cos = cos.unsqueeze(unsqueeze_dim)
790
+ sin = sin.unsqueeze(unsqueeze_dim)
791
+ q_embed = (q * cos) + (rotate_half(q) * sin)
792
+ k_embed = (k * cos) + (rotate_half(k) * sin)
793
+ return q_embed, k_embed
794
+
795
+
796
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
797
+ """
798
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
799
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
800
+ """
801
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
802
+ if n_rep == 1:
803
+ return hidden_states
804
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
805
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
806
+
807
+
808
+ def eager_attention_forward(
809
+ module: nn.Module,
810
+ query: torch.Tensor,
811
+ key: torch.Tensor,
812
+ value: torch.Tensor,
813
+ attention_mask: torch.Tensor | None,
814
+ scaling: float,
815
+ dropout: float = 0.0,
816
+ **kwargs: Unpack[TransformersKwargs],
817
+ ):
818
+ key_states = repeat_kv(key, module.num_key_value_groups)
819
+ value_states = repeat_kv(value, module.num_key_value_groups)
820
+
821
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
822
+ if attention_mask is not None:
823
+ attn_weights = attn_weights + attention_mask
824
+
825
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
826
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
827
+ attn_output = torch.matmul(attn_weights, value_states)
828
+ attn_output = attn_output.transpose(1, 2).contiguous()
829
+
830
+ return attn_output, attn_weights
831
+
832
+
833
+ @use_kernelized_func(apply_rotary_pos_emb)
834
+ class NemotronHAttention(nn.Module):
835
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
836
+
837
+ def __init__(self, config: NemotronHConfig, layer_idx: int):
838
+ super().__init__()
839
+ self.config = config
840
+ self.layer_idx = layer_idx
841
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
842
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
843
+ self.scaling = self.head_dim**-0.5
844
+ self.attention_dropout = config.attention_dropout
845
+ self.is_causal = True
846
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
847
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
848
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
849
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
850
+
851
+ def forward(
852
+ self,
853
+ hidden_states: torch.Tensor,
854
+ attention_mask: torch.Tensor | None = None,
855
+ past_key_values: Cache | None = None,
856
+ **kwargs: Unpack[TransformersKwargs],
857
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
858
+ input_shape = hidden_states.shape[:-1]
859
+ hidden_shape = (*input_shape, -1, self.head_dim)
860
+
861
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
862
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
863
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
864
+
865
+ if past_key_values is not None:
866
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
867
+
868
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
869
+ self.config._attn_implementation, eager_attention_forward
870
+ )
871
+
872
+ attn_output, attn_weights = attention_interface(
873
+ self,
874
+ query_states,
875
+ key_states,
876
+ value_states,
877
+ attention_mask,
878
+ dropout=0.0 if not self.training else self.attention_dropout,
879
+ scaling=self.scaling,
880
+ **kwargs,
881
+ )
882
+
883
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
884
+ attn_output = self.o_proj(attn_output)
885
+ return attn_output, attn_weights
886
+
887
+
888
+ MIXER_TYPES = {
889
+ "mamba": NemotronHMamba2Mixer,
890
+ "attention": NemotronHAttention,
891
+ "moe": NemotronHMoE,
892
+ "mlp": NemotronHMLP,
893
+ }
894
+
895
+
896
+ class NemotronHBlock(GradientCheckpointingLayer):
897
+ """
898
+ A single transformer block in the NemotronH model.
899
+
900
+ This block can contain different types of mixers (Mamba, Attention, MLP, or MoE)
901
+ depending on the configuration. Each block applies pre-normalization followed by
902
+ the mixer, then adds a residual connection.
903
+
904
+ Args:
905
+ config (`NemotronHConfig`):
906
+ Model configuration specifying the block architecture.
907
+ layer_idx (`int`):
908
+ Index of this block in the model. Used to determine the block type from
909
+ `config.layers_block_type[layer_idx]`.
910
+ """
911
+
912
+ def __init__(self, config, layer_idx):
913
+ super().__init__()
914
+ self.config = config
915
+ self.layer_idx = layer_idx
916
+ self.norm = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
917
+
918
+ self.block_type = config.layers_block_type[layer_idx]
919
+ self.mixer = MIXER_TYPES[self.block_type](config, layer_idx=layer_idx)
920
+
921
+ def forward(
922
+ self,
923
+ hidden_states,
924
+ past_key_values: Cache | None = None,
925
+ attention_mask: torch.Tensor | None = None,
926
+ position_ids: torch.LongTensor | None = None,
927
+ use_cache: bool | None = False,
928
+ **kwargs: Unpack[TransformersKwargs],
929
+ ):
930
+ residual = hidden_states
931
+ hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
932
+
933
+ if self.block_type == "mamba":
934
+ hidden_states = self.mixer(hidden_states, cache_params=past_key_values, attention_mask=attention_mask)
935
+ elif self.block_type == "attention":
936
+ hidden_states, _ = self.mixer(
937
+ hidden_states=hidden_states,
938
+ past_key_values=past_key_values,
939
+ attention_mask=attention_mask,
940
+ position_ids=position_ids,
941
+ user_cache=use_cache,
942
+ **kwargs,
943
+ )
944
+ else:
945
+ hidden_states = self.mixer(hidden_states)
946
+
947
+ hidden_states = residual + hidden_states
948
+
949
+ return hidden_states
950
+
951
+
952
+ class NemotronHPreTrainedModel(PreTrainedModel):
953
+ config: NemotronHConfig
954
+ base_model_prefix = "model"
955
+ supports_gradient_checkpointing = True
956
+ _no_split_modules = ["NemotronHBlock"]
957
+ _skip_keys_device_placement = ["past_key_values"]
958
+ _supports_flash_attn = True
959
+ _supports_flash_attn_2 = True
960
+ _supports_sdpa = True
961
+ _supports_flex_attn = True
962
+ _is_stateful = True
963
+ _can_record_outputs = {
964
+ "hidden_states": NemotronHBlock,
965
+ "attentions": NemotronHAttention,
966
+ }
967
+ _keep_in_fp32_modules_strict = [
968
+ "e_score_correction_bias",
969
+ ]
970
+ _keys_to_ignore_on_load_unexpected = [r"mtp.*"]
971
+
972
+ @torch.no_grad()
973
+ def _init_weights(self, module):
974
+ """Initialize the weights."""
975
+ super()._init_weights(module)
976
+ if isinstance(module, NemotronHMamba2Mixer):
977
+ # Only re-initialise params that were NOT loaded from a checkpoint.
978
+ # `_is_hf_initialized` is set by `from_pretrained` on each loaded
979
+ # parameter; without this guard a post-load safety pass of
980
+ # `_init_weights` would overwrite checkpoint values of
981
+ # A_log / D / dt_bias with fresh random draws.
982
+ if not getattr(module.A_log, "_is_hf_initialized", False):
983
+ A = torch.arange(1, self.config.mamba_num_heads + 1)
984
+ init.copy_(module.A_log, torch.log(A))
985
+ if not getattr(module.D, "_is_hf_initialized", False):
986
+ init.ones_(module.D)
987
+ if not getattr(module.dt_bias, "_is_hf_initialized", False):
988
+ dt = torch.exp(
989
+ torch.rand(self.config.mamba_num_heads)
990
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
991
+ + math.log(self.config.time_step_min)
992
+ ).clamp(min=self.config.time_step_floor)
993
+
994
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
995
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
996
+ with torch.no_grad():
997
+ init.copy_(module.dt_bias, inv_dt)
998
+ elif isinstance(module, NemotronHTopkRouter):
999
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
1000
+ init.zeros_(module.e_score_correction_bias)
1001
+ elif isinstance(module, NemotronHExperts):
1002
+ # Initialize expert weights
1003
+ init.normal_(module.up_proj, mean=0.0, std=self.config.initializer_range)
1004
+ init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
1005
+
1006
+ if isinstance(module, nn.Linear):
1007
+ if module.bias is not None:
1008
+ if not getattr(module.bias, "_is_hf_initialized", False):
1009
+ init.zeros_(module.bias)
1010
+ elif isinstance(module, nn.Embedding):
1011
+ init.normal_(module.weight, std=self.config.initializer_range)
1012
+
1013
+ if self.config.rescale_prenorm_residual:
1014
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
1015
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
1016
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
1017
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
1018
+ #
1019
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
1020
+ for name, p in module.named_parameters():
1021
+ if name == "out_proj.weight":
1022
+ # Skip checkpoint-loaded weights so a post-load safety
1023
+ # pass of `_init_weights` doesn't silently overwrite them.
1024
+ if getattr(p, "_is_hf_initialized", False):
1025
+ continue
1026
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
1027
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
1028
+ init.kaiming_uniform_(p, a=math.sqrt(5))
1029
+ with torch.no_grad():
1030
+ p_new = p / math.sqrt(self.config.num_hidden_layers)
1031
+ init.copy_(p, p_new)
1032
+
1033
+
1034
+ class NemotronHModel(NemotronHPreTrainedModel):
1035
+ def __init__(self, config):
1036
+ super().__init__(config)
1037
+
1038
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
1039
+ self.layers = nn.ModuleList([NemotronHBlock(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
1040
+
1041
+ self.norm_f = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
1042
+ # Initialize weights and apply final processing
1043
+ self.post_init()
1044
+
1045
+ def get_input_embeddings(self):
1046
+ return self.embeddings
1047
+
1048
+ def set_input_embeddings(self, new_embeddings):
1049
+ self.embeddings = new_embeddings
1050
+
1051
+ @merge_with_config_defaults
1052
+ @capture_outputs
1053
+ def forward(
1054
+ self,
1055
+ input_ids: torch.LongTensor | None = None,
1056
+ inputs_embeds: torch.LongTensor | None = None,
1057
+ position_ids: torch.LongTensor | None = None,
1058
+ past_key_values: Cache | None = None,
1059
+ use_cache: bool | None = None,
1060
+ attention_mask: torch.Tensor | None = None,
1061
+ **kwargs: Unpack[TransformersKwargs],
1062
+ ) -> tuple | BaseModelOutputWithPast:
1063
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
1064
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1065
+
1066
+ if inputs_embeds is None:
1067
+ inputs_embeds = self.embeddings(input_ids)
1068
+
1069
+ if use_cache and past_key_values is None:
1070
+ past_key_values = DynamicCache(config=self.config)
1071
+
1072
+ hidden_states = inputs_embeds
1073
+
1074
+ if position_ids is None:
1075
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1076
+ position_ids = torch.arange(hidden_states.shape[1], device=hidden_states.device) + past_seen_tokens
1077
+ position_ids = position_ids.unsqueeze(0)
1078
+
1079
+ causal_mask = create_causal_mask(
1080
+ config=self.config,
1081
+ input_embeds=inputs_embeds,
1082
+ attention_mask=attention_mask,
1083
+ past_key_values=past_key_values,
1084
+ position_ids=position_ids,
1085
+ )
1086
+ mamba_mask = self._update_mamba_mask(attention_mask, past_key_values)
1087
+
1088
+ # Map block types to their corresponding masks
1089
+ block_type_to_mask = {
1090
+ "mamba": mamba_mask,
1091
+ "attention": causal_mask,
1092
+ "moe": None,
1093
+ "mlp": None,
1094
+ }
1095
+
1096
+ for layer_idx, mixer_block in enumerate(self.layers):
1097
+ layer_mask = block_type_to_mask[mixer_block.block_type]
1098
+
1099
+ hidden_states = mixer_block(
1100
+ hidden_states,
1101
+ attention_mask=layer_mask,
1102
+ position_ids=position_ids,
1103
+ past_key_values=past_key_values,
1104
+ use_cache=use_cache,
1105
+ **kwargs,
1106
+ )
1107
+
1108
+ hidden_states = self.norm_f(hidden_states)
1109
+
1110
+ return BaseModelOutputWithPast(
1111
+ last_hidden_state=hidden_states,
1112
+ past_key_values=past_key_values if use_cache else None,
1113
+ )
1114
+
1115
+ def _update_mamba_mask(self, attention_mask, past_key_values):
1116
+ """
1117
+ No need for zeroing states when
1118
+ 1. Cached forward
1119
+ 2. Attending to all inputs
1120
+ """
1121
+ mamba_mask = attention_mask
1122
+ if (past_key_values is not None and past_key_values.has_previous_state()) or (
1123
+ attention_mask is not None and torch.all(attention_mask == 1)
1124
+ ):
1125
+ mamba_mask = None
1126
+ return mamba_mask
1127
+
1128
+
1129
+ # Adapted from transformers.models.jamba.modeling_jamba.JambaForCausalLM with Jamba->NemotronH, JAMBA->NEMOTRON_H
1130
+ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
1131
+ _tied_weights_keys = {}
1132
+
1133
+ def __init__(self, config: NemotronHConfig):
1134
+ super().__init__(config)
1135
+ self.model = NemotronHModel(config)
1136
+ self.vocab_size = config.vocab_size
1137
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1138
+
1139
+ # Initialize weights and apply final processing
1140
+ self.post_init()
1141
+
1142
+ @can_return_tuple
1143
+ @auto_docstring
1144
+ def forward(
1145
+ self,
1146
+ input_ids: torch.LongTensor | None = None,
1147
+ attention_mask: torch.Tensor | None = None,
1148
+ position_ids: torch.LongTensor | None = None,
1149
+ past_key_values: Cache | None = None,
1150
+ inputs_embeds: torch.FloatTensor | None = None,
1151
+ labels: torch.LongTensor | None = None,
1152
+ use_cache: bool | None = None,
1153
+ logits_to_keep: int | torch.Tensor = 0,
1154
+ **kwargs,
1155
+ ) -> tuple | CausalLMOutputWithPast:
1156
+ r"""
1157
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1158
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1159
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1160
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1161
+
1162
+ Example:
1163
+
1164
+ ```python
1165
+ >>> from transformers import AutoTokenizer, NemotronHForCausalLM
1166
+
1167
+ >>> model = NemotronHForCausalLM.from_pretrained("Zyphra/NemotronH-7B-v1")
1168
+ >>> tokenizer = AutoTokenizer.from_pretrained("Zyphra/NemotronH-7B-v1")
1169
+
1170
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1171
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1172
+
1173
+ >>> # Generate
1174
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1175
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1176
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1177
+ ```"""
1178
+ outputs = self.model(
1179
+ input_ids=input_ids,
1180
+ attention_mask=attention_mask,
1181
+ position_ids=position_ids,
1182
+ past_key_values=past_key_values,
1183
+ inputs_embeds=inputs_embeds,
1184
+ use_cache=use_cache,
1185
+ **kwargs,
1186
+ )
1187
+
1188
+ hidden_states = outputs[0]
1189
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1190
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1191
+ logits = self.lm_head(hidden_states[:, slice_indices, :]).float()
1192
+
1193
+ loss = None
1194
+ if labels is not None:
1195
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
1196
+
1197
+ return CausalLMOutputWithPast(
1198
+ loss=loss,
1199
+ logits=logits,
1200
+ past_key_values=outputs.past_key_values,
1201
+ hidden_states=outputs.hidden_states,
1202
+ attentions=outputs.attentions,
1203
+ )
1204
+
1205
+ def prepare_inputs_for_generation(
1206
+ self,
1207
+ input_ids,
1208
+ past_key_values=None,
1209
+ attention_mask=None,
1210
+ inputs_embeds=None,
1211
+ position_ids=None,
1212
+ use_cache=True,
1213
+ is_first_iteration=False,
1214
+ **kwargs,
1215
+ ):
1216
+ kwargs["logits_to_keep"] = self.config.num_logits_to_keep
1217
+ model_inputs = super().prepare_inputs_for_generation(
1218
+ input_ids,
1219
+ past_key_values=past_key_values,
1220
+ attention_mask=attention_mask,
1221
+ inputs_embeds=inputs_embeds,
1222
+ position_ids=position_ids,
1223
+ use_cache=use_cache,
1224
+ is_first_iteration=is_first_iteration,
1225
+ **kwargs,
1226
+ )
1227
+
1228
+ return model_inputs
1229
+
1230
+
1231
+ __all__ = ["NemotronHPreTrainedModel", "NemotronHModel", "NemotronHForCausalLM"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nemotron_h/modular_nemotron_h.py ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+
20
+ import torch
21
+ from torch import nn
22
+
23
+ from ... import initialization as init
24
+ from ...activations import ACT2FN
25
+ from ...cache_utils import Cache, DynamicCache
26
+ from ...integrations import use_experts_implementation
27
+ from ...masking_utils import create_causal_mask
28
+ from ...modeling_layers import GradientCheckpointingLayer
29
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
30
+ from ...modeling_utils import PreTrainedModel
31
+ from ...models.deepseek_v3.modeling_deepseek_v3 import DeepseekV3MoE, DeepseekV3TopkRouter
32
+ from ...models.jamba.modeling_jamba import JambaAttention
33
+ from ...models.llama.modeling_llama import LlamaRMSNorm
34
+ from ...models.nemotron.modeling_nemotron import NemotronMLP
35
+ from ...models.zamba.modeling_zamba import ZambaForCausalLM
36
+ from ...models.zamba2.modeling_zamba2 import Zamba2MambaMixer, Zamba2RMSNormGated
37
+ from ...processing_utils import Unpack
38
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
39
+ from ...utils.generic import merge_with_config_defaults
40
+ from ...utils.output_capturing import capture_outputs
41
+ from .configuration_nemotron_h import NemotronHConfig
42
+
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+ is_fast_path_available = False
47
+
48
+
49
+ class NemotronHMamba2Mixer(Zamba2MambaMixer):
50
+ def __init__(self, config: NemotronHConfig, layer_idx: int | None = None):
51
+ super().__init__(config, layer_idx)
52
+ self.ssm_state_size = config.ssm_state_size
53
+ self.conv_kernel_size = config.conv_kernel
54
+ self.intermediate_size = config.mamba_num_heads * config.mamba_head_dim
55
+ self.use_conv_bias = config.use_conv_bias
56
+ self.activation = config.mamba_hidden_act
57
+ self.act = ACT2FN[config.mamba_hidden_act]
58
+ self.use_mem_eff_path = True
59
+
60
+ self.n_groups = config.n_groups
61
+ self.head_dim = config.mamba_head_dim
62
+ self.num_heads = config.mamba_num_heads
63
+
64
+ self.conv1d = nn.Conv1d(
65
+ in_channels=self.conv_dim,
66
+ out_channels=self.conv_dim,
67
+ bias=config.use_conv_bias,
68
+ kernel_size=self.conv_kernel_size,
69
+ groups=self.conv_dim,
70
+ padding=self.conv_kernel_size - 1,
71
+ )
72
+
73
+ # projection of the input hidden states
74
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
75
+
76
+ self.in_proj = nn.Linear(
77
+ self.hidden_size,
78
+ projection_size,
79
+ bias=config.use_bias,
80
+ )
81
+
82
+ self.norm = Zamba2RMSNormGated(
83
+ self.intermediate_size, group_size=self.intermediate_size // self.n_groups, eps=config.layer_norm_epsilon
84
+ )
85
+
86
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
87
+
88
+ def forward(
89
+ self,
90
+ hidden_states,
91
+ cache_params: Cache | None = None,
92
+ attention_mask: torch.Tensor | None = None,
93
+ **kwargs,
94
+ ):
95
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type and not is_torchdynamo_compiling():
96
+ # Use cuda stream to avoid NaN when using multiple GPUs, which is caused by multi-GPU synchronization issue.
97
+ # Mamba might launch on the default cuda stream that not strictly respect the current Pytorch cuda stream.
98
+ # This leads to kernel reading uninitialized memory before the data transfer is complete.
99
+ with torch.cuda.stream(torch.cuda.default_stream(hidden_states.device)):
100
+ return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
101
+
102
+ return self.torch_forward(hidden_states, cache_params, attention_mask)
103
+
104
+
105
+ class NemotronHRMSNorm(LlamaRMSNorm):
106
+ pass
107
+
108
+
109
+ class NemotronHMLP(NemotronMLP, nn.Module):
110
+ def __init__(self, config, intermediate_size=None, **kwargs):
111
+ nn.Module.__init__()
112
+ self.config = config
113
+ self.hidden_size = config.hidden_size
114
+ self.intermediate_size = intermediate_size or config.intermediate_size
115
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
116
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
117
+ self.act_fn = ACT2FN[config.mlp_hidden_act]
118
+
119
+
120
+ @use_experts_implementation(has_gate=False)
121
+ class NemotronHExperts(nn.Module):
122
+ """
123
+ Collection of expert weights stored as 3D tensors.
124
+
125
+ **Architecture Note**: Unlike Mixtral or DeepSeek which use gated MLPs,
126
+ NemotronH uses a standard MLP architecture with only up_proj and down_proj
127
+ """
128
+
129
+ def __init__(self, config):
130
+ super().__init__()
131
+ self.num_experts = config.n_routed_experts
132
+ self.hidden_dim = config.hidden_size
133
+ self.intermediate_dim = config.moe_intermediate_size
134
+
135
+ # Determine input/output dimension based on whether latent projection is used
136
+ input_dim = config.moe_latent_size if config.moe_latent_size is not None else config.hidden_size
137
+
138
+ # All expert weights stored as 3D tensors: (num_experts, out_dim, in_dim)
139
+ # up_proj: (num_experts, intermediate_dim, input_dim)
140
+ self.up_proj = nn.Parameter(torch.empty(self.num_experts, self.intermediate_dim, input_dim))
141
+ # down_proj: (num_experts, input_dim, intermediate_dim)
142
+ self.down_proj = nn.Parameter(torch.empty(self.num_experts, input_dim, self.intermediate_dim))
143
+
144
+ self.act_fn = ACT2FN[config.mlp_hidden_act]
145
+
146
+ def forward(self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor):
147
+ final_hidden_states = torch.zeros_like(hidden_states, dtype=top_k_weights.dtype)
148
+
149
+ # Create expert mask to identify which tokens go to which experts
150
+ with torch.no_grad():
151
+ expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
152
+ expert_mask = expert_mask.permute(2, 1, 0) # (num_experts, num_experts_per_tok, num_tokens)
153
+ # Only iterate over experts that have at least one token assigned
154
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero().squeeze(-1)
155
+
156
+ for expert_idx in expert_hit:
157
+ expert_idx = expert_idx.item()
158
+ # Find which tokens are routed to this expert
159
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
160
+
161
+ if token_idx.numel() == 0:
162
+ continue
163
+
164
+ # Get input for this expert
165
+ current_state = hidden_states[token_idx]
166
+
167
+ # Expert computation: down_proj(act_fn(up_proj(x)))
168
+ # No gating mechanism unlike Mixtral which uses: down_proj(act_fn(gate_proj(x)) * up_proj(x))
169
+ current_hidden_states = torch.nn.functional.linear(current_state, self.up_proj[expert_idx])
170
+ current_hidden_states = self.act_fn(current_hidden_states)
171
+ current_hidden_states = torch.nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
172
+
173
+ # Apply routing weights
174
+ current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
175
+
176
+ # Accumulate into final output
177
+ final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
178
+
179
+ return final_hidden_states.to(hidden_states.dtype)
180
+
181
+
182
+ class NemotronHMoE(DeepseekV3MoE):
183
+ """
184
+ Mixture-of-Experts (MoE) module for NemotronH.
185
+
186
+ Unique architectures:
187
+ - Uses non-gated MLP experts (NemotronHExperts) instead of gated experts
188
+ - Adds optional latent projection for computational efficiency
189
+ """
190
+
191
+ def __init__(self, config, layer_idx: int | None = None):
192
+ super().__init__(config)
193
+
194
+ # Replace with NemotronH-specific experts (non-gated MLP architecture)
195
+ self.experts = NemotronHExperts(config)
196
+ self.gate = NemotronHTopkRouter(config)
197
+
198
+ # Override shared_experts to use NemotronHMLP with correct intermediate size
199
+ self.shared_experts = NemotronHMLP(config=config, intermediate_size=config.moe_shared_expert_intermediate_size)
200
+
201
+ # NemotronH-specific latent projection layers
202
+ if config.moe_latent_size is not None:
203
+ self.fc1_latent_proj = nn.Linear(config.hidden_size, config.moe_latent_size, bias=config.mlp_bias)
204
+ self.fc2_latent_proj = nn.Linear(config.moe_latent_size, config.hidden_size, bias=config.mlp_bias)
205
+ else:
206
+ self.fc1_latent_proj = nn.Identity()
207
+ self.fc2_latent_proj = nn.Identity()
208
+
209
+ def forward(self, hidden_states):
210
+ residuals = hidden_states
211
+ orig_shape = hidden_states.shape
212
+ router_logits = self.gate(hidden_states)
213
+ topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
214
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
215
+
216
+ # NemotronH-specific: latent projection
217
+ hidden_states = self.fc1_latent_proj(hidden_states)
218
+ hidden_states = self.experts(hidden_states, topk_indices, topk_weights)
219
+ hidden_states = self.fc2_latent_proj(hidden_states)
220
+
221
+ hidden_states = hidden_states.view(*orig_shape)
222
+ hidden_states = hidden_states + self.shared_experts(residuals)
223
+ return hidden_states
224
+
225
+
226
+ class NemotronHTopkRouter(DeepseekV3TopkRouter):
227
+ pass
228
+
229
+
230
+ class NemotronHAttention(JambaAttention):
231
+ def forward(
232
+ self,
233
+ hidden_states: torch.Tensor,
234
+ attention_mask: torch.Tensor | None = None,
235
+ past_key_values: Cache | None = None,
236
+ **kwargs: Unpack[TransformersKwargs],
237
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
238
+ return super().forward(hidden_states, attention_mask, past_key_values, **kwargs)
239
+
240
+
241
+ MIXER_TYPES = {
242
+ "mamba": NemotronHMamba2Mixer,
243
+ "attention": NemotronHAttention,
244
+ "moe": NemotronHMoE,
245
+ "mlp": NemotronHMLP,
246
+ }
247
+
248
+
249
+ class NemotronHBlock(GradientCheckpointingLayer):
250
+ """
251
+ A single transformer block in the NemotronH model.
252
+
253
+ This block can contain different types of mixers (Mamba, Attention, MLP, or MoE)
254
+ depending on the configuration. Each block applies pre-normalization followed by
255
+ the mixer, then adds a residual connection.
256
+
257
+ Args:
258
+ config (`NemotronHConfig`):
259
+ Model configuration specifying the block architecture.
260
+ layer_idx (`int`):
261
+ Index of this block in the model. Used to determine the block type from
262
+ `config.layers_block_type[layer_idx]`.
263
+ """
264
+
265
+ def __init__(self, config, layer_idx):
266
+ super().__init__()
267
+ self.config = config
268
+ self.layer_idx = layer_idx
269
+ self.norm = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
270
+
271
+ self.block_type = config.layers_block_type[layer_idx]
272
+ self.mixer = MIXER_TYPES[self.block_type](config, layer_idx=layer_idx)
273
+
274
+ def forward(
275
+ self,
276
+ hidden_states,
277
+ past_key_values: Cache | None = None,
278
+ attention_mask: torch.Tensor | None = None,
279
+ position_ids: torch.LongTensor | None = None,
280
+ use_cache: bool | None = False,
281
+ **kwargs: Unpack[TransformersKwargs],
282
+ ):
283
+ residual = hidden_states
284
+ hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
285
+
286
+ if self.block_type == "mamba":
287
+ hidden_states = self.mixer(hidden_states, cache_params=past_key_values, attention_mask=attention_mask)
288
+ elif self.block_type == "attention":
289
+ hidden_states, _ = self.mixer(
290
+ hidden_states=hidden_states,
291
+ past_key_values=past_key_values,
292
+ attention_mask=attention_mask,
293
+ position_ids=position_ids,
294
+ user_cache=use_cache,
295
+ **kwargs,
296
+ )
297
+ else:
298
+ hidden_states = self.mixer(hidden_states)
299
+
300
+ hidden_states = residual + hidden_states
301
+
302
+ return hidden_states
303
+
304
+
305
+ class NemotronHPreTrainedModel(PreTrainedModel):
306
+ config: NemotronHConfig
307
+ base_model_prefix = "model"
308
+ supports_gradient_checkpointing = True
309
+ _no_split_modules = ["NemotronHBlock"]
310
+ _skip_keys_device_placement = ["past_key_values"]
311
+ _supports_flash_attn = True
312
+ _supports_flash_attn_2 = True
313
+ _supports_sdpa = True
314
+ _supports_flex_attn = True
315
+ _is_stateful = True
316
+ _can_record_outputs = {
317
+ "hidden_states": NemotronHBlock,
318
+ "attentions": NemotronHAttention,
319
+ }
320
+ _keep_in_fp32_modules_strict = [
321
+ "e_score_correction_bias",
322
+ ]
323
+ _keys_to_ignore_on_load_unexpected = [r"mtp.*"]
324
+
325
+ @torch.no_grad()
326
+ def _init_weights(self, module):
327
+ """Initialize the weights."""
328
+ super()._init_weights(module)
329
+ if isinstance(module, NemotronHMamba2Mixer):
330
+ # Only re-initialise params that were NOT loaded from a checkpoint.
331
+ # `_is_hf_initialized` is set by `from_pretrained` on each loaded
332
+ # parameter; without this guard a post-load safety pass of
333
+ # `_init_weights` would overwrite checkpoint values of
334
+ # A_log / D / dt_bias with fresh random draws.
335
+ if not getattr(module.A_log, "_is_hf_initialized", False):
336
+ A = torch.arange(1, self.config.mamba_num_heads + 1)
337
+ init.copy_(module.A_log, torch.log(A))
338
+ if not getattr(module.D, "_is_hf_initialized", False):
339
+ init.ones_(module.D)
340
+ if not getattr(module.dt_bias, "_is_hf_initialized", False):
341
+ dt = torch.exp(
342
+ torch.rand(self.config.mamba_num_heads)
343
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
344
+ + math.log(self.config.time_step_min)
345
+ ).clamp(min=self.config.time_step_floor)
346
+
347
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
348
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
349
+ with torch.no_grad():
350
+ init.copy_(module.dt_bias, inv_dt)
351
+ elif isinstance(module, NemotronHTopkRouter):
352
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
353
+ init.zeros_(module.e_score_correction_bias)
354
+ elif isinstance(module, NemotronHExperts):
355
+ # Initialize expert weights
356
+ init.normal_(module.up_proj, mean=0.0, std=self.config.initializer_range)
357
+ init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
358
+
359
+ if isinstance(module, nn.Linear):
360
+ if module.bias is not None:
361
+ if not getattr(module.bias, "_is_hf_initialized", False):
362
+ init.zeros_(module.bias)
363
+ elif isinstance(module, nn.Embedding):
364
+ init.normal_(module.weight, std=self.config.initializer_range)
365
+
366
+ if self.config.rescale_prenorm_residual:
367
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
368
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
369
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
370
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
371
+ #
372
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
373
+ for name, p in module.named_parameters():
374
+ if name == "out_proj.weight":
375
+ # Skip checkpoint-loaded weights so a post-load safety
376
+ # pass of `_init_weights` doesn't silently overwrite them.
377
+ if getattr(p, "_is_hf_initialized", False):
378
+ continue
379
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
380
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
381
+ init.kaiming_uniform_(p, a=math.sqrt(5))
382
+ with torch.no_grad():
383
+ p_new = p / math.sqrt(self.config.num_hidden_layers)
384
+ init.copy_(p, p_new)
385
+
386
+
387
+ class NemotronHModel(NemotronHPreTrainedModel):
388
+ def __init__(self, config):
389
+ super().__init__(config)
390
+
391
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
392
+ self.layers = nn.ModuleList([NemotronHBlock(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
393
+
394
+ self.norm_f = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
395
+ # Initialize weights and apply final processing
396
+ self.post_init()
397
+
398
+ def get_input_embeddings(self):
399
+ return self.embeddings
400
+
401
+ def set_input_embeddings(self, new_embeddings):
402
+ self.embeddings = new_embeddings
403
+
404
+ @merge_with_config_defaults
405
+ @capture_outputs
406
+ def forward(
407
+ self,
408
+ input_ids: torch.LongTensor | None = None,
409
+ inputs_embeds: torch.LongTensor | None = None,
410
+ position_ids: torch.LongTensor | None = None,
411
+ past_key_values: Cache | None = None,
412
+ use_cache: bool | None = None,
413
+ attention_mask: torch.Tensor | None = None,
414
+ **kwargs: Unpack[TransformersKwargs],
415
+ ) -> tuple | BaseModelOutputWithPast:
416
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
417
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
418
+
419
+ if inputs_embeds is None:
420
+ inputs_embeds = self.embeddings(input_ids)
421
+
422
+ if use_cache and past_key_values is None:
423
+ past_key_values = DynamicCache(config=self.config)
424
+
425
+ hidden_states = inputs_embeds
426
+
427
+ if position_ids is None:
428
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
429
+ position_ids = torch.arange(hidden_states.shape[1], device=hidden_states.device) + past_seen_tokens
430
+ position_ids = position_ids.unsqueeze(0)
431
+
432
+ causal_mask = create_causal_mask(
433
+ config=self.config,
434
+ input_embeds=inputs_embeds,
435
+ attention_mask=attention_mask,
436
+ past_key_values=past_key_values,
437
+ position_ids=position_ids,
438
+ )
439
+ mamba_mask = self._update_mamba_mask(attention_mask, past_key_values)
440
+
441
+ # Map block types to their corresponding masks
442
+ block_type_to_mask = {
443
+ "mamba": mamba_mask,
444
+ "attention": causal_mask,
445
+ "moe": None,
446
+ "mlp": None,
447
+ }
448
+
449
+ for layer_idx, mixer_block in enumerate(self.layers):
450
+ layer_mask = block_type_to_mask[mixer_block.block_type]
451
+
452
+ hidden_states = mixer_block(
453
+ hidden_states,
454
+ attention_mask=layer_mask,
455
+ position_ids=position_ids,
456
+ past_key_values=past_key_values,
457
+ use_cache=use_cache,
458
+ **kwargs,
459
+ )
460
+
461
+ hidden_states = self.norm_f(hidden_states)
462
+
463
+ return BaseModelOutputWithPast(
464
+ last_hidden_state=hidden_states,
465
+ past_key_values=past_key_values if use_cache else None,
466
+ )
467
+
468
+ def _update_mamba_mask(self, attention_mask, past_key_values):
469
+ """
470
+ No need for zeroing states when
471
+ 1. Cached forward
472
+ 2. Attending to all inputs
473
+ """
474
+ mamba_mask = attention_mask
475
+ if (past_key_values is not None and past_key_values.has_previous_state()) or (
476
+ attention_mask is not None and torch.all(attention_mask == 1)
477
+ ):
478
+ mamba_mask = None
479
+ return mamba_mask
480
+
481
+
482
+ class NemotronHForCausalLM(ZambaForCausalLM):
483
+ _tied_weights_keys = {}
484
+
485
+ @can_return_tuple
486
+ @auto_docstring
487
+ def forward(
488
+ self,
489
+ input_ids: torch.LongTensor | None = None,
490
+ attention_mask: torch.Tensor | None = None,
491
+ position_ids: torch.LongTensor | None = None,
492
+ past_key_values: Cache | None = None,
493
+ inputs_embeds: torch.FloatTensor | None = None,
494
+ labels: torch.LongTensor | None = None,
495
+ use_cache: bool | None = None,
496
+ logits_to_keep: int | torch.Tensor = 0,
497
+ **kwargs,
498
+ ) -> tuple | CausalLMOutputWithPast:
499
+ outputs = self.model(
500
+ input_ids=input_ids,
501
+ attention_mask=attention_mask,
502
+ position_ids=position_ids,
503
+ past_key_values=past_key_values,
504
+ inputs_embeds=inputs_embeds,
505
+ use_cache=use_cache,
506
+ **kwargs,
507
+ )
508
+
509
+ hidden_states = outputs[0]
510
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
511
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
512
+ logits = self.lm_head(hidden_states[:, slice_indices, :]).float()
513
+
514
+ loss = None
515
+ if labels is not None:
516
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
517
+
518
+ return CausalLMOutputWithPast(
519
+ loss=loss,
520
+ logits=logits,
521
+ past_key_values=outputs.past_key_values,
522
+ hidden_states=outputs.hidden_states,
523
+ attentions=outputs.attentions,
524
+ )
525
+
526
+
527
+ __all__ = [
528
+ "NemotronHPreTrainedModel",
529
+ "NemotronHModel",
530
+ "NemotronHForCausalLM",
531
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nllb/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .tokenization_nllb import *
22
+ else:
23
+ import sys
24
+
25
+ _file = globals()["__file__"]
26
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nllb/tokenization_nllb.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The Facebook AI Research Team Authors and 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
+
16
+ from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors
17
+ from tokenizers.models import BPE
18
+
19
+ from ...tokenization_python import AddedToken, BatchEncoding
20
+ from ...tokenization_utils_tokenizers import TokenizersBackend
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}
28
+
29
+
30
+ FAIRSEQ_LANGUAGE_CODES = ['ace_Arab', 'ace_Latn', 'acm_Arab', 'acq_Arab', 'aeb_Arab', 'afr_Latn', 'ajp_Arab', 'aka_Latn', 'amh_Ethi', 'apc_Arab', 'arb_Arab', 'ars_Arab', 'ary_Arab', 'arz_Arab', 'asm_Beng', 'ast_Latn', 'awa_Deva', 'ayr_Latn', 'azb_Arab', 'azj_Latn', 'bak_Cyrl', 'bam_Latn', 'ban_Latn', 'bel_Cyrl', 'bem_Latn', 'ben_Beng', 'bho_Deva', 'bjn_Arab', 'bjn_Latn', 'bod_Tibt', 'bos_Latn', 'bug_Latn', 'bul_Cyrl', 'cat_Latn', 'ceb_Latn', 'ces_Latn', 'cjk_Latn', 'ckb_Arab', 'crh_Latn', 'cym_Latn', 'dan_Latn', 'deu_Latn', 'dik_Latn', 'dyu_Latn', 'dzo_Tibt', 'ell_Grek', 'eng_Latn', 'epo_Latn', 'est_Latn', 'eus_Latn', 'ewe_Latn', 'fao_Latn', 'pes_Arab', 'fij_Latn', 'fin_Latn', 'fon_Latn', 'fra_Latn', 'fur_Latn', 'fuv_Latn', 'gla_Latn', 'gle_Latn', 'glg_Latn', 'grn_Latn', 'guj_Gujr', 'hat_Latn', 'hau_Latn', 'heb_Hebr', 'hin_Deva', 'hne_Deva', 'hrv_Latn', 'hun_Latn', 'hye_Armn', 'ibo_Latn', 'ilo_Latn', 'ind_Latn', 'isl_Latn', 'ita_Latn', 'jav_Latn', 'jpn_Jpan', 'kab_Latn', 'kac_Latn', 'kam_Latn', 'kan_Knda', 'kas_Arab', 'kas_Deva', 'kat_Geor', 'knc_Arab', 'knc_Latn', 'kaz_Cyrl', 'kbp_Latn', 'kea_Latn', 'khm_Khmr', 'kik_Latn', 'kin_Latn', 'kir_Cyrl', 'kmb_Latn', 'kon_Latn', 'kor_Hang', 'kmr_Latn', 'lao_Laoo', 'lvs_Latn', 'lij_Latn', 'lim_Latn', 'lin_Latn', 'lit_Latn', 'lmo_Latn', 'ltg_Latn', 'ltz_Latn', 'lua_Latn', 'lug_Latn', 'luo_Latn', 'lus_Latn', 'mag_Deva', 'mai_Deva', 'mal_Mlym', 'mar_Deva', 'min_Latn', 'mkd_Cyrl', 'plt_Latn', 'mlt_Latn', 'mni_Beng', 'khk_Cyrl', 'mos_Latn', 'mri_Latn', 'zsm_Latn', 'mya_Mymr', 'nld_Latn', 'nno_Latn', 'nob_Latn', 'npi_Deva', 'nso_Latn', 'nus_Latn', 'nya_Latn', 'oci_Latn', 'gaz_Latn', 'ory_Orya', 'pag_Latn', 'pan_Guru', 'pap_Latn', 'pol_Latn', 'por_Latn', 'prs_Arab', 'pbt_Arab', 'quy_Latn', 'ron_Latn', 'run_Latn', 'rus_Cyrl', 'sag_Latn', 'san_Deva', 'sat_Beng', 'scn_Latn', 'shn_Mymr', 'sin_Sinh', 'slk_Latn', 'slv_Latn', 'smo_Latn', 'sna_Latn', 'snd_Arab', 'som_Latn', 'sot_Latn', 'spa_Latn', 'als_Latn', 'srd_Latn', 'srp_Cyrl', 'ssw_Latn', 'sun_Latn', 'swe_Latn', 'swh_Latn', 'szl_Latn', 'tam_Taml', 'tat_Cyrl', 'tel_Telu', 'tgk_Cyrl', 'tgl_Latn', 'tha_Thai', 'tir_Ethi', 'taq_Latn', 'taq_Tfng', 'tpi_Latn', 'tsn_Latn', 'tso_Latn', 'tuk_Latn', 'tum_Latn', 'tur_Latn', 'twi_Latn', 'tzm_Tfng', 'uig_Arab', 'ukr_Cyrl', 'umb_Latn', 'urd_Arab', 'uzn_Latn', 'vec_Latn', 'vie_Latn', 'war_Latn', 'wol_Latn', 'xho_Latn', 'ydd_Hebr', 'yor_Latn', 'yue_Hant', 'zho_Hans', 'zho_Hant', 'zul_Latn'] # fmt: skip
31
+
32
+
33
+ class NllbTokenizer(TokenizersBackend):
34
+ """
35
+ Construct an NLLB tokenizer (backed by HuggingFace's *tokenizers* library). Based on
36
+ [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).
37
+
38
+ This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
39
+ refer to this superclass for more information regarding those methods.
40
+
41
+ The tokenization method is `<tokens> <eos> <language code>` for source language documents, and `<language code>
42
+ <tokens> <eos>` for target language documents.
43
+
44
+ Examples:
45
+
46
+ ```python
47
+ >>> from transformers import NllbTokenizer
48
+
49
+ >>> tokenizer = NllbTokenizer.from_pretrained(
50
+ ... "facebook/nllb-200-distilled-600M", src_lang="eng_Latn", tgt_lang="fra_Latn"
51
+ ... )
52
+ >>> example_english_phrase = " UN Chief Says There Is No Military Solution in Syria"
53
+ >>> expected_translation_french = "Le chef de l'ONU affirme qu'il n'y a pas de solution militaire en Syrie."
54
+ >>> inputs = tokenizer(example_english_phrase, text_target=expected_translation_french, return_tensors="pt")
55
+ ```
56
+
57
+ Args:
58
+ vocab_file (`str`, *optional*):
59
+ Path to the vocabulary file.
60
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
61
+ The beginning of sequence token that was used during pretraining.
62
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
63
+ The end of sequence token.
64
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
65
+ The separator token.
66
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
67
+ The classifier token.
68
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
69
+ The unknown token.
70
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
71
+ The token used for padding.
72
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
73
+ The token used for masking values.
74
+ src_lang (`str`, *optional*):
75
+ The language to use as source language for translation.
76
+ tgt_lang (`str`, *optional*):
77
+ The language to use as target language for translation.
78
+ legacy_behaviour (`bool`, *optional*, defaults to `False`):
79
+ Whether to use legacy behaviour (suffix pattern) or new behaviour (prefix pattern).
80
+ """
81
+
82
+ vocab_files_names = VOCAB_FILES_NAMES
83
+ model_input_names = ["input_ids", "attention_mask"]
84
+ model = BPE
85
+
86
+ prefix_tokens: list[int] = []
87
+ suffix_tokens: list[int] = []
88
+
89
+ def __init__(
90
+ self,
91
+ vocab: str | dict[str, int] | None = None,
92
+ merges: str | list[str] | None = None,
93
+ bos_token="<s>",
94
+ eos_token="</s>",
95
+ sep_token="</s>",
96
+ cls_token="<s>",
97
+ unk_token="<unk>",
98
+ pad_token="<pad>",
99
+ mask_token="<mask>",
100
+ src_lang=None,
101
+ tgt_lang=None,
102
+ _spm_precompiled_charsmap: str | None = None,
103
+ additional_special_tokens=None,
104
+ extra_special_tokens=None,
105
+ legacy_behaviour=False,
106
+ **kwargs,
107
+ ):
108
+ # V5: extra_special_tokens takes precedence over additional_special_tokens (deprecated)
109
+ # Handle case where both are passed (ie. from config and user override)
110
+ if extra_special_tokens is not None:
111
+ additional_special_tokens = extra_special_tokens
112
+ elif additional_special_tokens is None:
113
+ additional_special_tokens = FAIRSEQ_LANGUAGE_CODES
114
+
115
+ mask_token = (
116
+ AddedToken(mask_token, normalized=True, lstrip=True, special=True)
117
+ if isinstance(mask_token, str)
118
+ else mask_token
119
+ )
120
+ self.legacy_behaviour = legacy_behaviour
121
+
122
+ if vocab is None:
123
+ vocab = {
124
+ str(bos_token): 0,
125
+ str(pad_token): 1,
126
+ str(eos_token): 2,
127
+ str(unk_token): 3,
128
+ }
129
+ self._vocab = vocab
130
+ self._merges = merges or []
131
+
132
+ self._tokenizer = Tokenizer(
133
+ BPE(
134
+ vocab=self._vocab,
135
+ merges=self._merges,
136
+ dropout=None,
137
+ unk_token=str(unk_token),
138
+ fuse_unk=True,
139
+ byte_fallback=False,
140
+ )
141
+ )
142
+
143
+ if _spm_precompiled_charsmap is not None:
144
+ self._tokenizer.normalizer = normalizers.Sequence(
145
+ [
146
+ normalizers.Precompiled(_spm_precompiled_charsmap),
147
+ normalizers.Replace(Regex(r" {2,}"), " "),
148
+ ]
149
+ )
150
+
151
+ self._tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(replacement="▁", prepend_scheme="always", split=True)
152
+ self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme="always", split=True)
153
+
154
+ super().__init__(
155
+ bos_token=bos_token,
156
+ eos_token=eos_token,
157
+ sep_token=sep_token,
158
+ cls_token=cls_token,
159
+ unk_token=unk_token,
160
+ pad_token=pad_token,
161
+ src_lang=src_lang,
162
+ tgt_lang=tgt_lang,
163
+ mask_token=mask_token,
164
+ extra_special_tokens=additional_special_tokens,
165
+ legacy_behaviour=legacy_behaviour,
166
+ **kwargs,
167
+ )
168
+
169
+ # Build fairseq mappings for backward compatibility
170
+ self.fairseq_offset = 1
171
+ self.fairseq_tokens_to_ids = {
172
+ "<s>": 0,
173
+ "<pad>": 1,
174
+ "</s>": 2,
175
+ "<unk>": 3,
176
+ }
177
+ self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
178
+
179
+ self._src_lang = src_lang if src_lang is not None else "eng_Latn"
180
+ self.cur_lang_code = self.convert_tokens_to_ids(self._src_lang)
181
+ self.tgt_lang = tgt_lang
182
+ self.set_src_lang_special_tokens(self._src_lang)
183
+
184
+ @property
185
+ def src_lang(self) -> str:
186
+ return self._src_lang
187
+
188
+ @src_lang.setter
189
+ def src_lang(self, new_src_lang: str) -> None:
190
+ self._src_lang = new_src_lang
191
+ self.set_src_lang_special_tokens(self._src_lang)
192
+
193
+ def _build_translation_inputs(
194
+ self, raw_inputs, return_tensors: str, src_lang: str | None, tgt_lang: str | None, **extra_kwargs
195
+ ):
196
+ """Used by translation pipeline, to prepare inputs for the generate function"""
197
+ if src_lang is None or tgt_lang is None:
198
+ raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model")
199
+ self.src_lang = src_lang
200
+ inputs = self(raw_inputs, add_special_tokens=True, return_tensors=return_tensors, **extra_kwargs)
201
+ tgt_lang_id = self.convert_tokens_to_ids(tgt_lang)
202
+ inputs["forced_bos_token_id"] = tgt_lang_id
203
+ return inputs
204
+
205
+ def prepare_seq2seq_batch(
206
+ self,
207
+ src_texts: list[str],
208
+ src_lang: str = "eng_Latn",
209
+ tgt_texts: list[str] | None = None,
210
+ tgt_lang: str = "fra_Latn",
211
+ max_length: int | None = None,
212
+ max_target_length: int | None = None,
213
+ padding: str = "longest",
214
+ return_tensors: str | None = None,
215
+ truncation: bool = True,
216
+ **kwargs,
217
+ ) -> BatchEncoding:
218
+ self.src_lang = src_lang
219
+ self.tgt_lang = tgt_lang
220
+
221
+ if max_length is None:
222
+ max_length = self.model_max_length
223
+
224
+ model_inputs = self(
225
+ src_texts,
226
+ add_special_tokens=True,
227
+ return_tensors=return_tensors,
228
+ max_length=max_length,
229
+ padding=padding,
230
+ truncation=truncation,
231
+ **kwargs,
232
+ )
233
+
234
+ if tgt_texts is None:
235
+ return model_inputs
236
+
237
+ # Process tgt_texts
238
+ if max_target_length is None:
239
+ max_target_length = max_length
240
+
241
+ # Switch to target mode to set the right special tokens
242
+ self._switch_to_target_mode()
243
+ labels = self(
244
+ tgt_texts,
245
+ add_special_tokens=True,
246
+ return_tensors=return_tensors,
247
+ padding=padding,
248
+ max_length=max_target_length,
249
+ truncation=truncation,
250
+ **kwargs,
251
+ )
252
+ model_inputs["labels"] = labels["input_ids"]
253
+
254
+ # Switch back to input mode
255
+ self._switch_to_input_mode()
256
+
257
+ return model_inputs
258
+
259
+ def _switch_to_input_mode(self):
260
+ return self.set_src_lang_special_tokens(self.src_lang)
261
+
262
+ def _switch_to_target_mode(self):
263
+ if self.tgt_lang is None:
264
+ self.tgt_lang = self._src_lang
265
+ return self.set_tgt_lang_special_tokens(self.tgt_lang)
266
+
267
+ def set_src_lang_special_tokens(self, src_lang) -> None:
268
+ """Reset the special tokens to the source lang setting.
269
+ - In legacy mode: No prefix and suffix=[eos, src_lang_code].
270
+ - In default mode: Prefix=[src_lang_code], suffix = [eos]
271
+ """
272
+ self.cur_lang_code = self.convert_tokens_to_ids(src_lang)
273
+ lang_code_token = src_lang
274
+
275
+ if self.legacy_behaviour:
276
+ self.prefix_tokens = []
277
+ self.suffix_tokens = [self.eos_token_id, self.cur_lang_code]
278
+ self._tokenizer.post_processor = processors.TemplateProcessing(
279
+ single=["$A", self.eos_token, lang_code_token],
280
+ pair=["$A", "$B", self.eos_token, lang_code_token],
281
+ special_tokens=[(self.eos_token, self.eos_token_id), (lang_code_token, self.cur_lang_code)],
282
+ )
283
+ else:
284
+ self.prefix_tokens = [self.cur_lang_code]
285
+ self.suffix_tokens = [self.eos_token_id]
286
+ self._tokenizer.post_processor = processors.TemplateProcessing(
287
+ single=[lang_code_token, "$A", self.eos_token],
288
+ pair=[lang_code_token, "$A", "$B", self.eos_token],
289
+ special_tokens=[(self.eos_token, self.eos_token_id), (lang_code_token, self.cur_lang_code)],
290
+ )
291
+
292
+ def set_tgt_lang_special_tokens(self, lang: str) -> None:
293
+ """Reset the special tokens to the target lang setting.
294
+ - In legacy mode: No prefix and suffix=[eos, tgt_lang_code].
295
+ - In default mode: Prefix=[tgt_lang_code], suffix = [eos]
296
+ """
297
+ self.cur_lang_code = self.convert_tokens_to_ids(lang)
298
+ lang_code_token = lang
299
+
300
+ if self.legacy_behaviour:
301
+ self.prefix_tokens = []
302
+ self.suffix_tokens = [self.eos_token_id, self.cur_lang_code]
303
+ self._tokenizer.post_processor = processors.TemplateProcessing(
304
+ single=["$A", self.eos_token, lang_code_token],
305
+ pair=["$A", "$B", self.eos_token, lang_code_token],
306
+ special_tokens=[(self.eos_token, self.eos_token_id), (lang_code_token, self.cur_lang_code)],
307
+ )
308
+ else:
309
+ self.prefix_tokens = [self.cur_lang_code]
310
+ self.suffix_tokens = [self.eos_token_id]
311
+ self._tokenizer.post_processor = processors.TemplateProcessing(
312
+ single=[lang_code_token, "$A", self.eos_token],
313
+ pair=[lang_code_token, "$A", "$B", self.eos_token],
314
+ special_tokens=[(self.eos_token, self.eos_token_id), (lang_code_token, self.cur_lang_code)],
315
+ )
316
+
317
+
318
+ __all__ = ["NllbTokenizer"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nllb_moe/__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_nllb_moe import *
22
+ from .modeling_nllb_moe 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__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nllb_moe/configuration_nllb_moe.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023, HuggingFace Inc.
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
+ """NLLB-MoE model configuration"""
15
+
16
+ from typing import Literal
17
+
18
+ from huggingface_hub.dataclasses import strict
19
+
20
+ from ...configuration_utils import PreTrainedConfig
21
+ from ...utils import auto_docstring
22
+
23
+
24
+ @auto_docstring(checkpoint="facebook/nllb-moe-54b")
25
+ @strict
26
+ class NllbMoeConfig(PreTrainedConfig):
27
+ r"""
28
+ router_bias (`bool`, *optional*, defaults to `False`):
29
+ Whether or not the classifier of the router should have a bias.
30
+ router_dtype (`str`, *optional*, default to `"float32"`):
31
+ The `dtype` used for the routers. It is preferable to keep the `dtype` to `"float32"` as specified in the
32
+ *selective precision* discussion in [the paper](https://huggingface.co/papers/2101.03961).
33
+ router_ignore_padding_tokens (`bool`, *optional*, defaults to `False`):
34
+ Whether to ignore padding tokens when routing. if `False`, the padding tokens are not routed to any
35
+ experts.
36
+ expert_capacity (`int`, *optional*, defaults to 64):
37
+ Number of tokens that can be stored in each expert.
38
+ encoder_sparse_step (`int`, *optional*, defaults to 4):
39
+ Frequency of the sparse layers in the encoder. 4 means that one out of 4 layers will be sparse.
40
+ decoder_sparse_step (`int`, *optional*, defaults to 4):
41
+ Frequency of the sparse layers in the decoder. 4 means that one out of 4 layers will be sparse.
42
+ second_expert_policy (`str`, *optional*, default to `"all"`):
43
+ The policy used for the sampling the probability of being sampled to a second expert for each token.
44
+ normalize_router_prob_before_dropping (`bool`, *optional*, defaults to `True`):
45
+ Whether or not to normalize the router probabilities before applying a mask based on the experts capacity
46
+ (capacity dropping).
47
+ batch_prioritized_routing (`bool`, *optional*, defaults to `True`):
48
+ Whether or not to orders the tokens by their router probabilities before capacity dropping. This means that
49
+ the tokens that have the highest probabilities will be routed before other tokens that might be further in
50
+ the sequence.
51
+ moe_eval_capacity_token_fraction (`float`, *optional*, defaults to 1.0):
52
+ Fraction of tokens as capacity during validation, if set to negative, uses the same as training. Should be
53
+ in range: (0.0, 1.0].
54
+ moe_token_dropout (`float`, *optional*, default to 0.2):
55
+ Masking rate for MoE expert output masking (EOM), which is implemented via a Dropout2d on the expert
56
+ outputs.
57
+
58
+ Example:
59
+
60
+ ```python
61
+ >>> from transformers import NllbMoeModel, NllbMoeConfig
62
+
63
+ >>> # Initializing a NllbMoe facebook/nllb-moe-54b style configuration
64
+ >>> configuration = NllbMoeConfig()
65
+
66
+ >>> # Initializing a model from the facebook/nllb-moe-54b style configuration
67
+ >>> model = NllbMoeModel(configuration)
68
+
69
+ >>> # Accessing the model configuration
70
+ >>> configuration = model.config
71
+ ```"""
72
+
73
+ model_type = "nllb-moe"
74
+ keys_to_ignore_at_inference = ["past_key_values"]
75
+ attribute_map = {
76
+ "num_attention_heads": "encoder_attention_heads",
77
+ "hidden_size": "d_model",
78
+ "num_hidden_layers": "encoder_layers",
79
+ }
80
+
81
+ vocab_size: int = 128112
82
+ max_position_embeddings: int = 1024
83
+ encoder_layers: int = 12
84
+ encoder_ffn_dim: int = 4096
85
+ encoder_attention_heads: int = 16
86
+ decoder_layers: int = 12
87
+ decoder_ffn_dim: int = 4096
88
+ decoder_attention_heads: int = 16
89
+ encoder_layerdrop: float | int = 0.05
90
+ decoder_layerdrop: float | int = 0.05
91
+ use_cache: bool = True
92
+ is_encoder_decoder: bool = True
93
+ activation_function: str = "relu"
94
+ d_model: int = 1024
95
+ dropout: float | int = 0.1
96
+ attention_dropout: float | int = 0.1
97
+ activation_dropout: float | int = 0.0
98
+ init_std: float = 0.02
99
+ decoder_start_token_id: int | None = 2
100
+ scale_embedding: bool = True
101
+ router_bias: bool = False
102
+ router_dtype: Literal["float32", "float16", "bfloat16"] = "float32"
103
+ router_ignore_padding_tokens: bool = False
104
+ num_experts: int = 128
105
+ expert_capacity: int = 64
106
+ encoder_sparse_step: int = 4
107
+ decoder_sparse_step: int = 4
108
+ router_z_loss_coef: float = 0.001
109
+ router_aux_loss_coef: float = 0.001
110
+ second_expert_policy: str = "all"
111
+ normalize_router_prob_before_dropping: bool = False
112
+ batch_prioritized_routing: bool = False
113
+ moe_eval_capacity_token_fraction: float = 1.0
114
+ moe_token_dropout: float | int = 0.2
115
+ pad_token_id: int | None = 1
116
+ bos_token_id: int | None = 0
117
+ eos_token_id: int | list[int] | None = 2
118
+ tie_word_embeddings: bool = True
119
+ output_router_logits: bool = False
120
+
121
+
122
+ __all__ = ["NllbMoeConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nllb_moe/modeling_nllb_moe.py ADDED
@@ -0,0 +1,1143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 NllbMoe 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
+
15
+ import math
16
+ from collections.abc import Callable
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ from torch.nn import CrossEntropyLoss
21
+
22
+ from ... import initialization as init
23
+ from ...activations import ACT2FN
24
+ from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
25
+ from ...generation import GenerationMixin
26
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
27
+ from ...integrations.fsdp import is_fsdp_managed_module
28
+ from ...masking_utils import create_bidirectional_mask, create_causal_mask
29
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
30
+ from ...modeling_layers import GradientCheckpointingLayer
31
+ from ...modeling_outputs import (
32
+ BaseModelOutputWithPastAndCrossAttentions,
33
+ MoEModelOutput,
34
+ MoEModelOutputWithPastAndCrossAttentions,
35
+ Seq2SeqMoEModelOutput,
36
+ Seq2SeqMoEOutput,
37
+ )
38
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
39
+ from ...processing_utils import Unpack
40
+ from ...utils import TransformersKwargs, auto_docstring, logging
41
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
42
+ from ...utils.output_capturing import OutputRecorder, capture_outputs
43
+ from .configuration_nllb_moe import NllbMoeConfig
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ class NllbMoeScaledWordEmbedding(nn.Embedding):
50
+ """
51
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
52
+ """
53
+
54
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float | None = 1.0):
55
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
56
+ self.embed_scale = embed_scale
57
+
58
+ def forward(self, input_ids: torch.Tensor):
59
+ return super().forward(input_ids) * self.embed_scale
60
+
61
+
62
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding with M2M100->NllbMoe
63
+ class NllbMoeSinusoidalPositionalEmbedding(nn.Module):
64
+ """This module produces sinusoidal positional embeddings of any length."""
65
+
66
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: int | None = None):
67
+ super().__init__()
68
+ self.offset = 2
69
+ self.num_positions = num_positions
70
+ self.embedding_dim = embedding_dim
71
+ self.padding_idx = padding_idx
72
+ self.make_weights(num_positions + self.offset, embedding_dim, padding_idx)
73
+
74
+ def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: int | None = None):
75
+ emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
76
+ if hasattr(self, "weights"):
77
+ # in forward put the weights on the correct dtype and device of the param
78
+ emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
79
+
80
+ self.register_buffer("weights", emb_weights, persistent=False)
81
+
82
+ @staticmethod
83
+ def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: int | None = None):
84
+ """
85
+ Build sinusoidal embeddings.
86
+
87
+ This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
88
+ "Attention Is All You Need".
89
+ """
90
+ half_dim = embedding_dim // 2
91
+ emb = math.log(10000) / (half_dim - 1)
92
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
93
+ emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
94
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
95
+ if embedding_dim % 2 == 1:
96
+ # zero pad
97
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
98
+ if padding_idx is not None:
99
+ emb[padding_idx, :] = 0
100
+
101
+ return emb.to(torch.get_default_dtype())
102
+
103
+ @torch.no_grad()
104
+ def forward(
105
+ self,
106
+ input_ids: torch.Tensor | None = None,
107
+ inputs_embeds: torch.Tensor | None = None,
108
+ past_key_values_length: int = 0,
109
+ ):
110
+ if input_ids is not None:
111
+ bsz, seq_len = input_ids.size()
112
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
113
+ position_ids = self.create_position_ids_from_input_ids(
114
+ input_ids, self.padding_idx, past_key_values_length
115
+ ).to(input_ids.device)
116
+ else:
117
+ bsz, seq_len = inputs_embeds.size()[:-1]
118
+ position_ids = self.create_position_ids_from_inputs_embeds(
119
+ inputs_embeds, past_key_values_length, self.padding_idx
120
+ )
121
+
122
+ # expand embeddings if needed
123
+ max_pos = self.padding_idx + 1 + seq_len + past_key_values_length
124
+ if max_pos > self.weights.size(0):
125
+ self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx)
126
+
127
+ return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, self.weights.shape[-1]).detach()
128
+
129
+ @staticmethod
130
+ def create_position_ids_from_inputs_embeds(inputs_embeds, past_key_values_length, padding_idx):
131
+ """
132
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
133
+
134
+ Args:
135
+ inputs_embeds: torch.Tensor
136
+
137
+ Returns: torch.Tensor
138
+ """
139
+ input_shape = inputs_embeds.size()[:-1]
140
+ sequence_length = input_shape[1]
141
+
142
+ position_ids = torch.arange(
143
+ padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
144
+ )
145
+ return position_ids.unsqueeze(0).expand(input_shape).contiguous() + past_key_values_length
146
+
147
+ @staticmethod
148
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings.create_position_ids_from_input_ids
149
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
150
+ """
151
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
152
+ are ignored. This is modified from fairseq's `utils.make_positions`.
153
+
154
+ Args:
155
+ x: torch.Tensor x:
156
+
157
+ Returns: torch.Tensor
158
+ """
159
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
160
+ mask = input_ids.ne(padding_idx).int()
161
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
162
+ return incremental_indices.long() + padding_idx
163
+
164
+
165
+ class NllbMoeTop2Router(nn.Module):
166
+ """
167
+ Router using tokens choose top-2 experts assignment.
168
+
169
+ This router uses the same mechanism as in NLLB-MoE from the fairseq repository. Items are sorted by router_probs
170
+ and then routed to their choice of expert until the expert's expert_capacity is reached. **There is no guarantee
171
+ that each token is processed by an expert**, or that each expert receives at least one token.
172
+
173
+ The router combining weights are also returned to make sure that the states that are not updated will be masked.
174
+
175
+ """
176
+
177
+ def __init__(self, config: NllbMoeConfig):
178
+ super().__init__()
179
+ self.num_experts = config.num_experts
180
+ self.expert_capacity = config.expert_capacity
181
+ self.classifier = nn.Linear(config.hidden_size, self.num_experts, bias=config.router_bias)
182
+ self.router_ignore_padding_tokens = config.router_ignore_padding_tokens
183
+ self.dtype = getattr(torch, config.router_dtype)
184
+
185
+ self.second_expert_policy = config.second_expert_policy
186
+ self.normalize_router_prob_before_dropping = config.normalize_router_prob_before_dropping
187
+ self.batch_prioritized_routing = config.batch_prioritized_routing
188
+ self.moe_eval_capacity_token_fraction = config.moe_eval_capacity_token_fraction
189
+
190
+ def _cast_classifier(self):
191
+ r"""
192
+ `bitsandbytes` `Linear8bitLt` layers does not support manual casting Therefore we need to check if they are an
193
+ instance of the `Linear8bitLt` class by checking special attributes.
194
+ """
195
+ if not (hasattr(self.classifier, "SCB") or hasattr(self.classifier, "CB")):
196
+ self.classifier = self.classifier.to(self.dtype)
197
+
198
+ def normalize_router_probabilities(self, router_probs, top_1_mask, top_2_mask):
199
+ top_1_max_probs = (router_probs * top_1_mask).sum(dim=1)
200
+ top_2_max_probs = (router_probs * top_2_mask).sum(dim=1)
201
+ denom_s = torch.clamp(top_1_max_probs + top_2_max_probs, min=torch.finfo(router_probs.dtype).eps)
202
+ top_1_max_probs = top_1_max_probs / denom_s
203
+ top_2_max_probs = top_2_max_probs / denom_s
204
+ return top_1_max_probs, top_2_max_probs
205
+
206
+ def route_tokens(
207
+ self,
208
+ router_logits: torch.Tensor,
209
+ input_dtype: torch.dtype = torch.float32,
210
+ padding_mask: torch.LongTensor | None = None,
211
+ ) -> tuple:
212
+ """
213
+ Computes the `dispatch_mask` and the `dispatch_weights` for each experts. The masks are adapted to the expert
214
+ capacity.
215
+ """
216
+ nb_tokens = router_logits.shape[0]
217
+ # Apply Softmax and cast back to the original `dtype`
218
+ router_probs = nn.functional.softmax(router_logits, dim=-1, dtype=self.dtype).to(input_dtype)
219
+ top_1_expert_index = torch.argmax(router_probs, dim=-1)
220
+ top_1_mask = torch.nn.functional.one_hot(top_1_expert_index, num_classes=self.num_experts)
221
+
222
+ if self.second_expert_policy == "sampling":
223
+ gumbel = torch.distributions.gumbel.Gumbel(0, 1).rsample
224
+ router_logits += gumbel(router_logits.shape).to(router_logits.device)
225
+
226
+ # replace top_1_expert_index with min values
227
+ logits_except_top_1 = router_logits.masked_fill(top_1_mask.bool(), float("-inf"))
228
+ top_2_expert_index = torch.argmax(logits_except_top_1, dim=-1)
229
+ top_2_mask = torch.nn.functional.one_hot(top_2_expert_index, num_classes=self.num_experts)
230
+
231
+ if self.normalize_router_prob_before_dropping:
232
+ top_1_max_probs, top_2_max_probs = self.normalize_router_probabilities(
233
+ router_probs, top_1_mask, top_2_mask
234
+ )
235
+
236
+ if self.second_expert_policy == "random":
237
+ top_2_max_probs = (router_probs * top_2_mask).sum(dim=1)
238
+ sampled = (2 * top_2_max_probs) > torch.rand_like(top_2_max_probs.float())
239
+ top_2_mask = top_2_mask * sampled.repeat(self.num_experts, 1).transpose(1, 0)
240
+
241
+ if padding_mask is not None and not self.router_ignore_padding_tokens:
242
+ if len(padding_mask.shape) == 4:
243
+ # only get the last causal mask
244
+ padding_mask = padding_mask[:, :, -1, :].reshape(-1)[-nb_tokens:]
245
+ non_padding = ~padding_mask.bool()
246
+ top_1_mask = top_1_mask * non_padding.unsqueeze(-1).to(top_1_mask.dtype)
247
+ top_2_mask = top_2_mask * non_padding.unsqueeze(-1).to(top_1_mask.dtype)
248
+
249
+ if self.batch_prioritized_routing:
250
+ # sort tokens based on their routing probability
251
+ # to make sure important tokens are routed, first
252
+ importance_scores = -1 * router_probs.max(dim=1)[0]
253
+ sorted_top_1_mask = top_1_mask[importance_scores.argsort(dim=0)]
254
+ sorted_cumsum1 = (torch.cumsum(sorted_top_1_mask, dim=0) - 1) * sorted_top_1_mask
255
+ locations1 = sorted_cumsum1[importance_scores.argsort(dim=0).argsort(dim=0)]
256
+
257
+ sorted_top_2_mask = top_2_mask[importance_scores.argsort(dim=0)]
258
+ sorted_cumsum2 = (torch.cumsum(sorted_top_2_mask, dim=0) - 1) * sorted_top_2_mask
259
+ locations2 = sorted_cumsum2[importance_scores.argsort(dim=0).argsort(dim=0)]
260
+ # Update 2nd's location by accounting for locations of 1st
261
+ locations2 += torch.sum(top_1_mask, dim=0, keepdim=True)
262
+
263
+ else:
264
+ locations1 = torch.cumsum(top_1_mask, dim=0) - 1
265
+ locations2 = torch.cumsum(top_2_mask, dim=0) - 1
266
+ # Update 2nd's location by accounting for locations of 1st
267
+ locations2 += torch.sum(top_1_mask, dim=0, keepdim=True)
268
+
269
+ if not self.training and self.moe_eval_capacity_token_fraction > 0:
270
+ self.expert_capacity = math.ceil(self.moe_eval_capacity_token_fraction * nb_tokens)
271
+ else:
272
+ capacity = 2 * math.ceil(nb_tokens / self.num_experts)
273
+ self.expert_capacity = capacity if self.expert_capacity is None else self.expert_capacity
274
+
275
+ # Remove locations outside capacity from ( cumsum < capacity = False will not be routed)
276
+ top_1_mask = top_1_mask * torch.lt(locations1, self.expert_capacity)
277
+ top_2_mask = top_2_mask * torch.lt(locations2, self.expert_capacity)
278
+
279
+ if not self.normalize_router_prob_before_dropping:
280
+ top_1_max_probs, top_2_max_probs = self.normalize_router_probabilities(
281
+ router_probs, top_1_mask, top_2_mask
282
+ )
283
+
284
+ # Calculate combine_weights and dispatch_mask
285
+ gates1 = top_1_max_probs[:, None] * top_1_mask
286
+ gates2 = top_2_max_probs[:, None] * top_2_mask
287
+ router_probs = gates1 + gates2
288
+
289
+ return top_1_mask, router_probs
290
+
291
+ def forward(self, hidden_states: torch.Tensor, padding_mask: torch.LongTensor | None = None) -> tuple:
292
+ r"""
293
+ The hidden states are reshaped to simplify the computation of the router probabilities (combining weights for
294
+ each experts.)
295
+
296
+ Args:
297
+ hidden_states (`torch.Tensor`):
298
+ (batch_size, sequence_length, hidden_dim) from which router probabilities are computed.
299
+ Returns:
300
+ top_1_mask (`torch.Tensor` of shape (batch_size, sequence_length)):
301
+ Index tensor of shape [batch_size, sequence_length] corresponding to the expert selected for each token
302
+ using the top1 probabilities of the router.
303
+ router_probabilities (`torch.Tensor` of shape (batch_size, sequence_length, nump_experts)):
304
+ Tensor of shape (batch_size, sequence_length, num_experts) corresponding to the probabilities for each
305
+ token and expert. Used for routing tokens to experts.
306
+ router_logits (`torch.Tensor` of shape (batch_size, sequence_length))):
307
+ Logits tensor of shape (batch_size, sequence_length, num_experts) corresponding to raw router logits.
308
+ This is used later for computing router z-loss.
309
+ """
310
+ self.input_dtype = hidden_states.dtype
311
+ hidden_states = hidden_states.to(self.dtype)
312
+ self._cast_classifier()
313
+ router_logits = self.classifier(hidden_states)
314
+ top_1_mask, router_probs = self.route_tokens(router_logits, self.input_dtype, padding_mask)
315
+ return top_1_mask, router_probs, router_logits
316
+
317
+
318
+ class NllbMoeDenseActDense(nn.Module):
319
+ def __init__(self, config: NllbMoeConfig, ffn_dim: int):
320
+ super().__init__()
321
+ self.fc1 = nn.Linear(config.d_model, ffn_dim)
322
+ self.fc2 = nn.Linear(ffn_dim, config.d_model)
323
+ self.dropout = nn.Dropout(config.activation_dropout)
324
+ self.act = ACT2FN[config.activation_function]
325
+
326
+ def forward(self, hidden_states: torch.Tensor):
327
+ hidden_states = self.fc1(hidden_states)
328
+ hidden_states = self.act(hidden_states)
329
+ hidden_states = self.dropout(hidden_states)
330
+ if (
331
+ isinstance(self.fc2.weight, torch.Tensor)
332
+ and hidden_states.dtype != self.fc2.weight.dtype
333
+ and (self.fc2.weight.dtype != torch.int8 and self.fc2.weight.dtype != torch.uint8)
334
+ ):
335
+ hidden_states = hidden_states.to(self.fc2.weight.dtype)
336
+ hidden_states = self.fc2(hidden_states)
337
+ return hidden_states
338
+
339
+
340
+ class NllbMoeExperts(nn.ModuleDict):
341
+ def __init__(self, config: NllbMoeConfig, ffn_dim: int):
342
+ super().__init__()
343
+ self.num_experts = config.num_experts
344
+ for idx in range(self.num_experts):
345
+ self[f"expert_{idx}"] = NllbMoeDenseActDense(config, ffn_dim)
346
+ self.moe_token_dropout = config.moe_token_dropout
347
+ self.token_dropout = nn.Dropout(self.moe_token_dropout)
348
+
349
+ def forward(self, hidden_states: torch.Tensor, router_mask: torch.Tensor, router_probs: torch.Tensor):
350
+ final_hidden_states = torch.zeros_like(hidden_states)
351
+ expert_mask = torch.nn.functional.one_hot(router_mask, num_classes=self.num_experts).permute(2, 1, 0)
352
+
353
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
354
+ for expert_idx in expert_hit:
355
+ idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
356
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_states.shape[-1])
357
+ current_hidden_states = self[f"expert_{expert_idx[0]}"](current_state) * router_probs[top_x, idx, None]
358
+ if self.moe_token_dropout > 0:
359
+ if self.training:
360
+ current_hidden_states = self.token_dropout(current_hidden_states)
361
+ else:
362
+ current_hidden_states *= 1 - self.moe_token_dropout
363
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
364
+ return final_hidden_states
365
+
366
+
367
+ class NllbMoeSparseMLP(nn.Module):
368
+ r"""
369
+ Implementation of the NLLB-MoE sparse MLP module.
370
+ """
371
+
372
+ def __init__(self, config: NllbMoeConfig, ffn_dim: int):
373
+ super().__init__()
374
+ self.router = NllbMoeTop2Router(config)
375
+ self.num_experts = config.num_experts
376
+ self.experts = NllbMoeExperts(config, ffn_dim)
377
+
378
+ def forward(self, hidden_states: torch.Tensor, padding_mask: torch.Tensor | None = None):
379
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
380
+ hidden_states = hidden_states.view(-1, hidden_dim)
381
+ top_1_mask, router_probs, _ = self.router(hidden_states, padding_mask)
382
+ hidden_states = self.experts(hidden_states, top_1_mask, router_probs)
383
+ return hidden_states.reshape(batch_size, sequence_length, hidden_dim)
384
+
385
+
386
+ # Copied from transformers.models.bert.modeling_bert.eager_attention_forward
387
+ def eager_attention_forward(
388
+ module: nn.Module,
389
+ query: torch.Tensor,
390
+ key: torch.Tensor,
391
+ value: torch.Tensor,
392
+ attention_mask: torch.Tensor | None,
393
+ scaling: float | None = None,
394
+ dropout: float = 0.0,
395
+ **kwargs: Unpack[TransformersKwargs],
396
+ ):
397
+ if scaling is None:
398
+ scaling = query.size(-1) ** -0.5
399
+
400
+ # Take the dot product between "query" and "key" to get the raw attention scores.
401
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
402
+
403
+ if attention_mask is not None:
404
+ attn_weights = attn_weights + attention_mask
405
+
406
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
407
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
408
+
409
+ attn_output = torch.matmul(attn_weights, value)
410
+ attn_output = attn_output.transpose(1, 2).contiguous()
411
+
412
+ return attn_output, attn_weights
413
+
414
+
415
+ class NllbMoeAttention(nn.Module):
416
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
417
+
418
+ def __init__(
419
+ self,
420
+ embed_dim: int,
421
+ num_heads: int,
422
+ dropout: float | None = 0.0,
423
+ is_decoder: bool | None = False,
424
+ bias: bool | None = True,
425
+ is_causal: bool | None = False,
426
+ config: NllbMoeConfig | None = None,
427
+ layer_idx: int | None = None,
428
+ ):
429
+ super().__init__()
430
+ self.embed_dim = embed_dim
431
+ self.num_heads = num_heads
432
+ self.dropout = dropout
433
+ self.head_dim = embed_dim // num_heads
434
+ self.config = config
435
+
436
+ if (self.head_dim * num_heads) != self.embed_dim:
437
+ raise ValueError(
438
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
439
+ f" and `num_heads`: {num_heads})."
440
+ )
441
+ self.scaling = self.head_dim**-0.5
442
+ self.is_decoder = is_decoder
443
+ self.is_causal = is_causal
444
+ self.layer_idx = layer_idx
445
+
446
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
447
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
448
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
449
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
450
+
451
+ def forward(
452
+ self,
453
+ hidden_states: torch.Tensor,
454
+ key_value_states: torch.Tensor | None = None,
455
+ past_key_values: Cache | None = None,
456
+ attention_mask: torch.Tensor | None = None,
457
+ **kwargs: Unpack[FlashAttentionKwargs],
458
+ ) -> tuple[torch.Tensor, torch.Tensor]:
459
+ is_cross_attention = key_value_states is not None
460
+ input_shape = hidden_states.shape[:-1]
461
+ hidden_shape = (*input_shape, -1, self.head_dim)
462
+
463
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
464
+ is_updated = False
465
+ if past_key_values is not None:
466
+ if isinstance(past_key_values, EncoderDecoderCache):
467
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
468
+ if is_cross_attention:
469
+ # after the first generated id, we can subsequently re-use all key/value_layer from cache
470
+ curr_past_key_values = past_key_values.cross_attention_cache
471
+ else:
472
+ curr_past_key_values = past_key_values.self_attention_cache
473
+ else:
474
+ curr_past_key_values = past_key_values
475
+
476
+ current_states = key_value_states if is_cross_attention else hidden_states
477
+ if is_cross_attention and past_key_values is not None and is_updated:
478
+ # reuse k,v, cross_attentions
479
+ key_states = curr_past_key_values.layers[self.layer_idx].keys
480
+ value_states = curr_past_key_values.layers[self.layer_idx].values
481
+ else:
482
+ kv_shape = (*current_states.shape[:-1], -1, self.head_dim)
483
+ key_states = self.k_proj(current_states).view(kv_shape).transpose(1, 2)
484
+ value_states = self.v_proj(current_states).view(kv_shape).transpose(1, 2)
485
+
486
+ if past_key_values is not None:
487
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
488
+ key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
489
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
490
+ if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
491
+ past_key_values.is_updated[self.layer_idx] = True
492
+
493
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
494
+ self.config._attn_implementation, eager_attention_forward
495
+ )
496
+
497
+ attn_output, attn_weights = attention_interface(
498
+ self,
499
+ query_states,
500
+ key_states,
501
+ value_states,
502
+ attention_mask,
503
+ dropout=0.0 if not self.training else self.dropout,
504
+ scaling=self.scaling,
505
+ **kwargs,
506
+ )
507
+
508
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
509
+ attn_output = self.out_proj(attn_output)
510
+ return attn_output, attn_weights
511
+
512
+
513
+ class NllbMoeEncoderLayer(GradientCheckpointingLayer):
514
+ def __init__(self, config: NllbMoeConfig, is_sparse: bool = False, layer_idx: int = 0):
515
+ super().__init__()
516
+ self.embed_dim = config.d_model
517
+ self.is_sparse = is_sparse
518
+ self.self_attn = NllbMoeAttention(
519
+ embed_dim=self.embed_dim,
520
+ num_heads=config.encoder_attention_heads,
521
+ dropout=config.attention_dropout,
522
+ config=config,
523
+ layer_idx=layer_idx,
524
+ )
525
+ self.attn_dropout = nn.Dropout(config.dropout)
526
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
527
+ if not self.is_sparse:
528
+ self.ffn = NllbMoeDenseActDense(config, ffn_dim=config.encoder_ffn_dim)
529
+ else:
530
+ self.ffn = NllbMoeSparseMLP(config, ffn_dim=config.encoder_ffn_dim)
531
+ self.ff_layer_norm = nn.LayerNorm(config.d_model)
532
+ self.ff_dropout = nn.Dropout(config.activation_dropout)
533
+
534
+ def forward(
535
+ self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, **kwargs: Unpack[TransformersKwargs]
536
+ ) -> torch.Tensor:
537
+ residual = hidden_states
538
+ hidden_states = self.self_attn_layer_norm(hidden_states)
539
+ hidden_states, _ = self.self_attn(hidden_states, attention_mask=attention_mask, **kwargs)
540
+ hidden_states = self.attn_dropout(hidden_states)
541
+ hidden_states = residual + hidden_states
542
+ residual = hidden_states
543
+
544
+ hidden_states = self.ff_layer_norm(hidden_states)
545
+ if self.is_sparse:
546
+ hidden_states = self.ffn(hidden_states, attention_mask)
547
+ else:
548
+ hidden_states = self.ffn(hidden_states)
549
+ hidden_states = self.ff_dropout(hidden_states)
550
+ hidden_states = residual + hidden_states
551
+ if hidden_states.dtype == torch.float16 and not torch.isfinite(hidden_states).all():
552
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
553
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
554
+ return hidden_states
555
+
556
+
557
+ class NllbMoeDecoderLayer(GradientCheckpointingLayer):
558
+ def __init__(self, config: NllbMoeConfig, is_sparse: bool = False, layer_idx: int | None = None):
559
+ super().__init__()
560
+ self.embed_dim = config.d_model
561
+ self.is_sparse = is_sparse
562
+ self.self_attn = NllbMoeAttention(
563
+ embed_dim=self.embed_dim,
564
+ num_heads=config.decoder_attention_heads,
565
+ dropout=config.attention_dropout,
566
+ is_decoder=True,
567
+ config=config,
568
+ layer_idx=layer_idx,
569
+ )
570
+ self.dropout = config.dropout
571
+ self.activation_fn = ACT2FN[config.activation_function]
572
+ self.attn_dropout = nn.Dropout(config.dropout)
573
+
574
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
575
+ self.cross_attention = NllbMoeAttention(
576
+ self.embed_dim,
577
+ config.decoder_attention_heads,
578
+ config.attention_dropout,
579
+ is_decoder=True,
580
+ config=config,
581
+ layer_idx=layer_idx,
582
+ )
583
+ self.cross_attention_layer_norm = nn.LayerNorm(self.embed_dim)
584
+ if not self.is_sparse:
585
+ self.ffn = NllbMoeDenseActDense(config, ffn_dim=config.decoder_ffn_dim)
586
+ else:
587
+ self.ffn = NllbMoeSparseMLP(config, ffn_dim=config.decoder_ffn_dim)
588
+ self.ff_layer_norm = nn.LayerNorm(config.d_model)
589
+ self.ff_dropout = nn.Dropout(config.activation_dropout)
590
+
591
+ def forward(
592
+ self,
593
+ hidden_states: torch.Tensor,
594
+ attention_mask: torch.Tensor | None = None,
595
+ encoder_hidden_states: torch.Tensor | None = None,
596
+ encoder_attention_mask: torch.Tensor | None = None,
597
+ past_key_values: Cache | None = None,
598
+ **kwargs: Unpack[TransformersKwargs],
599
+ ) -> torch.Tensor:
600
+ residual = hidden_states
601
+ hidden_states = self.self_attn_layer_norm(hidden_states)
602
+
603
+ # Self Attention
604
+ hidden_states, _ = self.self_attn(
605
+ hidden_states=hidden_states,
606
+ past_key_values=past_key_values,
607
+ attention_mask=attention_mask,
608
+ **kwargs,
609
+ )
610
+ hidden_states = self.attn_dropout(hidden_states)
611
+ hidden_states = residual + hidden_states
612
+
613
+ if encoder_hidden_states is not None:
614
+ residual = hidden_states
615
+ hidden_states = self.cross_attention_layer_norm(hidden_states)
616
+
617
+ hidden_states, _ = self.cross_attention(
618
+ hidden_states=hidden_states,
619
+ key_value_states=encoder_hidden_states,
620
+ past_key_values=past_key_values,
621
+ attention_mask=encoder_attention_mask,
622
+ **kwargs,
623
+ )
624
+ hidden_states = self.attn_dropout(hidden_states)
625
+ hidden_states = residual + hidden_states
626
+
627
+ residual = hidden_states
628
+ hidden_states = self.ff_layer_norm(hidden_states)
629
+ if self.is_sparse:
630
+ hidden_states = self.ffn(hidden_states, attention_mask)
631
+ else:
632
+ hidden_states = self.ffn(hidden_states)
633
+
634
+ hidden_states = self.ff_dropout(hidden_states)
635
+ hidden_states = residual + hidden_states
636
+
637
+ # clamp inf values to enable fp16 training
638
+ if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
639
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
640
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
641
+
642
+ return hidden_states
643
+
644
+
645
+ @auto_docstring
646
+ class NllbMoePreTrainedModel(PreTrainedModel):
647
+ config: NllbMoeConfig
648
+ base_model_prefix = "model"
649
+ supports_gradient_checkpointing = True
650
+ _no_split_modules = ["NllbMoeEncoderLayer", "NllbMoeDecoderLayer"]
651
+ # TODO: If anyone is up to it to make sure tests pass etc
652
+ # Flash attention has problems due to not preparing masks the same way as eager/sdpa
653
+ # SDPA has more flaky logits which requires more time to look into tests
654
+ _supports_flash_attn = False
655
+ _supports_sdpa = False
656
+ _supports_flex_attn = False
657
+
658
+ def _init_weights(self, module):
659
+ super()._init_weights(module)
660
+ if isinstance(module, NllbMoeSinusoidalPositionalEmbedding):
661
+ emb_weights = module.get_embedding(
662
+ module.num_positions + module.offset, module.embedding_dim, module.padding_idx
663
+ )
664
+ init.copy_(module.weights, emb_weights)
665
+
666
+
667
+ class NllbMoeEncoder(NllbMoePreTrainedModel):
668
+ _can_record_outputs = {
669
+ "hidden_states": NllbMoeEncoderLayer,
670
+ "router_logits": OutputRecorder(NllbMoeTop2Router, index=2),
671
+ "attentions": NllbMoeAttention,
672
+ }
673
+
674
+ def __init__(self, config: NllbMoeConfig):
675
+ super().__init__(config)
676
+
677
+ self.dropout = config.dropout
678
+ self.layerdrop = config.encoder_layerdrop
679
+
680
+ embed_dim = config.d_model
681
+ self.padding_idx = config.pad_token_id
682
+ self.max_source_positions = config.max_position_embeddings
683
+ embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
684
+
685
+ self.embed_tokens = NllbMoeScaledWordEmbedding(
686
+ config.vocab_size, embed_dim, self.padding_idx, embed_scale=embed_scale
687
+ )
688
+
689
+ self.embed_positions = NllbMoeSinusoidalPositionalEmbedding(
690
+ config.max_position_embeddings,
691
+ embed_dim,
692
+ self.padding_idx,
693
+ )
694
+ sparse_step = config.encoder_sparse_step
695
+ self.layers = nn.ModuleList()
696
+ for i in range(config.encoder_layers):
697
+ is_sparse = (i + 1) % sparse_step == 0 if sparse_step > 0 else False
698
+ self.layers.append(NllbMoeEncoderLayer(config, is_sparse, layer_idx=i))
699
+
700
+ self.layer_norm = nn.LayerNorm(config.d_model)
701
+ self.gradient_checkpointing = False
702
+ self.post_init()
703
+
704
+ @merge_with_config_defaults
705
+ @capture_outputs
706
+ @auto_docstring
707
+ def forward(
708
+ self,
709
+ input_ids: torch.Tensor | None = None,
710
+ attention_mask: torch.Tensor | None = None,
711
+ inputs_embeds: torch.Tensor | None = None,
712
+ **kwargs: Unpack[TransformersKwargs],
713
+ ):
714
+ if inputs_embeds is None:
715
+ inputs_embeds = self.embed_tokens(input_ids)
716
+
717
+ embed_pos = self.embed_positions(input_ids, inputs_embeds)
718
+ embed_pos = embed_pos.to(inputs_embeds.device)
719
+
720
+ hidden_states = inputs_embeds + embed_pos
721
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
722
+
723
+ attention_mask = create_bidirectional_mask(
724
+ config=self.config,
725
+ inputs_embeds=inputs_embeds,
726
+ attention_mask=attention_mask,
727
+ )
728
+
729
+ for encoder_layer in self.layers:
730
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
731
+ dropout_probability = torch.rand([])
732
+ if self.training and (dropout_probability < self.layerdrop): # skip the layer
733
+ continue
734
+ else:
735
+ hidden_states = encoder_layer(hidden_states, attention_mask, **kwargs)
736
+
737
+ last_hidden_state = self.layer_norm(hidden_states)
738
+ return MoEModelOutput(last_hidden_state=last_hidden_state)
739
+
740
+
741
+ class NllbMoeDecoder(NllbMoePreTrainedModel):
742
+ """
743
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`NllbMoeDecoderLayer`]
744
+
745
+ Args:
746
+ config:
747
+ NllbMoeConfig
748
+ embed_tokens (nn.Embedding):
749
+ output embedding
750
+ """
751
+
752
+ _can_record_outputs = {
753
+ "hidden_states": NllbMoeDecoderLayer,
754
+ "attentions": OutputRecorder(NllbMoeAttention, layer_name="self_attn", index=1),
755
+ "router_logits": OutputRecorder(NllbMoeTop2Router, index=2),
756
+ "cross_attentions": OutputRecorder(NllbMoeAttention, layer_name="cross_attention", index=1),
757
+ }
758
+
759
+ def __init__(self, config: NllbMoeConfig):
760
+ super().__init__(config)
761
+ self.dropout = config.dropout
762
+ self.layerdrop = config.decoder_layerdrop
763
+ self.padding_idx = config.pad_token_id
764
+ self.max_target_positions = config.max_position_embeddings
765
+ embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
766
+
767
+ self.embed_tokens = NllbMoeScaledWordEmbedding(
768
+ config.vocab_size, config.d_model, self.padding_idx, embed_scale=embed_scale
769
+ )
770
+
771
+ self.embed_positions = NllbMoeSinusoidalPositionalEmbedding(
772
+ config.max_position_embeddings,
773
+ config.d_model,
774
+ self.padding_idx,
775
+ )
776
+
777
+ sparse_step = config.decoder_sparse_step
778
+ self.layers = nn.ModuleList()
779
+ for i in range(config.decoder_layers):
780
+ is_sparse = (i + 1) % sparse_step == 0 if sparse_step > 0 else False
781
+ self.layers.append(NllbMoeDecoderLayer(config, is_sparse, layer_idx=i))
782
+
783
+ self.layer_norm = nn.LayerNorm(config.d_model)
784
+
785
+ self.gradient_checkpointing = False
786
+ # Initialize weights and apply final processing
787
+ self.post_init()
788
+
789
+ @auto_docstring
790
+ @merge_with_config_defaults
791
+ @capture_outputs
792
+ def forward(
793
+ self,
794
+ input_ids: torch.Tensor | None = None,
795
+ attention_mask: torch.Tensor | None = None,
796
+ encoder_hidden_states: torch.Tensor | None = None,
797
+ encoder_attention_mask: torch.Tensor | None = None,
798
+ past_key_values: Cache | None = None,
799
+ inputs_embeds: torch.Tensor | None = None,
800
+ use_cache: bool | None = None,
801
+ **kwargs: Unpack[TransformersKwargs],
802
+ ) -> tuple | BaseModelOutputWithPastAndCrossAttentions:
803
+ if inputs_embeds is None:
804
+ inputs_embeds = self.embed_tokens(input_ids)
805
+
806
+ # initialize `past_key_values`
807
+ if use_cache and past_key_values is None:
808
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
809
+
810
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
811
+
812
+ attention_mask = create_causal_mask(
813
+ config=self.config,
814
+ inputs_embeds=inputs_embeds,
815
+ attention_mask=attention_mask,
816
+ past_key_values=past_key_values,
817
+ )
818
+ encoder_attention_mask = create_bidirectional_mask(
819
+ config=self.config,
820
+ inputs_embeds=inputs_embeds,
821
+ attention_mask=encoder_attention_mask,
822
+ encoder_hidden_states=encoder_hidden_states,
823
+ )
824
+
825
+ # embed positions
826
+ positions = self.embed_positions(input_ids, inputs_embeds, past_key_values_length)
827
+ positions = positions.to(inputs_embeds.device)
828
+
829
+ hidden_states = inputs_embeds + positions
830
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
831
+
832
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
833
+
834
+ for idx, decoder_layer in enumerate(self.layers):
835
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
836
+ dropout_probability = torch.rand([])
837
+ skip_the_layer = self.training and dropout_probability < self.layerdrop
838
+ if not skip_the_layer or synced_gpus:
839
+ hidden_states = decoder_layer(
840
+ hidden_states,
841
+ attention_mask,
842
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
843
+ encoder_attention_mask=encoder_attention_mask,
844
+ past_key_values=past_key_values,
845
+ use_cache=use_cache,
846
+ **kwargs,
847
+ )
848
+
849
+ if skip_the_layer:
850
+ continue
851
+
852
+ last_hidden_states = self.layer_norm(hidden_states)
853
+
854
+ return MoEModelOutputWithPastAndCrossAttentions(
855
+ last_hidden_state=last_hidden_states, past_key_values=past_key_values
856
+ )
857
+
858
+
859
+ @auto_docstring
860
+ class NllbMoeModel(NllbMoePreTrainedModel):
861
+ _tied_weights_keys = {
862
+ "encoder.embed_tokens.weight": "shared.weight",
863
+ "decoder.embed_tokens.weight": "shared.weight",
864
+ }
865
+
866
+ def __init__(self, config: NllbMoeConfig):
867
+ super().__init__(config)
868
+
869
+ padding_idx, vocab_size = config.pad_token_id, config.vocab_size
870
+ embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
871
+ self.shared = NllbMoeScaledWordEmbedding(vocab_size, config.d_model, padding_idx, embed_scale=embed_scale)
872
+
873
+ self.encoder = NllbMoeEncoder(config)
874
+ self.decoder = NllbMoeDecoder(config)
875
+
876
+ # Initialize weights and apply final processing
877
+ self.post_init()
878
+
879
+ def get_input_embeddings(self):
880
+ return self.shared
881
+
882
+ def set_input_embeddings(self, value):
883
+ self.shared = value
884
+ self.encoder.embed_tokens = self.shared
885
+ self.decoder.embed_tokens = self.shared
886
+
887
+ @auto_docstring
888
+ @can_return_tuple
889
+ def forward(
890
+ self,
891
+ input_ids: torch.LongTensor | None = None,
892
+ attention_mask: torch.Tensor | None = None,
893
+ decoder_input_ids: torch.LongTensor | None = None,
894
+ decoder_attention_mask: torch.LongTensor | None = None,
895
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
896
+ past_key_values: Cache | None = None,
897
+ inputs_embeds: torch.FloatTensor | None = None,
898
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
899
+ use_cache: bool | None = None,
900
+ **kwargs: Unpack[TransformersKwargs],
901
+ ) -> tuple[torch.Tensor] | Seq2SeqMoEModelOutput:
902
+ if encoder_outputs is None:
903
+ encoder_outputs = self.encoder(
904
+ input_ids=input_ids,
905
+ attention_mask=attention_mask,
906
+ inputs_embeds=inputs_embeds,
907
+ **kwargs,
908
+ )
909
+
910
+ # decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)
911
+ decoder_outputs = self.decoder(
912
+ input_ids=decoder_input_ids,
913
+ attention_mask=decoder_attention_mask,
914
+ encoder_hidden_states=encoder_outputs.last_hidden_state,
915
+ encoder_attention_mask=attention_mask,
916
+ past_key_values=past_key_values,
917
+ inputs_embeds=decoder_inputs_embeds,
918
+ use_cache=use_cache,
919
+ **kwargs,
920
+ )
921
+
922
+ return Seq2SeqMoEModelOutput(
923
+ past_key_values=decoder_outputs.past_key_values,
924
+ cross_attentions=decoder_outputs.cross_attentions,
925
+ last_hidden_state=decoder_outputs.last_hidden_state,
926
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
927
+ encoder_hidden_states=encoder_outputs.hidden_states,
928
+ decoder_hidden_states=decoder_outputs.hidden_states,
929
+ encoder_attentions=encoder_outputs.attentions,
930
+ decoder_attentions=decoder_outputs.attentions,
931
+ encoder_router_logits=encoder_outputs.router_logits,
932
+ decoder_router_logits=decoder_outputs.router_logits,
933
+ )
934
+
935
+
936
+ def load_balancing_loss_func(
937
+ gate_logits: torch.Tensor | tuple[torch.Tensor] | None,
938
+ num_experts: int | None = None,
939
+ top_k=2,
940
+ attention_mask: torch.Tensor | None = None,
941
+ ) -> torch.Tensor | int:
942
+ r"""
943
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
944
+
945
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
946
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
947
+ experts is too unbalanced.
948
+
949
+ Args:
950
+ gate_logits:
951
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
952
+ shape [batch_size X sequence_length, num_experts].
953
+ num_experts:
954
+ Number of experts
955
+ top_k:
956
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
957
+ parameter.
958
+ attention_mask (`torch.Tensor`, *optional*):
959
+ The attention_mask used in forward function
960
+ shape [batch_size X sequence_length] if not None.
961
+
962
+ Returns:
963
+ The auxiliary loss.
964
+ """
965
+ if gate_logits is None or not isinstance(gate_logits, tuple):
966
+ return 0
967
+
968
+ if isinstance(gate_logits, tuple):
969
+ compute_device = gate_logits[0].device
970
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
971
+
972
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
973
+
974
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
975
+
976
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
977
+
978
+ if attention_mask is None:
979
+ # Compute the percentage of tokens routed to each experts
980
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
981
+
982
+ # Compute the average probability of routing to these experts
983
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
984
+ else:
985
+ batch_size, sequence_length = attention_mask.shape
986
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
987
+
988
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
989
+ expert_attention_mask = (
990
+ attention_mask[None, :, :, None, None]
991
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
992
+ .reshape(-1, top_k, num_experts)
993
+ .to(compute_device)
994
+ )
995
+
996
+ # Compute the percentage of tokens routed to each experts
997
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
998
+ expert_attention_mask, dim=0
999
+ )
1000
+
1001
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
1002
+ router_per_expert_attention_mask = (
1003
+ attention_mask[None, :, :, None]
1004
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
1005
+ .reshape(-1, num_experts)
1006
+ .to(compute_device)
1007
+ )
1008
+
1009
+ # Compute the average probability of routing to these experts
1010
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
1011
+ router_per_expert_attention_mask, dim=0
1012
+ )
1013
+
1014
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
1015
+ return overall_loss * num_experts
1016
+
1017
+
1018
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
1019
+ """
1020
+ Shift input ids one token to the right.
1021
+ """
1022
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
1023
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
1024
+ shifted_input_ids[:, 0] = decoder_start_token_id
1025
+
1026
+ if pad_token_id is None:
1027
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
1028
+ # replace possible -100 values in labels by `pad_token_id`
1029
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
1030
+
1031
+ return shifted_input_ids
1032
+
1033
+
1034
+ @auto_docstring(
1035
+ custom_intro="""
1036
+ The NllbMoe Model with a language modeling head. Can be used for summarization.
1037
+ """
1038
+ )
1039
+ class NllbMoeForConditionalGeneration(NllbMoePreTrainedModel, GenerationMixin):
1040
+ base_model_prefix = "model"
1041
+ _tied_weights_keys = {
1042
+ "lm_head.weight": "model.shared.weight",
1043
+ }
1044
+
1045
+ def __init__(self, config: NllbMoeConfig):
1046
+ super().__init__(config)
1047
+ self.model = NllbMoeModel(config)
1048
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
1049
+ self.num_experts = config.num_experts
1050
+ self.router_z_loss_coef = config.router_z_loss_coef
1051
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1052
+ # Initialize weights and apply final processing
1053
+ self.post_init()
1054
+
1055
+ @can_return_tuple
1056
+ @auto_docstring
1057
+ def forward(
1058
+ self,
1059
+ input_ids: torch.LongTensor | None = None,
1060
+ attention_mask: torch.Tensor | None = None,
1061
+ decoder_input_ids: torch.LongTensor | None = None,
1062
+ decoder_attention_mask: torch.LongTensor | None = None,
1063
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
1064
+ past_key_values: Cache | None = None,
1065
+ inputs_embeds: torch.FloatTensor | None = None,
1066
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
1067
+ labels: torch.LongTensor | None = None,
1068
+ use_cache: bool | None = None,
1069
+ output_router_logits: bool | None = None,
1070
+ **kwargs: Unpack[TransformersKwargs],
1071
+ ) -> tuple[torch.Tensor] | Seq2SeqMoEOutput:
1072
+ output_router_logits = (
1073
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1074
+ )
1075
+ if labels is not None:
1076
+ if decoder_input_ids is None:
1077
+ decoder_input_ids = shift_tokens_right(
1078
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1079
+ )
1080
+
1081
+ outputs = self.model(
1082
+ input_ids,
1083
+ attention_mask=attention_mask,
1084
+ decoder_input_ids=decoder_input_ids,
1085
+ encoder_outputs=encoder_outputs,
1086
+ decoder_attention_mask=decoder_attention_mask,
1087
+ past_key_values=past_key_values,
1088
+ inputs_embeds=inputs_embeds,
1089
+ decoder_inputs_embeds=decoder_inputs_embeds,
1090
+ use_cache=use_cache,
1091
+ output_router_logits=output_router_logits,
1092
+ **kwargs,
1093
+ )
1094
+ lm_logits = self.lm_head(outputs[0])
1095
+
1096
+ loss = None
1097
+ encoder_aux_loss = None
1098
+ decoder_aux_loss = None
1099
+
1100
+ if labels is not None:
1101
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1102
+ # todo check in the config if router loss enables
1103
+
1104
+ if output_router_logits:
1105
+ encoder_router_logits = outputs.encoder_router_logits
1106
+ decoder_router_logits = outputs.decoder_router_logits
1107
+ encoder_aux_loss = load_balancing_loss_func(
1108
+ encoder_router_logits, self.num_experts, top_k=2, attention_mask=attention_mask
1109
+ )
1110
+ decoder_aux_loss = load_balancing_loss_func(
1111
+ decoder_router_logits, self.num_experts, top_k=2, attention_mask=decoder_attention_mask
1112
+ )
1113
+
1114
+ loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
1115
+
1116
+ if output_router_logits and labels is not None:
1117
+ aux_loss = self.router_aux_loss_coef * (encoder_aux_loss + decoder_aux_loss)
1118
+ loss = loss + aux_loss
1119
+
1120
+ return Seq2SeqMoEOutput(
1121
+ loss=loss,
1122
+ logits=lm_logits,
1123
+ past_key_values=outputs.past_key_values,
1124
+ cross_attentions=outputs.cross_attentions,
1125
+ encoder_aux_loss=encoder_aux_loss,
1126
+ decoder_aux_loss=decoder_aux_loss,
1127
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1128
+ encoder_hidden_states=outputs.encoder_hidden_states,
1129
+ decoder_hidden_states=outputs.decoder_hidden_states,
1130
+ encoder_attentions=outputs.encoder_attentions,
1131
+ decoder_attentions=outputs.decoder_attentions,
1132
+ encoder_router_logits=outputs.encoder_router_logits,
1133
+ decoder_router_logits=outputs.decoder_router_logits,
1134
+ )
1135
+
1136
+
1137
+ __all__ = [
1138
+ "NllbMoeForConditionalGeneration",
1139
+ "NllbMoeModel",
1140
+ "NllbMoePreTrainedModel",
1141
+ "NllbMoeTop2Router",
1142
+ "NllbMoeSparseMLP",
1143
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nomic_bert/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 the HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import _LazyModule
18
+ from ...utils.import_utils import define_import_structure
19
+
20
+
21
+ if TYPE_CHECKING:
22
+ from .configuration_nomic_bert import *
23
+ from .modeling_nomic_bert import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nomic_bert/configuration_nomic_bert.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/nomic_bert/modular_nomic_bert.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_nomic_bert.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 the HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+
22
+ from huggingface_hub.dataclasses import strict
23
+
24
+ from ...configuration_utils import PreTrainedConfig
25
+ from ...modeling_rope_utils import RopeParameters
26
+ from ...utils import auto_docstring
27
+
28
+
29
+ @auto_docstring(checkpoint="nomic-ai/nomic-embed-text-v1.5")
30
+ @strict
31
+ class NomicBertConfig(PreTrainedConfig):
32
+ r"""
33
+ Examples:
34
+
35
+ ```python
36
+ >>> from transformers import NomicBertConfig, NomicBertModel
37
+
38
+ >>> # Initializing a Nomic BERT nomic-ai/nomic-embed-text-v1.5 style configuration
39
+ >>> configuration = NomicBertConfig()
40
+
41
+ >>> # Initializing a model (with random weights) from the nomic-ai/nomic-embed-text-v1.5 style configuration
42
+ >>> model = NomicBertModel(configuration)
43
+
44
+ >>> # Accessing the model configuration
45
+ >>> configuration = model.config
46
+ ```"""
47
+
48
+ model_type = "nomic_bert"
49
+
50
+ vocab_size: int = 30528
51
+ hidden_size: int = 768
52
+ num_hidden_layers: int = 12
53
+ num_attention_heads: int = 12
54
+ intermediate_size: int = 3072
55
+ hidden_act: str = "silu"
56
+ hidden_dropout_prob: float = 0.0
57
+ attention_probs_dropout_prob: float = 0.0
58
+ max_position_embeddings: int = 2048
59
+ type_vocab_size: int = 2
60
+ initializer_range: float = 0.02
61
+ layer_norm_eps: float = 1e-12
62
+ pad_token_id: int = 0
63
+ classifier_dropout: float | None = None
64
+ bos_token_id: int | None = None
65
+ eos_token_id: int | None = None
66
+ tie_word_embeddings = True
67
+ default_theta = 1000.0
68
+ rope_parameters: RopeParameters | dict | None = None
69
+ head_dim: int | None = None
70
+
71
+ def __post_init__(self, **kwargs):
72
+ super().__post_init__(**kwargs)
73
+ if self.head_dim is None:
74
+ self.head_dim = self.hidden_size // self.num_attention_heads
75
+
76
+
77
+ __all__ = ["NomicBertConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nomic_bert/modeling_nomic_bert.py ADDED
@@ -0,0 +1,721 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/nomic_bert/modular_nomic_bert.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_nomic_bert.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 the HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+
22
+ from collections.abc import Callable
23
+ from typing import Optional
24
+
25
+ import torch
26
+ import torch.nn as nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from ... import initialization as init
30
+ from ...activations import ACT2FN
31
+ from ...integrations import use_kernel_func_from_hub, use_kernelized_func
32
+ from ...masking_utils import create_bidirectional_mask
33
+ from ...modeling_layers import GradientCheckpointingLayer
34
+ from ...modeling_outputs import (
35
+ BaseModelOutputWithPooling,
36
+ MaskedLMOutput,
37
+ SequenceClassifierOutput,
38
+ TokenClassifierOutput,
39
+ )
40
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
41
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
42
+ from ...processing_utils import Unpack
43
+ from ...utils import TransformersKwargs, auto_docstring
44
+ from ...utils.generic import can_return_tuple, maybe_autocast, merge_with_config_defaults
45
+ from ...utils.output_capturing import capture_outputs
46
+ from .configuration_nomic_bert import NomicBertConfig
47
+
48
+
49
+ class NomicBertEmbeddings(nn.Module):
50
+ """Construct the embeddings from word, position and token_type embeddings."""
51
+
52
+ def __init__(self, config: NomicBertConfig):
53
+ super().__init__()
54
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
55
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
56
+
57
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
58
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
59
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
60
+ self.register_buffer(
61
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
62
+ )
63
+ self.register_buffer(
64
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
65
+ )
66
+
67
+ def forward(
68
+ self,
69
+ input_ids: torch.LongTensor | None = None,
70
+ token_type_ids: torch.LongTensor | None = None,
71
+ position_ids: torch.LongTensor | None = None,
72
+ inputs_embeds: torch.FloatTensor | None = None,
73
+ ) -> torch.Tensor:
74
+ embeddings = inputs_embeds
75
+ if inputs_embeds is None:
76
+ embeddings = self.word_embeddings(input_ids)
77
+
78
+ input_shape = embeddings.shape[:-1]
79
+ device = embeddings.device
80
+
81
+ if token_type_ids is None:
82
+ if hasattr(self, "token_type_ids"):
83
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
84
+ buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
85
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
86
+ token_type_ids = buffered_token_type_ids.expand(*input_shape)
87
+ else:
88
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
89
+
90
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
91
+
92
+ embeddings = embeddings + token_type_embeddings
93
+ embeddings = self.LayerNorm(embeddings)
94
+ embeddings = self.dropout(embeddings)
95
+
96
+ return embeddings
97
+
98
+
99
+ class NomicBertRotaryEmbedding(nn.Module):
100
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
101
+
102
+ def __init__(self, config: NomicBertConfig, device=None):
103
+ super().__init__()
104
+ self.max_seq_len_cached = config.max_position_embeddings
105
+ self.original_max_seq_len = config.max_position_embeddings
106
+
107
+ self.config = config
108
+
109
+ self.rope_type = self.config.rope_parameters["rope_type"]
110
+ rope_init_fn: Callable = self.compute_default_rope_parameters
111
+ if self.rope_type != "default":
112
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
113
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
114
+
115
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
116
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
117
+
118
+ @staticmethod
119
+ def compute_default_rope_parameters(
120
+ config: NomicBertConfig | None = None,
121
+ device: Optional["torch.device"] = None,
122
+ seq_len: int | None = None,
123
+ ) -> tuple["torch.Tensor", float]:
124
+ """
125
+ Computes the inverse frequencies according to the original RoPE implementation
126
+ Args:
127
+ config ([`~transformers.PreTrainedConfig`]):
128
+ The model configuration.
129
+ device (`torch.device`):
130
+ The device to use for initialization of the inverse frequencies.
131
+ seq_len (`int`, *optional*):
132
+ The current sequence length. Unused for this type of RoPE.
133
+ Returns:
134
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
135
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
136
+ """
137
+ base = config.rope_parameters["rope_theta"]
138
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
139
+
140
+ attention_factor = 1.0 # Unused in this type of RoPE
141
+
142
+ # Compute the inverse frequencies
143
+ inv_freq = 1.0 / (
144
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
145
+ )
146
+ return inv_freq, attention_factor
147
+
148
+ @torch.no_grad()
149
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
150
+ def forward(self, x, position_ids):
151
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
152
+ position_ids_expanded = position_ids[:, None, :].float()
153
+
154
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
155
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
156
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
157
+ emb = torch.cat((freqs, freqs), dim=-1)
158
+ cos = emb.cos() * self.attention_scaling
159
+ sin = emb.sin() * self.attention_scaling
160
+
161
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
162
+
163
+
164
+ def rotate_half(x):
165
+ """Rotates half the hidden dims of the input."""
166
+ x1 = x[..., : x.shape[-1] // 2]
167
+ x2 = x[..., x.shape[-1] // 2 :]
168
+ return torch.cat((-x2, x1), dim=-1)
169
+
170
+
171
+ @use_kernel_func_from_hub("rotary_pos_emb")
172
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
173
+ """Applies Rotary Position Embedding to the query and key tensors.
174
+
175
+ Args:
176
+ q (`torch.Tensor`): The query tensor.
177
+ k (`torch.Tensor`): The key tensor.
178
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
179
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
180
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
181
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
182
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
183
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
184
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
185
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
186
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
187
+ Returns:
188
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
189
+ """
190
+ cos = cos.unsqueeze(unsqueeze_dim)
191
+ sin = sin.unsqueeze(unsqueeze_dim)
192
+ q_embed = (q * cos) + (rotate_half(q) * sin)
193
+ k_embed = (k * cos) + (rotate_half(k) * sin)
194
+ return q_embed, k_embed
195
+
196
+
197
+ def eager_attention_forward(
198
+ module: nn.Module,
199
+ query: torch.Tensor,
200
+ key: torch.Tensor,
201
+ value: torch.Tensor,
202
+ attention_mask: torch.Tensor | None,
203
+ scaling: float | None = None,
204
+ dropout: float = 0.0,
205
+ **kwargs: Unpack[TransformersKwargs],
206
+ ):
207
+ if scaling is None:
208
+ scaling = query.size(-1) ** -0.5
209
+
210
+ # Take the dot product between "query" and "key" to get the raw attention scores.
211
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
212
+
213
+ if attention_mask is not None:
214
+ attn_weights = attn_weights + attention_mask
215
+
216
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
217
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
218
+
219
+ attn_output = torch.matmul(attn_weights, value)
220
+ attn_output = attn_output.transpose(1, 2).contiguous()
221
+
222
+ return attn_output, attn_weights
223
+
224
+
225
+ @use_kernelized_func(apply_rotary_pos_emb)
226
+ class NomicBertAttention(nn.Module):
227
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
228
+
229
+ def __init__(self, config):
230
+ super().__init__()
231
+ self.config = config
232
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
233
+ self.scaling = self.head_dim**-0.5
234
+ self.attention_dropout = config.attention_probs_dropout_prob
235
+ self.is_causal = False
236
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
237
+ self.k_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
238
+ self.v_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
239
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
240
+
241
+ def forward(
242
+ self,
243
+ hidden_states: torch.Tensor,
244
+ attention_mask: torch.Tensor | None = None,
245
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
246
+ **kwargs: Unpack[TransformersKwargs],
247
+ ) -> tuple[torch.Tensor]:
248
+ input_shape = hidden_states.shape[:-1]
249
+ hidden_shape = (*input_shape, -1, self.head_dim)
250
+
251
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
252
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
253
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
254
+
255
+ cos, sin = position_embeddings
256
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
257
+
258
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
259
+ self.config._attn_implementation, eager_attention_forward
260
+ )
261
+
262
+ attn_output, attn_weights = attention_interface(
263
+ self,
264
+ query_states,
265
+ key_states,
266
+ value_states,
267
+ attention_mask,
268
+ dropout=0.0 if not self.training else self.attention_dropout,
269
+ scaling=self.scaling,
270
+ **kwargs,
271
+ )
272
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
273
+ attn_output = self.o_proj(attn_output)
274
+ return attn_output, attn_weights
275
+
276
+
277
+ class NomicBertMLP(nn.Module):
278
+ def __init__(self, config):
279
+ super().__init__()
280
+ self.config = config
281
+ self.hidden_size = config.hidden_size
282
+ self.intermediate_size = config.intermediate_size
283
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
284
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
285
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
286
+ self.act_fn = ACT2FN[config.hidden_act]
287
+
288
+ def forward(self, x):
289
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
290
+ return down_proj
291
+
292
+
293
+ class NomicBertLayer(GradientCheckpointingLayer):
294
+ def __init__(self, config: NomicBertConfig):
295
+ super().__init__()
296
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
297
+
298
+ self.post_attention_dropout = nn.Dropout(config.hidden_dropout_prob)
299
+ self.post_mlp_dropout = nn.Dropout(config.hidden_dropout_prob)
300
+ self.mlp = NomicBertMLP(config)
301
+ self.self_attn = NomicBertAttention(config=config)
302
+ self.post_mlp_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
303
+
304
+ def forward(
305
+ self,
306
+ hidden_states: torch.Tensor,
307
+ attention_mask: torch.Tensor | None = None,
308
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
309
+ **kwargs: Unpack[TransformersKwargs],
310
+ ) -> torch.FloatTensor:
311
+ residual = hidden_states
312
+ attention_output, _ = self.self_attn(
313
+ hidden_states,
314
+ attention_mask=attention_mask,
315
+ position_embeddings=position_embeddings,
316
+ **kwargs,
317
+ )
318
+ hidden_states = residual + self.post_attention_dropout(attention_output)
319
+ hidden_states = self.post_attention_layernorm(hidden_states)
320
+
321
+ residual = hidden_states
322
+ hidden_states = self.mlp(hidden_states)
323
+ hidden_states = residual + self.post_mlp_dropout(hidden_states)
324
+ hidden_states = self.post_mlp_layernorm(hidden_states)
325
+ return hidden_states
326
+
327
+
328
+ class NomicBertLMPredictionHead(nn.Module):
329
+ def __init__(self, config):
330
+ super().__init__()
331
+ self.transform = NomicBertPredictionHeadTransform(config)
332
+
333
+ # The output weights are the same as the input embeddings, but there is
334
+ # an output-only bias for each token.
335
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
336
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
337
+
338
+ def forward(self, hidden_states):
339
+ hidden_states = self.transform(hidden_states)
340
+ hidden_states = self.decoder(hidden_states)
341
+ return hidden_states
342
+
343
+
344
+ @auto_docstring
345
+ class NomicBertPreTrainedModel(PreTrainedModel):
346
+ config_class = NomicBertConfig
347
+ base_model_prefix = "nomic_bert"
348
+ supports_gradient_checkpointing = True
349
+ _supports_flash_attn = True
350
+ _supports_sdpa = True
351
+ _supports_flex_attn = True
352
+ _supports_attention_backend = True
353
+ _can_record_outputs = {
354
+ "hidden_states": NomicBertLayer,
355
+ "attentions": NomicBertAttention,
356
+ }
357
+
358
+ # Are kept as non-persistent buffers to avoid being saved in the state dict
359
+ # and causing mismatch when loading from a checkpoint that doesn't have them
360
+ _keys_to_ignore_on_load_unexpected = ["inv_freq", "original_inv_freq"]
361
+
362
+ @torch.no_grad()
363
+ def _init_weights(self, module):
364
+ """Initialize the weights"""
365
+ super()._init_weights(module)
366
+ if isinstance(module, NomicBertLMPredictionHead):
367
+ init.zeros_(module.bias)
368
+ elif isinstance(module, NomicBertEmbeddings):
369
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
370
+ init.zeros_(module.token_type_ids)
371
+
372
+
373
+ class NomicBertPooler(nn.Module):
374
+ def __init__(self, config):
375
+ super().__init__()
376
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
377
+ self.activation = nn.Tanh()
378
+
379
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
380
+ # We "pool" the model by simply taking the hidden state corresponding
381
+ # to the first token.
382
+ first_token_tensor = hidden_states[:, 0]
383
+ pooled_output = self.dense(first_token_tensor)
384
+ pooled_output = self.activation(pooled_output)
385
+ return pooled_output
386
+
387
+
388
+ @auto_docstring
389
+ class NomicBertModel(NomicBertPreTrainedModel):
390
+ _no_split_modules = ["NomicBertEmbeddings", "NomicBertLayer"]
391
+
392
+ def __init__(self, config, add_pooling_layer=False):
393
+ r"""
394
+ add_pooling_layer (`bool`, *optional*, defaults to `False`):
395
+ Whether to add a pooling layer.
396
+ """
397
+ super().__init__(config)
398
+ self.config = config
399
+ self.gradient_checkpointing = False
400
+
401
+ self.embeddings = NomicBertEmbeddings(config)
402
+
403
+ self.pooler = NomicBertPooler(config) if add_pooling_layer else None
404
+ self.rotary_emb = NomicBertRotaryEmbedding(config)
405
+ self.layers = nn.ModuleList([NomicBertLayer(config) for _ in range(config.num_hidden_layers)])
406
+
407
+ # Initialize weights and apply final processing
408
+ self.post_init()
409
+
410
+ def get_input_embeddings(self):
411
+ return self.embeddings.word_embeddings
412
+
413
+ def set_input_embeddings(self, value):
414
+ self.embeddings.word_embeddings = value
415
+
416
+ @merge_with_config_defaults
417
+ @capture_outputs
418
+ @auto_docstring
419
+ def forward(
420
+ self,
421
+ input_ids: torch.LongTensor | None = None,
422
+ attention_mask: torch.Tensor | None = None,
423
+ token_type_ids: torch.LongTensor | None = None,
424
+ position_ids: torch.LongTensor | None = None,
425
+ inputs_embeds: torch.FloatTensor | None = None,
426
+ **kwargs: Unpack[TransformersKwargs],
427
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPooling:
428
+ if (input_ids is None) ^ (inputs_embeds is not None):
429
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
430
+
431
+ if input_ids is not None:
432
+ seq_length = input_ids.shape[1]
433
+ device = input_ids.device
434
+ else:
435
+ seq_length = inputs_embeds.shape[1]
436
+ device = inputs_embeds.device
437
+
438
+ if position_ids is None:
439
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device)[None, :]
440
+
441
+ embedding_output = self.embeddings(
442
+ input_ids=input_ids,
443
+ position_ids=position_ids,
444
+ token_type_ids=token_type_ids,
445
+ inputs_embeds=inputs_embeds,
446
+ )
447
+
448
+ attention_mask = create_bidirectional_mask(
449
+ config=self.config,
450
+ inputs_embeds=embedding_output,
451
+ attention_mask=attention_mask,
452
+ )
453
+
454
+ hidden_states = embedding_output
455
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
456
+
457
+ for encoder_layer in self.layers[: self.config.num_hidden_layers]:
458
+ hidden_states = encoder_layer(
459
+ hidden_states,
460
+ attention_mask=attention_mask,
461
+ position_embeddings=position_embeddings,
462
+ position_ids=position_ids,
463
+ **kwargs,
464
+ )
465
+
466
+ sequence_output = hidden_states
467
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
468
+
469
+ return BaseModelOutputWithPooling(
470
+ last_hidden_state=hidden_states,
471
+ pooler_output=pooled_output,
472
+ )
473
+
474
+
475
+ class NomicBertPredictionHeadTransform(nn.Module):
476
+ def __init__(self, config):
477
+ super().__init__()
478
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
479
+ if isinstance(config.hidden_act, str):
480
+ self.transform_act_fn = ACT2FN[config.hidden_act]
481
+ else:
482
+ self.transform_act_fn = config.hidden_act
483
+ # Use layer_norm rather than LayerNorm to avoid bert legacy mappings weights and bias to gamma and beta
484
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
485
+
486
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
487
+ hidden_states = self.dense(hidden_states)
488
+ hidden_states = self.transform_act_fn(hidden_states)
489
+ hidden_states = self.layer_norm(hidden_states)
490
+ return hidden_states
491
+
492
+
493
+ class NomicBertOnlyMLMHead(nn.Module):
494
+ def __init__(self, config):
495
+ super().__init__()
496
+ self.predictions = NomicBertLMPredictionHead(config)
497
+
498
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
499
+ prediction_scores = self.predictions(sequence_output)
500
+ return prediction_scores
501
+
502
+
503
+ @auto_docstring
504
+ class NomicBertForMaskedLM(NomicBertPreTrainedModel):
505
+ _tied_weights_keys = {
506
+ "cls.predictions.decoder.weight": "nomic_bert.embeddings.word_embeddings.weight",
507
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
508
+ }
509
+
510
+ def __init__(self, config):
511
+ super().__init__(config)
512
+
513
+ self.nomic_bert = NomicBertModel(config)
514
+ self.cls = NomicBertOnlyMLMHead(config)
515
+
516
+ # Initialize weights and apply final processing
517
+ self.post_init()
518
+
519
+ def get_output_embeddings(self):
520
+ return self.cls.predictions.decoder
521
+
522
+ def set_output_embeddings(self, new_embeddings):
523
+ self.cls.predictions.decoder = new_embeddings
524
+ self.cls.predictions.bias = new_embeddings.bias
525
+
526
+ @can_return_tuple
527
+ @auto_docstring
528
+ def forward(
529
+ self,
530
+ input_ids: torch.Tensor | None = None,
531
+ attention_mask: torch.Tensor | None = None,
532
+ token_type_ids: torch.Tensor | None = None,
533
+ position_ids: torch.Tensor | None = None,
534
+ inputs_embeds: torch.Tensor | None = None,
535
+ labels: torch.Tensor | None = None,
536
+ **kwargs: Unpack[TransformersKwargs],
537
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
538
+ r"""
539
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
540
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
541
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
542
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
543
+ """
544
+ outputs = self.nomic_bert(
545
+ input_ids,
546
+ attention_mask=attention_mask,
547
+ token_type_ids=token_type_ids,
548
+ position_ids=position_ids,
549
+ inputs_embeds=inputs_embeds,
550
+ return_dict=True,
551
+ **kwargs,
552
+ )
553
+
554
+ sequence_output = outputs[0]
555
+ prediction_scores = self.cls(sequence_output)
556
+
557
+ masked_lm_loss = None
558
+ if labels is not None:
559
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
560
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
561
+
562
+ return MaskedLMOutput(
563
+ loss=masked_lm_loss,
564
+ logits=prediction_scores,
565
+ hidden_states=outputs.hidden_states,
566
+ attentions=outputs.attentions,
567
+ )
568
+
569
+
570
+ @auto_docstring(
571
+ custom_intro="""
572
+ NomicBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
573
+ output) e.g. for GLUE tasks.
574
+ """
575
+ )
576
+ class NomicBertForSequenceClassification(NomicBertPreTrainedModel):
577
+ def __init__(self, config):
578
+ super().__init__(config)
579
+ self.num_labels = config.num_labels
580
+ self.config = config
581
+ self.nomic_bert = NomicBertModel(config, add_pooling_layer=True)
582
+ classifier_dropout = (
583
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
584
+ )
585
+ self.dropout = nn.Dropout(classifier_dropout)
586
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
587
+
588
+ # Initialize weights and apply final processing
589
+ self.post_init()
590
+
591
+ @can_return_tuple
592
+ @auto_docstring
593
+ def forward(
594
+ self,
595
+ input_ids: torch.Tensor | None = None,
596
+ attention_mask: torch.Tensor | None = None,
597
+ token_type_ids: torch.Tensor | None = None,
598
+ position_ids: torch.Tensor | None = None,
599
+ inputs_embeds: torch.Tensor | None = None,
600
+ labels: torch.Tensor | None = None,
601
+ **kwargs: Unpack[TransformersKwargs],
602
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
603
+ r"""
604
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
605
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
606
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
607
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
608
+ """
609
+ outputs = self.nomic_bert(
610
+ input_ids,
611
+ attention_mask=attention_mask,
612
+ token_type_ids=token_type_ids,
613
+ position_ids=position_ids,
614
+ inputs_embeds=inputs_embeds,
615
+ return_dict=True,
616
+ **kwargs,
617
+ )
618
+
619
+ pooled_output = outputs[1]
620
+
621
+ pooled_output = self.dropout(pooled_output)
622
+ logits = self.classifier(pooled_output)
623
+
624
+ loss = None
625
+ if labels is not None:
626
+ if self.config.problem_type is None:
627
+ if self.num_labels == 1:
628
+ self.config.problem_type = "regression"
629
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
630
+ self.config.problem_type = "single_label_classification"
631
+ else:
632
+ self.config.problem_type = "multi_label_classification"
633
+
634
+ if self.config.problem_type == "regression":
635
+ loss_fct = MSELoss()
636
+ if self.num_labels == 1:
637
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
638
+ else:
639
+ loss = loss_fct(logits, labels)
640
+ elif self.config.problem_type == "single_label_classification":
641
+ loss_fct = CrossEntropyLoss()
642
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
643
+ elif self.config.problem_type == "multi_label_classification":
644
+ loss_fct = BCEWithLogitsLoss()
645
+ loss = loss_fct(logits, labels)
646
+
647
+ return SequenceClassifierOutput(
648
+ loss=loss,
649
+ logits=logits,
650
+ hidden_states=outputs.hidden_states,
651
+ attentions=outputs.attentions,
652
+ )
653
+
654
+
655
+ @auto_docstring
656
+ class NomicBertForTokenClassification(NomicBertPreTrainedModel):
657
+ def __init__(self, config):
658
+ super().__init__(config)
659
+ self.num_labels = config.num_labels
660
+
661
+ self.nomic_bert = NomicBertModel(config, add_pooling_layer=False)
662
+ classifier_dropout = (
663
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
664
+ )
665
+ self.dropout = nn.Dropout(classifier_dropout)
666
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
667
+
668
+ # Initialize weights and apply final processing
669
+ self.post_init()
670
+
671
+ @can_return_tuple
672
+ @auto_docstring
673
+ def forward(
674
+ self,
675
+ input_ids: torch.Tensor | None = None,
676
+ attention_mask: torch.Tensor | None = None,
677
+ token_type_ids: torch.Tensor | None = None,
678
+ position_ids: torch.Tensor | None = None,
679
+ inputs_embeds: torch.Tensor | None = None,
680
+ labels: torch.Tensor | None = None,
681
+ **kwargs: Unpack[TransformersKwargs],
682
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
683
+ r"""
684
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
685
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
686
+ """
687
+ outputs = self.nomic_bert(
688
+ input_ids,
689
+ attention_mask=attention_mask,
690
+ token_type_ids=token_type_ids,
691
+ position_ids=position_ids,
692
+ inputs_embeds=inputs_embeds,
693
+ return_dict=True,
694
+ **kwargs,
695
+ )
696
+
697
+ sequence_output = outputs[0]
698
+
699
+ sequence_output = self.dropout(sequence_output)
700
+ logits = self.classifier(sequence_output)
701
+
702
+ loss = None
703
+ if labels is not None:
704
+ loss_fct = CrossEntropyLoss()
705
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
706
+
707
+ return TokenClassifierOutput(
708
+ loss=loss,
709
+ logits=logits,
710
+ hidden_states=outputs.hidden_states,
711
+ attentions=outputs.attentions,
712
+ )
713
+
714
+
715
+ __all__ = [
716
+ "NomicBertPreTrainedModel",
717
+ "NomicBertModel",
718
+ "NomicBertForMaskedLM",
719
+ "NomicBertForSequenceClassification",
720
+ "NomicBertForTokenClassification",
721
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nomic_bert/modular_nomic_bert.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 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
+
16
+ import torch
17
+ import torch.nn as nn
18
+ from huggingface_hub.dataclasses import strict
19
+ from torch.nn import CrossEntropyLoss
20
+
21
+ from ...configuration_utils import PreTrainedConfig
22
+ from ...masking_utils import create_bidirectional_mask
23
+ from ...modeling_outputs import (
24
+ BaseModelOutputWithPooling,
25
+ MaskedLMOutput,
26
+ )
27
+ from ...modeling_rope_utils import RopeParameters
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...processing_utils import Unpack
30
+ from ...utils import TransformersKwargs, auto_docstring
31
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
32
+ from ...utils.output_capturing import capture_outputs
33
+ from ..bert.configuration_bert import BertConfig
34
+ from ..bert.modeling_bert import (
35
+ BertForMaskedLM,
36
+ BertForSequenceClassification,
37
+ BertForTokenClassification,
38
+ BertOnlyMLMHead,
39
+ BertPredictionHeadTransform,
40
+ BertPreTrainedModel,
41
+ )
42
+ from ..gemma.modeling_gemma import GemmaMLP
43
+ from ..jina_embeddings_v3.modeling_jina_embeddings_v3 import (
44
+ JinaEmbeddingsV3Attention,
45
+ JinaEmbeddingsV3Embeddings,
46
+ JinaEmbeddingsV3Layer,
47
+ JinaEmbeddingsV3Model,
48
+ )
49
+ from ..llama.modeling_llama import LlamaRotaryEmbedding
50
+
51
+
52
+ @auto_docstring(checkpoint="nomic-ai/nomic-embed-text-v1.5")
53
+ @strict
54
+ class NomicBertConfig(BertConfig):
55
+ r"""
56
+ Examples:
57
+
58
+ ```python
59
+ >>> from transformers import NomicBertConfig, NomicBertModel
60
+
61
+ >>> # Initializing a Nomic BERT nomic-ai/nomic-embed-text-v1.5 style configuration
62
+ >>> configuration = NomicBertConfig()
63
+
64
+ >>> # Initializing a model (with random weights) from the nomic-ai/nomic-embed-text-v1.5 style configuration
65
+ >>> model = NomicBertModel(configuration)
66
+
67
+ >>> # Accessing the model configuration
68
+ >>> configuration = model.config
69
+ ```"""
70
+
71
+ model_type = "nomic_bert"
72
+ default_theta = 1000.0
73
+
74
+ vocab_size: int = 30528
75
+ hidden_size: int = 768
76
+ num_hidden_layers: int = 12
77
+ num_attention_heads: int = 12
78
+ intermediate_size: int = 3072
79
+ hidden_act: str = "silu"
80
+ hidden_dropout_prob: float = 0.0
81
+ attention_probs_dropout_prob: float = 0.0
82
+ initializer_range: float = 0.02
83
+ layer_norm_eps: float = 1e-12
84
+ classifier_dropout: float | None = None
85
+ type_vocab_size: int = 2
86
+ bos_token_id: int | None = None
87
+ eos_token_id: int | None = None
88
+ pad_token_id: int = 0
89
+ tie_word_embeddings = True
90
+ rope_parameters: RopeParameters | dict | None = None
91
+ max_position_embeddings: int = 2048
92
+ head_dim: int | None = None
93
+ is_decoder = AttributeError()
94
+ add_cross_attention = AttributeError()
95
+ use_cache = AttributeError()
96
+
97
+ def __post_init__(self, **kwargs):
98
+ PreTrainedConfig.__post_init__(self, **kwargs)
99
+ if self.head_dim is None:
100
+ self.head_dim = self.hidden_size // self.num_attention_heads
101
+
102
+
103
+ class NomicBertEmbeddings(JinaEmbeddingsV3Embeddings):
104
+ pass
105
+
106
+
107
+ class NomicBertRotaryEmbedding(LlamaRotaryEmbedding):
108
+ pass
109
+
110
+
111
+ class NomicBertAttention(JinaEmbeddingsV3Attention):
112
+ def __init__(self, config):
113
+ super().__init__(config)
114
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
115
+ self.k_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
116
+ self.v_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
117
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
118
+
119
+
120
+ class NomicBertMLP(GemmaMLP):
121
+ pass
122
+
123
+
124
+ class NomicBertLayer(JinaEmbeddingsV3Layer):
125
+ pass
126
+
127
+
128
+ class NomicBertPreTrainedModel(BertPreTrainedModel):
129
+ config_class = NomicBertConfig
130
+ base_model_prefix = "nomic_bert"
131
+
132
+ # Are kept as non-persistent buffers to avoid being saved in the state dict
133
+ # and causing mismatch when loading from a checkpoint that doesn't have them
134
+ _keys_to_ignore_on_load_unexpected = ["inv_freq", "original_inv_freq"]
135
+ _can_record_outputs = {
136
+ "hidden_states": NomicBertLayer,
137
+ "attentions": NomicBertAttention,
138
+ }
139
+
140
+
141
+ @auto_docstring
142
+ class NomicBertModel(JinaEmbeddingsV3Model):
143
+ def __init__(self, config, add_pooling_layer=False):
144
+ r"""
145
+ add_pooling_layer (`bool`, *optional*, defaults to `False`):
146
+ Whether to add a pooling layer.
147
+ """
148
+ super().__init__(config, add_pooling_layer=add_pooling_layer)
149
+
150
+ @merge_with_config_defaults
151
+ @capture_outputs
152
+ @auto_docstring
153
+ def forward(
154
+ self,
155
+ input_ids: torch.LongTensor | None = None,
156
+ attention_mask: torch.Tensor | None = None,
157
+ token_type_ids: torch.LongTensor | None = None,
158
+ position_ids: torch.LongTensor | None = None,
159
+ inputs_embeds: torch.FloatTensor | None = None,
160
+ **kwargs: Unpack[TransformersKwargs],
161
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPooling:
162
+ if (input_ids is None) ^ (inputs_embeds is not None):
163
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
164
+
165
+ if input_ids is not None:
166
+ seq_length = input_ids.shape[1]
167
+ device = input_ids.device
168
+ else:
169
+ seq_length = inputs_embeds.shape[1]
170
+ device = inputs_embeds.device
171
+
172
+ if position_ids is None:
173
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device)[None, :]
174
+
175
+ embedding_output = self.embeddings(
176
+ input_ids=input_ids,
177
+ position_ids=position_ids,
178
+ token_type_ids=token_type_ids,
179
+ inputs_embeds=inputs_embeds,
180
+ )
181
+
182
+ attention_mask = create_bidirectional_mask(
183
+ config=self.config,
184
+ inputs_embeds=embedding_output,
185
+ attention_mask=attention_mask,
186
+ )
187
+
188
+ hidden_states = embedding_output
189
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
190
+
191
+ for encoder_layer in self.layers[: self.config.num_hidden_layers]:
192
+ hidden_states = encoder_layer(
193
+ hidden_states,
194
+ attention_mask=attention_mask,
195
+ position_embeddings=position_embeddings,
196
+ position_ids=position_ids,
197
+ **kwargs,
198
+ )
199
+
200
+ sequence_output = hidden_states
201
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
202
+
203
+ return BaseModelOutputWithPooling(
204
+ last_hidden_state=hidden_states,
205
+ pooler_output=pooled_output,
206
+ )
207
+
208
+
209
+ class NomicBertPredictionHeadTransform(BertPredictionHeadTransform):
210
+ def __init__(self, config):
211
+ super().__init__(config)
212
+ # Use layer_norm rather than LayerNorm to avoid bert legacy mappings weights and bias to gamma and beta
213
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
214
+ del self.LayerNorm
215
+
216
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
217
+ hidden_states = self.dense(hidden_states)
218
+ hidden_states = self.transform_act_fn(hidden_states)
219
+ hidden_states = self.layer_norm(hidden_states)
220
+ return hidden_states
221
+
222
+
223
+ class NomicBertOnlyMLMHead(BertOnlyMLMHead):
224
+ pass
225
+
226
+
227
+ @auto_docstring
228
+ class NomicBertForMaskedLM(BertForMaskedLM):
229
+ def __init__(self, config):
230
+ PreTrainedModel.__init__(self, config)
231
+
232
+ self.nomic_bert = NomicBertModel(config)
233
+ self.cls = NomicBertOnlyMLMHead(config)
234
+
235
+ # Initialize weights and apply final processing
236
+ self.post_init()
237
+
238
+ @can_return_tuple
239
+ @auto_docstring
240
+ def forward(
241
+ self,
242
+ input_ids: torch.Tensor | None = None,
243
+ attention_mask: torch.Tensor | None = None,
244
+ token_type_ids: torch.Tensor | None = None,
245
+ position_ids: torch.Tensor | None = None,
246
+ inputs_embeds: torch.Tensor | None = None,
247
+ labels: torch.Tensor | None = None,
248
+ **kwargs: Unpack[TransformersKwargs],
249
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
250
+ r"""
251
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
252
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
253
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
254
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
255
+ """
256
+ outputs = self.nomic_bert(
257
+ input_ids,
258
+ attention_mask=attention_mask,
259
+ token_type_ids=token_type_ids,
260
+ position_ids=position_ids,
261
+ inputs_embeds=inputs_embeds,
262
+ return_dict=True,
263
+ **kwargs,
264
+ )
265
+
266
+ sequence_output = outputs[0]
267
+ prediction_scores = self.cls(sequence_output)
268
+
269
+ masked_lm_loss = None
270
+ if labels is not None:
271
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
272
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
273
+
274
+ return MaskedLMOutput(
275
+ loss=masked_lm_loss,
276
+ logits=prediction_scores,
277
+ hidden_states=outputs.hidden_states,
278
+ attentions=outputs.attentions,
279
+ )
280
+
281
+
282
+ class NomicBertForSequenceClassification(BertForSequenceClassification):
283
+ def __init__(self, config):
284
+ super().__init__(config)
285
+ self.nomic_bert = NomicBertModel(config, add_pooling_layer=True)
286
+
287
+
288
+ class NomicBertForTokenClassification(BertForTokenClassification):
289
+ pass
290
+
291
+
292
+ __all__ = [
293
+ "NomicBertConfig",
294
+ "NomicBertPreTrainedModel",
295
+ "NomicBertModel",
296
+ "NomicBertForMaskedLM",
297
+ "NomicBertForSequenceClassification",
298
+ "NomicBertForTokenClassification",
299
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nougat/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .image_processing_nougat import *
22
+ from .image_processing_pil_nougat import *
23
+ from .processing_nougat import *
24
+ from .tokenization_nougat import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nougat/configuration_nougat.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...configuration_utils import PreTrainedConfig
19
+ from ...utils import auto_docstring, logging
20
+ from ..auto.configuration_auto import AutoConfig
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ @auto_docstring(checkpoint="facebook/nougat-base")
27
+ @strict
28
+ class NougatConfig(PreTrainedConfig):
29
+ r"""
30
+ encoder (`dict | PreTrainedConfig`):
31
+ The config object or dictionary of the encoder backbone.
32
+ decoder (`dict | PreTrainedConfig`):
33
+ The config object or dictionary of the decoder backbone.
34
+
35
+ Examples:
36
+
37
+ ```python
38
+ >>> from transformers import NougatConfig, VisionEncoderDecoderModel
39
+
40
+ >>> # Initializing a Nougat configuration
41
+ >>> config = NougatConfig()
42
+
43
+ >>> # Initializing a VisionEncoderDecoder model (with random weights) from a Nougat configurations
44
+ >>> model = VisionEncoderDecoderModel(config=config)
45
+ ```"""
46
+
47
+ model_type = "nougat"
48
+ sub_configs = {"encoder": AutoConfig, "decoder": AutoConfig}
49
+
50
+ encoder: dict | PreTrainedConfig | None = None
51
+ decoder: dict | PreTrainedConfig | None = None
52
+ is_encoder_decoder: bool = True
53
+
54
+ def __post_init__(self, **kwargs):
55
+ if self.encoder is None or self.decoder is None:
56
+ raise ValueError(
57
+ f"A configuration of type {self.model_type} cannot be instantiated because "
58
+ f"one of both `encoder` or `decoder` sub-configurations is not passed."
59
+ )
60
+
61
+ if isinstance(self.encoder, dict):
62
+ encoder_model_type = self.encoder.pop("model_type")
63
+ self.encoder = AutoConfig.for_model(encoder_model_type, **self.encoder)
64
+ if isinstance(self.decoder, dict):
65
+ decoder_model_type = self.decoder.pop("model_type")
66
+ self.decoder = AutoConfig.for_model(decoder_model_type, **self.decoder)
67
+ super().__post_init__(**kwargs)
68
+
69
+ @classmethod
70
+ def from_encoder_decoder_configs(
71
+ cls, encoder_config: PreTrainedConfig, decoder_config: PreTrainedConfig, **kwargs
72
+ ) -> PreTrainedConfig:
73
+ r"""
74
+ Instantiate a [`VisionEncoderDecoderConfig`] (or a derived class) from a pre-trained encoder model
75
+ configuration and decoder model configuration.
76
+
77
+ Returns:
78
+ [`VisionEncoderDecoderConfig`]: An instance of a configuration object
79
+ """
80
+ logger.info("Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config")
81
+ decoder_config.is_decoder = True
82
+ decoder_config.add_cross_attention = True
83
+
84
+ return cls(encoder=encoder_config.to_dict(), decoder=decoder_config.to_dict(), **kwargs)
85
+
86
+
87
+ __all__ = ["NougatConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nougat/image_processing_nougat.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Image processor class for Nougat."""
15
+
16
+ import torch
17
+ from torchvision.transforms.v2 import functional as tvF
18
+
19
+ from ...image_processing_backends import TorchvisionBackend
20
+ from ...image_processing_utils import BatchFeature
21
+ from ...image_transforms import (
22
+ get_resize_output_image_size,
23
+ group_images_by_shape,
24
+ reorder_images,
25
+ )
26
+ from ...image_utils import (
27
+ IMAGENET_DEFAULT_MEAN,
28
+ IMAGENET_DEFAULT_STD,
29
+ ChannelDimension,
30
+ ImageInput,
31
+ PILImageResampling,
32
+ SizeDict,
33
+ )
34
+ from ...processing_utils import ImagesKwargs, Unpack
35
+ from ...utils import (
36
+ TensorType,
37
+ auto_docstring,
38
+ )
39
+
40
+
41
+ class NougatImageProcessorKwargs(ImagesKwargs, total=False):
42
+ r"""
43
+ do_crop_margin (`bool`, *optional*, defaults to `self.do_crop_margin`):
44
+ Whether to crop the image margins.
45
+ do_thumbnail (`bool`, *optional*, defaults to `self.do_thumbnail`):
46
+ Whether to resize the image using thumbnail method.
47
+ do_align_long_axis (`bool`, *optional*, defaults to `self.do_align_long_axis`):
48
+ Whether to align the long axis of the image with the long axis of `size` by rotating by 90 degrees.
49
+ """
50
+
51
+ do_crop_margin: bool
52
+ do_thumbnail: bool
53
+ do_align_long_axis: bool
54
+
55
+
56
+ @auto_docstring
57
+ class NougatImageProcessor(TorchvisionBackend):
58
+ valid_kwargs = NougatImageProcessorKwargs
59
+ resample = PILImageResampling.BILINEAR
60
+ image_mean = IMAGENET_DEFAULT_MEAN
61
+ image_std = IMAGENET_DEFAULT_STD
62
+ size = {"height": 896, "width": 672}
63
+ do_resize = True
64
+ do_normalize = True
65
+ do_thumbnail = True
66
+ do_align_long_axis = False
67
+ do_pad = True
68
+ do_rescale = True
69
+ do_crop_margin = True
70
+
71
+ def __init__(self, **kwargs: Unpack[NougatImageProcessorKwargs]):
72
+ super().__init__(**kwargs)
73
+
74
+ @auto_docstring
75
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[NougatImageProcessorKwargs]) -> BatchFeature:
76
+ return super().preprocess(images, **kwargs)
77
+
78
+ def python_find_non_zero(
79
+ self,
80
+ image: "torch.Tensor",
81
+ ):
82
+ """This is a reimplementation of a findNonZero function equivalent to cv2."""
83
+
84
+ non_zero_indices = torch.nonzero(image, as_tuple=False)
85
+ idxvec = non_zero_indices[:, [2, 1]]
86
+ idxvec = idxvec.reshape(-1, 1, 2)
87
+ return idxvec
88
+
89
+ def python_bounding_rect(self, coordinates):
90
+ """This is a reimplementation of a BoundingRect function equivalent to cv2."""
91
+
92
+ min_values = torch.amin(coordinates, axis=(0, 1)).to(torch.int)
93
+ max_values = torch.amax(coordinates, axis=(0, 1)).to(torch.int)
94
+
95
+ x_min, y_min = min_values[0], min_values[1]
96
+ width = max_values[0] - x_min + 1
97
+ height = max_values[1] - y_min + 1
98
+ return x_min, y_min, width, height
99
+
100
+ def crop_margin(
101
+ self,
102
+ image: "torch.Tensor",
103
+ gray_threshold: int = 200,
104
+ ) -> "torch.Tensor":
105
+ """
106
+ Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the
107
+ threshold).
108
+
109
+ Args:
110
+ image (`torch.Tensor`):
111
+ The image to be cropped.
112
+ gray_threshold (`int`, *optional*, defaults to `200`)
113
+ Value below which pixels are considered to be gray.
114
+ """
115
+ data = tvF.rgb_to_grayscale(image, num_output_channels=1)
116
+
117
+ max_val = torch.max(data)
118
+ min_val = torch.min(data)
119
+
120
+ if max_val == min_val:
121
+ return image
122
+ data = (data - min_val) / (max_val - min_val) * 255
123
+ gray = data < gray_threshold
124
+ coords = self.python_find_non_zero(gray)
125
+ x_min, y_min, width, height = self.python_bounding_rect(coords)
126
+ image = image[:, y_min : y_min + height, x_min : x_min + width]
127
+
128
+ return image
129
+
130
+ def align_long_axis(
131
+ self,
132
+ image: "torch.Tensor",
133
+ size: SizeDict,
134
+ ) -> "torch.Tensor":
135
+ """
136
+ Align the long axis of the image to the longest axis of the specified size.
137
+
138
+ Args:
139
+ image (`torch.Tensor`):
140
+ The image to be aligned.
141
+ size (`SizeDict`):
142
+ The size to align the long axis to.
143
+ Returns:
144
+ `torch.Tensor`: The aligned image.
145
+ """
146
+ input_height, input_width = image.shape[-2:]
147
+ output_height, output_width = size.height, size.width
148
+
149
+ if (output_width < output_height and input_width > input_height) or (
150
+ output_width > output_height and input_width < input_height
151
+ ):
152
+ image = torch.rot90(image, 3, dims=[1, 2])
153
+
154
+ return image
155
+
156
+ def thumbnail(
157
+ self,
158
+ image: "torch.Tensor",
159
+ size: SizeDict,
160
+ ) -> "torch.Tensor":
161
+ """
162
+ Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
163
+ corresponding dimension of the specified size.
164
+
165
+ Args:
166
+ image (`torch.tensor`):
167
+ The image to be resized.
168
+ size (`SizeDict`):
169
+ The size to resize the image to.
170
+ """
171
+
172
+ input_height, input_width = image.shape[-2:]
173
+ output_height, output_width = size.height, size.width
174
+
175
+ # We always resize to the smallest of either the input or output size.
176
+ height = min(input_height, output_height)
177
+ width = min(input_width, output_width)
178
+
179
+ if height == input_height and width == input_width:
180
+ return image
181
+
182
+ if input_height > input_width:
183
+ width = int(input_width * height / input_height)
184
+ elif input_width > input_height:
185
+ height = int(input_height * width / input_width)
186
+
187
+ new_size = (height, width)
188
+
189
+ return tvF.resize(image, new_size, interpolation=tvF.InterpolationMode.BICUBIC)
190
+
191
+ def pad_images(
192
+ self,
193
+ image: "torch.Tensor",
194
+ size: SizeDict,
195
+ ) -> "torch.Tensor":
196
+ """
197
+ Pads a batch of images to the specified size at the top, bottom, left and right.
198
+
199
+ Args:
200
+ image (`torch.tensor`):
201
+ The image to be padded.
202
+ size (`SizeDict`):
203
+ The size to pad the image to.
204
+ """
205
+ input_height, input_width = image.shape[-2:]
206
+ output_height, output_width = size.height, size.width
207
+
208
+ delta_width = output_width - input_width
209
+ delta_height = output_height - input_height
210
+
211
+ pad_top = delta_height // 2
212
+ pad_left = delta_width // 2
213
+
214
+ pad_bottom = delta_height - pad_top
215
+ pad_right = delta_width - pad_left
216
+
217
+ padding = (pad_left, pad_top, pad_right, pad_bottom)
218
+ return tvF.pad(image, padding)
219
+
220
+ def resize(
221
+ self,
222
+ image: "torch.Tensor",
223
+ size: SizeDict,
224
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None" = None,
225
+ antialias: bool = True,
226
+ **kwargs,
227
+ ) -> "torch.Tensor":
228
+ """
229
+ Resize an image to `(size.height, size.width)`.
230
+
231
+ Args:
232
+ image (`torch.Tensor`):
233
+ Image to resize.
234
+ size (`SizeDict`):
235
+ Size of the output image.
236
+ resample (`PILImageResampling | tvF.InterpolationMode | int`, *optional*):
237
+ Resampling filter to use when resizing the image.
238
+ Returns:
239
+ `torch.Tensor`: The resized image.
240
+ """
241
+ shortest_edge = min(size.height, size.width)
242
+
243
+ new_size = get_resize_output_image_size(
244
+ image, size=shortest_edge, default_to_square=False, input_data_format=ChannelDimension.FIRST
245
+ )
246
+ return super().resize(
247
+ image, SizeDict(height=new_size[0], width=new_size[1]), resample=resample, antialias=antialias, **kwargs
248
+ )
249
+
250
+ def _preprocess(
251
+ self,
252
+ images: list["torch.Tensor"],
253
+ do_resize: bool,
254
+ size: SizeDict,
255
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
256
+ do_rescale: bool,
257
+ rescale_factor: float,
258
+ do_normalize: bool,
259
+ image_mean: float | list[float] | None,
260
+ image_std: float | list[float] | None,
261
+ do_pad: bool | None,
262
+ disable_grouping: bool | None,
263
+ return_tensors: str | TensorType | None,
264
+ do_align_long_axis: bool = False,
265
+ do_thumbnail: bool = True,
266
+ do_crop_margin: bool = True,
267
+ **kwargs,
268
+ ) -> BatchFeature:
269
+ # Crop images
270
+ if do_crop_margin:
271
+ images = [self.crop_margin(image) for image in images]
272
+
273
+ # Group images by size for batched resizing
274
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
275
+ resized_images_grouped = {}
276
+ for shape, stacked_images in grouped_images.items():
277
+ if do_align_long_axis:
278
+ stacked_images = self.align_long_axis(image=stacked_images, size=size)
279
+ if do_resize:
280
+ stacked_images = self.resize(image=stacked_images, size=size, resample=resample)
281
+ if do_thumbnail:
282
+ stacked_images = self.thumbnail(image=stacked_images, size=size)
283
+ if do_pad:
284
+ stacked_images = self.pad_images(image=stacked_images, size=size)
285
+ resized_images_grouped[shape] = stacked_images
286
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
287
+
288
+ # Group images by size for further processing
289
+ # Needed in case do_resize is False, or resize returns images with different sizes
290
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
291
+ processed_images_grouped = {}
292
+ for shape, stacked_images in grouped_images.items():
293
+ # Fused rescale and normalize
294
+ stacked_images = self.rescale_and_normalize(
295
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
296
+ )
297
+ processed_images_grouped[shape] = stacked_images
298
+
299
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
300
+
301
+ return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
302
+
303
+
304
+ __all__ = ["NougatImageProcessor"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nougat/image_processing_pil_nougat.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Image processor class for Nougat."""
15
+
16
+ import numpy as np
17
+
18
+ from ...image_processing_backends import PilBackend
19
+ from ...image_processing_utils import BatchFeature
20
+ from ...image_transforms import (
21
+ get_resize_output_image_size,
22
+ pad,
23
+ to_channel_dimension_format,
24
+ to_pil_image,
25
+ )
26
+ from ...image_utils import (
27
+ IMAGENET_DEFAULT_MEAN,
28
+ IMAGENET_DEFAULT_STD,
29
+ ChannelDimension,
30
+ ImageInput,
31
+ PILImageResampling,
32
+ SizeDict,
33
+ get_image_size,
34
+ )
35
+ from ...processing_utils import ImagesKwargs, Unpack
36
+ from ...utils import (
37
+ TensorType,
38
+ auto_docstring,
39
+ )
40
+
41
+
42
+ # Adapted from transformers.models.nougat.image_processing_nougat.NougatImageProcessorKwargs
43
+ class NougatImageProcessorKwargs(ImagesKwargs, total=False):
44
+ r"""
45
+ do_crop_margin (`bool`, *optional*, defaults to `self.do_crop_margin`):
46
+ Whether to crop the image margins.
47
+ do_thumbnail (`bool`, *optional*, defaults to `self.do_thumbnail`):
48
+ Whether to resize the image using thumbnail method.
49
+ do_align_long_axis (`bool`, *optional*, defaults to `self.do_align_long_axis`):
50
+ Whether to align the long axis of the image with the long axis of `size` by rotating by 90 degrees.
51
+ """
52
+
53
+ do_crop_margin: bool
54
+ do_thumbnail: bool
55
+ do_align_long_axis: bool
56
+
57
+
58
+ @auto_docstring
59
+ class NougatImageProcessorPil(PilBackend):
60
+ valid_kwargs = NougatImageProcessorKwargs
61
+ resample = PILImageResampling.BILINEAR
62
+ image_mean = IMAGENET_DEFAULT_MEAN
63
+ image_std = IMAGENET_DEFAULT_STD
64
+ size = {"height": 896, "width": 672}
65
+ do_resize = True
66
+ do_normalize = True
67
+ do_thumbnail = True
68
+ do_align_long_axis = False
69
+ do_pad = True
70
+ do_rescale = True
71
+ do_crop_margin = True
72
+
73
+ def __init__(self, **kwargs: Unpack[NougatImageProcessorKwargs]):
74
+ super().__init__(**kwargs)
75
+
76
+ @auto_docstring
77
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[NougatImageProcessorKwargs]) -> BatchFeature:
78
+ return super().preprocess(images, **kwargs)
79
+
80
+ def python_find_non_zero(self, image: np.ndarray):
81
+ """This is a reimplementation of a findNonZero function equivalent to cv2."""
82
+ non_zero_indices = np.column_stack(np.nonzero(image))
83
+ idxvec = non_zero_indices[:, [1, 0]]
84
+ idxvec = idxvec.reshape(-1, 1, 2)
85
+ return idxvec
86
+
87
+ def python_bounding_rect(self, coordinates):
88
+ """This is a reimplementation of a BoundingRect function equivalent to cv2."""
89
+ min_values = np.min(coordinates, axis=(0, 1)).astype(int)
90
+ max_values = np.max(coordinates, axis=(0, 1)).astype(int)
91
+ x_min, y_min = min_values[0], min_values[1]
92
+ width = max_values[0] - x_min + 1
93
+ height = max_values[1] - y_min + 1
94
+ return x_min, y_min, width, height
95
+
96
+ def crop_margin(
97
+ self,
98
+ image: np.ndarray,
99
+ gray_threshold: int = 200,
100
+ ) -> np.ndarray:
101
+ """
102
+ Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the
103
+ threshold).
104
+
105
+ Args:
106
+ image (`np.ndarray`):
107
+ The image to be cropped.
108
+ gray_threshold (`int`, *optional*, defaults to `200`)
109
+ Value below which pixels are considered to be gray.
110
+ """
111
+ image_pil = to_pil_image(image, input_data_format=ChannelDimension.FIRST)
112
+ data = np.array(image_pil.convert("L")).astype(np.uint8)
113
+ max_val = data.max()
114
+ min_val = data.min()
115
+ if max_val == min_val:
116
+ return image
117
+ data = (data - min_val) / (max_val - min_val) * 255
118
+ gray = data < gray_threshold
119
+ coords = self.python_find_non_zero(gray)
120
+ x_min, y_min, width, height = self.python_bounding_rect(coords)
121
+ image_pil = image_pil.crop((x_min, y_min, x_min + width, y_min + height))
122
+ image = np.array(image_pil).astype(np.uint8)
123
+ image = to_channel_dimension_format(image, ChannelDimension.FIRST, input_channel_dim=ChannelDimension.LAST)
124
+ return image
125
+
126
+ def align_long_axis(
127
+ self,
128
+ image: np.ndarray,
129
+ size: SizeDict,
130
+ ) -> np.ndarray:
131
+ """
132
+ Align the long axis of the image to the longest axis of the specified size.
133
+
134
+ Args:
135
+ image (`np.ndarray`):
136
+ The image to be aligned.
137
+ size (`SizeDict`):
138
+ The size to align the long axis to.
139
+ Returns:
140
+ `np.ndarray`: The aligned image.
141
+ """
142
+ input_height, input_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
143
+ output_height, output_width = size.height, size.width
144
+
145
+ if (output_width < output_height and input_width > input_height) or (
146
+ output_width > output_height and input_width < input_height
147
+ ):
148
+ image = np.rot90(image, 3, axes=(1, 2))
149
+
150
+ return image
151
+
152
+ def thumbnail(
153
+ self,
154
+ image: np.ndarray,
155
+ size: SizeDict,
156
+ ) -> np.ndarray:
157
+ """
158
+ Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
159
+ corresponding dimension of the specified size.
160
+
161
+ Args:
162
+ image (`np.ndarray`):
163
+ The image to be resized.
164
+ size (`SizeDict`):
165
+ The size to resize the image to.
166
+ """
167
+
168
+ input_height, input_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
169
+ output_height, output_width = size.height, size.width
170
+
171
+ # We always resize to the smallest of either the input or output size.
172
+ height = min(input_height, output_height)
173
+ width = min(input_width, output_width)
174
+
175
+ if height == input_height and width == input_width:
176
+ return image
177
+
178
+ if input_height > input_width:
179
+ width = int(input_width * height / input_height)
180
+ elif input_width > input_height:
181
+ height = int(input_height * width / input_width)
182
+
183
+ # Use np_resize for exact dimensions; self.resize uses shortest-edge logic and would produce
184
+ # different output due to rounding in get_resize_output_image_size.
185
+ return super().resize(
186
+ image, SizeDict(height=height, width=width), resample=PILImageResampling.BICUBIC, reducing_gap=2.0
187
+ )
188
+
189
+ def pad_images(
190
+ self,
191
+ image: np.ndarray,
192
+ size: SizeDict,
193
+ ) -> np.ndarray:
194
+ """
195
+ Pads a batch of images to the specified size at the top, bottom, left and right.
196
+
197
+ Args:
198
+ image (`np.ndarray`):
199
+ The image to be padded.
200
+ size (`SizeDict`):
201
+ The size to pad the image to.
202
+ """
203
+
204
+ input_height, input_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
205
+ output_height, output_width = size.height, size.width
206
+
207
+ delta_width = output_width - input_width
208
+ delta_height = output_height - input_height
209
+
210
+ pad_top = delta_height // 2
211
+ pad_left = delta_width // 2
212
+
213
+ pad_bottom = delta_height - pad_top
214
+ pad_right = delta_width - pad_left
215
+
216
+ padding = ((pad_top, pad_bottom), (pad_left, pad_right))
217
+ return pad(image, padding, input_data_format=ChannelDimension.FIRST, data_format=ChannelDimension.FIRST)
218
+
219
+ def resize(
220
+ self,
221
+ image: np.ndarray,
222
+ size: SizeDict,
223
+ resample: "PILImageResampling | None" = None,
224
+ reducing_gap: int | None = None,
225
+ **kwargs,
226
+ ) -> np.ndarray:
227
+ """
228
+ Resize an image to `(size.height, size.width)`.
229
+
230
+ Args:
231
+ image (`np.ndarray`):
232
+ Image to resize.
233
+ size (`SizeDict`):
234
+ Size of the output image.
235
+ resample (`PILImageResampling | int`, *optional*):
236
+ Resampling filter to use when resizing the image.
237
+ Returns:
238
+ `np.ndarray`: The resized image.
239
+ """
240
+
241
+ shortest_edge = min(size.height, size.width)
242
+
243
+ new_size = get_resize_output_image_size(
244
+ image, size=shortest_edge, default_to_square=False, input_data_format=ChannelDimension.FIRST
245
+ )
246
+ return super().resize(
247
+ image,
248
+ SizeDict(height=new_size[0], width=new_size[1]),
249
+ resample=resample,
250
+ reducing_gap=reducing_gap,
251
+ **kwargs,
252
+ )
253
+
254
+ def _preprocess(
255
+ self,
256
+ images: list[np.ndarray],
257
+ do_resize: bool,
258
+ size: SizeDict,
259
+ resample: "PILImageResampling | None",
260
+ do_rescale: bool,
261
+ rescale_factor: float,
262
+ do_normalize: bool,
263
+ image_mean: float | list[float] | None,
264
+ image_std: float | list[float] | None,
265
+ return_tensors: str | TensorType | None,
266
+ do_align_long_axis: bool = False,
267
+ do_thumbnail: bool = True,
268
+ do_crop_margin: bool = True,
269
+ do_pad: bool | None = None,
270
+ **kwargs,
271
+ ) -> BatchFeature:
272
+ processed_images = []
273
+ for image in images:
274
+ if do_crop_margin:
275
+ image = self.crop_margin(image)
276
+ if do_align_long_axis:
277
+ image = self.align_long_axis(image, size)
278
+ if do_resize:
279
+ image = self.resize(image, size, resample)
280
+ if do_thumbnail:
281
+ image = self.thumbnail(image, size)
282
+ if do_pad:
283
+ image = self.pad_images(image, size)
284
+ if do_rescale:
285
+ image = self.rescale(image, rescale_factor)
286
+ if do_normalize:
287
+ image = self.normalize(image, image_mean, image_std)
288
+ processed_images.append(image)
289
+
290
+ return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
291
+
292
+
293
+ __all__ = ["NougatImageProcessorPil"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nougat/processing_nougat.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 Nougat.
16
+ """
17
+
18
+ from typing import Optional, Union
19
+
20
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput, TruncationStrategy
21
+
22
+ from ...processing_utils import ProcessorMixin
23
+ from ...utils import PaddingStrategy, TensorType, auto_docstring
24
+
25
+
26
+ @auto_docstring
27
+ class NougatProcessor(ProcessorMixin):
28
+ def __init__(self, image_processor, tokenizer):
29
+ super().__init__(image_processor, tokenizer)
30
+
31
+ @auto_docstring
32
+ def __call__(
33
+ self,
34
+ images=None,
35
+ text=None,
36
+ do_crop_margin: bool | None = None,
37
+ do_resize: bool | None = None,
38
+ size: dict[str, int] | None = None,
39
+ resample: "PILImageResampling" = None, # noqa: F821
40
+ do_thumbnail: bool | None = None,
41
+ do_align_long_axis: bool | None = None,
42
+ do_pad: bool | None = None,
43
+ do_rescale: bool | None = None,
44
+ rescale_factor: int | float | None = None,
45
+ do_normalize: bool | None = None,
46
+ image_mean: float | list[float] | None = None,
47
+ image_std: float | list[float] | None = None,
48
+ data_format: Optional["ChannelDimension"] = "channels_first", # noqa: F821
49
+ input_data_format: Union[str, "ChannelDimension"] | None = None, # noqa: F821
50
+ text_pair: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
51
+ text_target: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
52
+ text_pair_target: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
53
+ add_special_tokens: bool = True,
54
+ padding: bool | str | PaddingStrategy = False,
55
+ truncation: bool | str | TruncationStrategy | None = None,
56
+ max_length: int | None = None,
57
+ stride: int = 0,
58
+ is_split_into_words: bool = False,
59
+ pad_to_multiple_of: int | None = None,
60
+ return_tensors: str | TensorType | None = None,
61
+ return_token_type_ids: bool | None = None,
62
+ return_attention_mask: bool | None = None,
63
+ return_overflowing_tokens: bool = False,
64
+ return_special_tokens_mask: bool = False,
65
+ return_offsets_mapping: bool = False,
66
+ return_length: bool = False,
67
+ verbose: bool = True,
68
+ ):
69
+ r"""
70
+ do_crop_margin (`bool`, *optional*):
71
+ Whether to automatically crop white margins from document images. When enabled, the processor detects
72
+ and removes white space around the edges of document pages, which is useful for processing scanned
73
+ documents or PDFs with large margins.
74
+ do_thumbnail (`bool`, *optional*):
75
+ Whether to create a thumbnail version of the image. When enabled, a smaller version of the image is
76
+ generated alongside the main processed image, which can be useful for preview or faster processing.
77
+ do_align_long_axis (`bool`, *optional*):
78
+ Whether to automatically align images so that the longer axis is horizontal. When enabled, portrait
79
+ images are rotated to landscape orientation, which is typically better for document processing tasks.
80
+ """
81
+ if images is None and text is None:
82
+ raise ValueError("You need to specify either an `images` or `text` input to process.")
83
+
84
+ if images is not None:
85
+ inputs = self.image_processor(
86
+ images,
87
+ do_crop_margin=do_crop_margin,
88
+ do_resize=do_resize,
89
+ size=size,
90
+ resample=resample,
91
+ do_thumbnail=do_thumbnail,
92
+ do_align_long_axis=do_align_long_axis,
93
+ do_pad=do_pad,
94
+ do_rescale=do_rescale,
95
+ rescale_factor=rescale_factor,
96
+ do_normalize=do_normalize,
97
+ image_mean=image_mean,
98
+ image_std=image_std,
99
+ return_tensors=return_tensors,
100
+ data_format=data_format,
101
+ input_data_format=input_data_format,
102
+ )
103
+ if text is not None:
104
+ encodings = self.tokenizer(
105
+ text,
106
+ text_pair=text_pair,
107
+ text_target=text_target,
108
+ text_pair_target=text_pair_target,
109
+ add_special_tokens=add_special_tokens,
110
+ padding=padding,
111
+ truncation=truncation,
112
+ max_length=max_length,
113
+ stride=stride,
114
+ is_split_into_words=is_split_into_words,
115
+ pad_to_multiple_of=pad_to_multiple_of,
116
+ return_tensors=return_tensors,
117
+ return_token_type_ids=return_token_type_ids,
118
+ return_attention_mask=return_attention_mask,
119
+ return_overflowing_tokens=return_overflowing_tokens,
120
+ return_special_tokens_mask=return_special_tokens_mask,
121
+ return_offsets_mapping=return_offsets_mapping,
122
+ return_length=return_length,
123
+ verbose=verbose,
124
+ )
125
+
126
+ if text is None:
127
+ return inputs
128
+ elif images is None:
129
+ return encodings
130
+ else:
131
+ inputs["labels"] = encodings["input_ids"]
132
+ return inputs
133
+
134
+ def post_process_generation(self, *args, **kwargs):
135
+ """
136
+ This method forwards all its arguments to NougatTokenizer's [`~PreTrainedTokenizer.post_process_generation`].
137
+ Please refer to the docstring of this method for more information.
138
+ """
139
+ return self.tokenizer.post_process_generation(*args, **kwargs)
140
+
141
+
142
+ __all__ = ["NougatProcessor"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nougat/tokenization_nougat.py ADDED
@@ -0,0 +1,660 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+ Tokenizer class for Nougat.
16
+ """
17
+
18
+ import re
19
+ from functools import partial
20
+ from multiprocessing import Pool
21
+
22
+ import numpy as np
23
+ from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
24
+ from tokenizers.models import BPE
25
+
26
+ from ...tokenization_utils_tokenizers import TokenizersBackend
27
+ from ...utils import is_levenshtein_available, is_nltk_available, logging, requires_backends
28
+
29
+
30
+ if is_levenshtein_available():
31
+ from Levenshtein import ratio
32
+
33
+ if is_nltk_available():
34
+ import nltk
35
+
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
40
+
41
+
42
+ def markdown_compatible(text: str) -> str:
43
+ """
44
+ Make text compatible with Markdown formatting.
45
+
46
+ This function makes various text formatting adjustments to make it compatible with Markdown.
47
+
48
+ Args:
49
+ text (`str`):
50
+ The input text to be made Markdown-compatible.
51
+
52
+ Returns:
53
+ `str`: The Markdown-compatible text.
54
+ """
55
+ # equation tag
56
+ # Replace lines that start with a pattern like (decimal) \[some text\] with \[[some text] \tag{decimal}\].
57
+ text = re.sub(r"^\(([\d.]+[a-zA-Z]?)\) \\\[(.+?)\\\]$", r"\[\2 \\tag{\1}\]", text, flags=re.MULTILINE)
58
+ # Replace lines that start with a pattern like \[some text\] (decimal) with \[[some text] \tag{decimal}\].
59
+ text = re.sub(r"^\\\[(.+?)\\\] \(([\d.]+[a-zA-Z]?)\)$", r"\[\1 \\tag{\2}\]", text, flags=re.MULTILINE)
60
+ # Replace lines that start with a pattern like \[some text\] (digits) \[another text\] with \[[some text] \tag{digits}\] [another text].
61
+ text = re.sub(
62
+ r"^\\\[(.+?)\\\] \(([\d.]+[a-zA-Z]?)\) (\\\[.+?\\\])$",
63
+ r"\[\1 \\tag{\2}\] \3",
64
+ text,
65
+ flags=re.MULTILINE,
66
+ )
67
+ # multi line
68
+ text = text.replace(r"\. ", ". ")
69
+ # bold formatting
70
+ text = text.replace(r"\bm{", r"\mathbf{").replace(r"{\\bm ", r"\mathbf{")
71
+ text = re.sub(r"\\mbox{ ?\\boldmath\$(.*?)\$}", r"\\mathbf{\1}", text)
72
+ # Reformat urls (http, ftp and https only) to markdown [url](url) clickable format
73
+ text = re.sub(
74
+ r"((?:http|ftp|https):\/\/(?:[\w_-]+(?:(?:\.[\w_-]+)+))(?:[\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-]))",
75
+ r"[\1](\1)",
76
+ text,
77
+ )
78
+ # algorithms
79
+ text = re.sub(r"```\s*(.+?)\s*```", r"```\n\1\n```", text, flags=re.DOTALL)
80
+
81
+ return text
82
+
83
+
84
+ def normalize_list_like_lines(generation):
85
+ """
86
+ Normalize lines in the given text that resemble list items. The function looks for lines that start optionally with
87
+ '-' or '*', possibly followed by Roman numerals or digits indicating nesting levels. The function reformats such
88
+ lines to make them more structured.
89
+
90
+ Args:
91
+ generation (str): The input text containing lines that need to be normalized.
92
+
93
+ Returns:
94
+ str: The input text with the list-like lines normalized.
95
+
96
+ Note:
97
+ The function uses regular expressions to identify and reformat the list-like lines. The patterns capture
98
+ optional bullet points, nesting levels indicated by numerals, and the actual list item content. The
99
+ normalization adjusts the bullet point style and nesting levels based on the captured patterns.
100
+ """
101
+
102
+ lines = generation.split("\n")
103
+ output_lines = []
104
+ for line_no, line in enumerate(lines):
105
+ match = re.search(r". ([-*]) ", line)
106
+ if not match or line[0] not in ("-", "*"):
107
+ output_lines.append(line)
108
+ continue # Doesn't fit the pattern we want, no changes
109
+ delim = match.group(1) + " "
110
+ splits = line.split(delim)[1:]
111
+ replacement = ""
112
+ delim1 = line[0] + " "
113
+
114
+ for i, item in enumerate(splits):
115
+ level = 0
116
+ potential_numeral, _, rest = item.strip().partition(" ")
117
+ if not rest:
118
+ continue
119
+ # Infer current nesting level based on detected numbering
120
+ if re.match(r"^[\dixv]+((?:\.[\dixv])?)+$", potential_numeral, flags=re.IGNORECASE | re.MULTILINE):
121
+ level = potential_numeral.count(".")
122
+
123
+ replacement += (
124
+ ("\n" if i > 0 else "") + ("\t" * level) + (delim if i > 0 or line_no == 0 else delim1) + item.strip()
125
+ )
126
+
127
+ if line_no == len(lines) - 1: # If this is the last line in the generation
128
+ replacement += "\n" # Add an empty line to the end of the generation
129
+
130
+ output_lines.append(replacement)
131
+
132
+ return "\n".join(output_lines)
133
+
134
+
135
+ def find_next_punctuation(text: str, start_idx=0):
136
+ """
137
+ Find the index of the next punctuation mark.
138
+
139
+ Args:
140
+ text (`str`):
141
+ String to examine
142
+ start_idx (`int`, *optional*)
143
+ Index where to start
144
+ """
145
+
146
+ for i in range(start_idx, len(text)):
147
+ if text[i] in [".", "?", "!", "\n"]:
148
+ return i
149
+
150
+ return None
151
+
152
+
153
+ def truncate_repetitions(text: str, min_len: int = 30) -> str:
154
+ """
155
+ Attempt to truncate repeating segments in the input string.
156
+
157
+ This function looks for the longest repeating substring at the end of the input string and truncates it to appear
158
+ only once. To be considered for removal, repetitions need to be continuous.
159
+
160
+ Args:
161
+ text (`str`):
162
+ The input raw prediction to be truncated.
163
+ min_len (int):
164
+ The minimum length of the repeating segment.
165
+
166
+ Returns:
167
+ `str`: The input string with repeated segments truncated.
168
+ """
169
+ text_lower = text.lower()
170
+ text_length = len(text_lower)
171
+
172
+ if text_length < 2 * min_len:
173
+ return text
174
+
175
+ # try to find a length at which the tail is repeating
176
+ max_repetition_length = None
177
+ for repetition_length in range(min_len, int(text_length / 2)):
178
+ # check if there is a repetition at the end
179
+ same = True
180
+ for i in range(0, repetition_length):
181
+ if text_lower[text_length - repetition_length - i - 1] != text_lower[text_length - i - 1]:
182
+ same = False
183
+ break
184
+
185
+ if same:
186
+ max_repetition_length = repetition_length
187
+
188
+ if max_repetition_length is None:
189
+ return text
190
+
191
+ lcs = text_lower[-max_repetition_length:]
192
+
193
+ # remove all but the last repetition
194
+ substituted_text = text
195
+ substituted_text_lower = text_lower
196
+ while substituted_text_lower.endswith(lcs):
197
+ substituted_text = substituted_text[:-max_repetition_length]
198
+ substituted_text_lower = substituted_text_lower[:-max_repetition_length]
199
+
200
+ # this is the tail with the repetitions
201
+ repeating_tail = text_lower[len(substituted_text_lower) :]
202
+
203
+ # add until next punctuation and make sure last sentence is not repeating
204
+ substituted_text_lower_out = substituted_text_lower
205
+ while True:
206
+ sentence_end = find_next_punctuation(text_lower, len(substituted_text_lower_out))
207
+ sentence_start = find_next_punctuation(text_lower[::-1], len(substituted_text_lower_out))
208
+ if sentence_end and sentence_start:
209
+ sentence = text_lower[sentence_start:sentence_end]
210
+ substituted_text_lower_out = text_lower[: sentence_end + 1]
211
+ if sentence in repeating_tail:
212
+ break
213
+ else:
214
+ break
215
+
216
+ text_out = text[: len(substituted_text_lower_out)]
217
+
218
+ return text_out
219
+
220
+
221
+ def remove_numbers(lines):
222
+ def _clean(s):
223
+ return re.sub(r"(?:[\d_]|\*\*)", "", s).strip()
224
+
225
+ if isinstance(lines, str):
226
+ return _clean(lines)
227
+ out = []
228
+ for l in lines:
229
+ out.append(_clean(l))
230
+ return out
231
+
232
+
233
+ def get_slices(lines, clean_lines):
234
+ """
235
+ Get slices of text based on specific criteria within the lines.
236
+
237
+ This function identifies and returns slices of text from the input lines based on certain conditions.
238
+
239
+ These conditions were chosen by the Nougat authors:
240
+ - The slice is less than 200 characters long.
241
+ - The slice is more than 3 characters long.
242
+ - The slice does not start with "[MISSING_PAGE".
243
+ - The slice is either the same as the next slice or the ratio of the two in terms of Levenshtein distance is
244
+ greater than 0.9.
245
+
246
+ Args:
247
+ lines (`list[str]`):
248
+ The list of lines containing the text.
249
+ clean_lines (`list[str]`):
250
+ A cleaned version of the text (without numbers).
251
+
252
+ Returns:
253
+ `list[tuple]`: A list of tuples representing the start and end indices of text slices.
254
+ """
255
+ indices = np.zeros(len(lines))
256
+ for i in range(len(lines) - 1):
257
+ j = i + 1
258
+ while not clean_lines[j] and j < len(lines) - 1:
259
+ j += 1
260
+ if (
261
+ len(clean_lines[i]) < 200
262
+ and len(clean_lines[i]) > 3
263
+ and len(clean_lines[j]) < 200
264
+ and len(clean_lines[j]) > 3
265
+ and not clean_lines[i].startswith("[MISSING_PAGE")
266
+ and (clean_lines[i] == clean_lines[j] or ratio(clean_lines[i], clean_lines[j]) > 0.9)
267
+ ):
268
+ indices[i:j] = 1
269
+ ids = np.where(indices)[0]
270
+ slices = []
271
+ if len(ids) == 0:
272
+ return slices
273
+ j0 = 0
274
+ for j, x in enumerate(np.diff(ids) > 3):
275
+ if x:
276
+ slices.append((ids[j0], ids[j] + 2))
277
+ j0 = j + 1
278
+ slices.append((ids[j0], ids[-1] + 2))
279
+ return [sli for sli in slices if sli[1] - sli[0] > 15]
280
+
281
+
282
+ def remove_slice_from_lines(lines, clean_text, slice) -> str:
283
+ """
284
+ Remove a slice of text from the lines based on specific criteria.
285
+
286
+ This function identifies a slice of text within the lines and removes it based on certain conditions.
287
+
288
+ Args:
289
+ lines (list of str): The list of lines containing the text.
290
+ clean_text (list of str): A cleaned version of the text (without numbers).
291
+ slice (tuple): A tuple representing the start and end indices of the slice to be removed.
292
+
293
+ Returns:
294
+ str: The removed slice of text as a single string.
295
+ """
296
+ base = clean_text[slice[0]]
297
+ section = list(slice)
298
+ check_start_flag = False
299
+ # backwards pass, at most 5 lines
300
+ for line_idx in range(max(0, slice[0] - 1), max(0, slice[0] - 5), -1):
301
+ if not lines[line_idx]:
302
+ continue
303
+ if lines[line_idx] == "## References":
304
+ section[0] = line_idx
305
+ break
306
+ elif ratio(base, remove_numbers(lines[line_idx])) < 0.9:
307
+ section[0] = line_idx + 1
308
+ potential_ref = remove_numbers(lines[max(0, line_idx - 1)].partition("* [")[-1])
309
+ if len(potential_ref) >= 0.75 * len(base) and ratio(base, potential_ref) < 0.9:
310
+ section[0] = line_idx
311
+ check_start_flag = True
312
+ break
313
+ # forward pass, at most 5 lines
314
+ for line_idx in range(min(len(lines), slice[1]), min(len(lines), slice[1] + 5)):
315
+ if ratio(base, remove_numbers(lines[line_idx])) < 0.9:
316
+ section[1] = line_idx
317
+ break
318
+ if len(lines) <= section[1]:
319
+ section[1] = len(lines) - 1
320
+ to_delete = "\n".join(lines[section[0] : section[1] + 1])
321
+ # cut off next page content
322
+ itera, iterb = enumerate(lines[section[1] - 1]), enumerate(lines[section[1]])
323
+ while True:
324
+ try:
325
+ (ia, a) = next(itera)
326
+ while a.isnumeric():
327
+ (ia, a) = next(itera)
328
+ (ib, b) = next(iterb)
329
+ while b.isnumeric():
330
+ (ib, b) = next(iterb)
331
+ if a != b:
332
+ break
333
+ except StopIteration:
334
+ break
335
+ if check_start_flag and "* [" in to_delete:
336
+ to_delete = "* [" + to_delete.partition("* [")[-1]
337
+ try:
338
+ delta = len(lines[section[1]]) - ib - 1
339
+ if delta > 0:
340
+ to_delete = to_delete[:-delta]
341
+ except UnboundLocalError:
342
+ pass
343
+
344
+ return to_delete.strip()
345
+
346
+
347
+ class NougatTokenizer(TokenizersBackend):
348
+ """
349
+ Tokenizer for Nougat (backed by HuggingFace tokenizers library).
350
+
351
+ This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
352
+ refer to this superclass for more information regarding those methods. This class mainly adds Nougat-specific
353
+ methods for postprocessing the generated text.
354
+
355
+ Args:
356
+ vocab_file (`str`, *optional*):
357
+ Path to the vocabulary file.
358
+ merges_file (`str`, *optional*):
359
+ Path to the merges file.
360
+ tokenizer_file (`str`, *optional*):
361
+ [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
362
+ contains everything needed to load the tokenizer.
363
+
364
+ clean_up_tokenization_spaces (`str`, *optional*, defaults to `False`):
365
+ Whether to cleanup spaces after decoding, cleanup consists in removing potential artifacts like extra
366
+ spaces.
367
+
368
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
369
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
370
+ token instead.
371
+
372
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
373
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
374
+
375
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
376
+ The end of sequence token.
377
+
378
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
379
+ The token used for padding, for example when batching sequences of different lengths.
380
+
381
+ vocab (`str`, `dict` or `list`, *optional*):
382
+ Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file.
383
+
384
+ merges (`str` or `list`, *optional*):
385
+ Custom merges list. If not provided, merges are loaded from merges_file.
386
+ """
387
+
388
+ vocab_files_names = VOCAB_FILES_NAMES
389
+ model_input_names = ["input_ids", "attention_mask"]
390
+ model = BPE
391
+
392
+ def __init__(
393
+ self,
394
+ errors: str = "replace",
395
+ unk_token: str = "<unk>",
396
+ bos_token: str = "<s>",
397
+ eos_token: str = "</s>",
398
+ pad_token: str = "<pad>",
399
+ vocab: str | dict | list | None = None,
400
+ merges: str | list | None = None,
401
+ **kwargs,
402
+ ):
403
+ self._vocab = (
404
+ vocab
405
+ if vocab is not None
406
+ else {
407
+ str(bos_token): 0,
408
+ str(pad_token): 1,
409
+ str(eos_token): 2,
410
+ str(unk_token): 3,
411
+ "[START_REF]": 4,
412
+ }
413
+ )
414
+ self._merges = merges or []
415
+ self._tokenizer = Tokenizer(
416
+ BPE(
417
+ vocab=self._vocab,
418
+ merges=self._merges,
419
+ dropout=None,
420
+ continuing_subword_prefix="",
421
+ end_of_word_suffix="",
422
+ fuse_unk=False,
423
+ )
424
+ )
425
+
426
+ self._tokenizer.normalizer = normalizers.NFKC()
427
+ self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
428
+ [
429
+ pre_tokenizers.Split(pattern="SPL1T-TH1S-Pl3A5E", behavior="removed", invert=False),
430
+ pre_tokenizers.Digits(individual_digits=True),
431
+ pre_tokenizers.Split(
432
+ pattern=r"[\(\)\[\]\{\}]|([!\"#\$%\&'\*\+,\-\./:;<=>\?\\\^_`\|\~])\1*",
433
+ behavior="isolated",
434
+ invert=False,
435
+ ),
436
+ pre_tokenizers.Split(pattern="\n", behavior="isolated", invert=False),
437
+ pre_tokenizers.ByteLevel(add_prefix_space=False, trim_offsets=True, use_regex=True),
438
+ ]
439
+ )
440
+ self._tokenizer.decoder = decoders.ByteLevel(add_prefix_space=True, trim_offsets=True, use_regex=True)
441
+
442
+ super().__init__(
443
+ errors=errors,
444
+ unk_token=unk_token,
445
+ bos_token=bos_token,
446
+ eos_token=eos_token,
447
+ pad_token=pad_token,
448
+ **kwargs,
449
+ )
450
+ self._tokenizer.post_processor = processors.TemplateProcessing(
451
+ single=f"{bos_token}:0 $A:0 {eos_token}:0",
452
+ pair="$A:0 $B:1",
453
+ special_tokens=[
454
+ (str(eos_token), self.eos_token_id),
455
+ (str(bos_token), self.bos_token_id),
456
+ ],
457
+ )
458
+
459
+ # Enable truncation and padding
460
+ self._tokenizer.enable_truncation(max_length=4096)
461
+ self._tokenizer.enable_padding(length=4096, pad_id=self.pad_token_id, pad_token=str(pad_token))
462
+
463
+ def remove_hallucinated_references(self, text: str) -> str:
464
+ """
465
+ Remove hallucinated or missing references from the text.
466
+
467
+ This function identifies and removes references that are marked as missing or hallucinated from the input text.
468
+
469
+ Args:
470
+ text (`str`):
471
+ The input text containing references.
472
+
473
+ Returns:
474
+ `str`: The text with hallucinated references removed.
475
+ """
476
+ lines = text.split("\n")
477
+ if len(lines) == 0:
478
+ return ""
479
+ clean_lines = remove_numbers(lines)
480
+ slices = get_slices(lines, clean_lines)
481
+ to_delete = []
482
+ for slice in slices:
483
+ to_delete.append(remove_slice_from_lines(lines, clean_lines, slice))
484
+ for to_delete in reversed(to_delete):
485
+ text = text.replace(to_delete, "\n\n[MISSING_PAGE_POST]\n\n")
486
+ text = re.sub(
487
+ r"## References\n+\[MISSING_PAGE_POST(:\d+)?\]",
488
+ "\n\n[MISSING_PAGE_POST\\1]",
489
+ text,
490
+ )
491
+ return text
492
+
493
+ def correct_tables(self, generation: str) -> str:
494
+ """
495
+ Takes a generated string and fixes tables/tabulars to make them match the markdown format needed.
496
+
497
+ Args:
498
+ generation (str): The generated text to be postprocessed.
499
+
500
+ Returns:
501
+ str: The postprocessed text.
502
+
503
+ Example:
504
+
505
+ ```python
506
+ correct_tables("\\begin{table} \\begin{tabular}{l l} & \\ \\end{tabular} \\end{table}")
507
+ "\\begin{table}\n\\begin{tabular}{l l} & \\ \\end{tabular}\n\\end{table}"
508
+ ```
509
+ """
510
+ # remove obvious wrong tables
511
+ for l in generation.split("\n"):
512
+ if l.count("\\begin{tabular}") > 15 or l.count("\\multicolumn") > 60 or l.count("&") > 400:
513
+ generation = generation.replace(l, "")
514
+ # whitespace corrections
515
+
516
+ generation = generation.replace("\\begin{table} \\begin{tabular}", "\\begin{table}\n\\begin{tabular}")
517
+ generation = generation.replace("\\end{tabular} \\end{table}", "\\end{tabular}\n\\end{table}")
518
+ generation = generation.replace("\\end{table} Tab", "\\end{table}\nTab")
519
+
520
+ generation = re.sub(r"(^.+)\\begin{tab", r"\1\n\\begin{tab", generation, flags=re.MULTILINE)
521
+
522
+ # Remove left-aligned empty LaTeX tabular blocks.
523
+ generation = generation.replace(r"\begin{tabular}{l l} & \\ \end{tabular}", "")
524
+ # Remove tabulars with just 2 newline characters.
525
+ generation = generation.replace("\\begin{tabular}{}\n\n\\end{tabular}", "")
526
+ return generation
527
+
528
+ def post_process_single(self, generation: str, fix_markdown: bool = True) -> str:
529
+ """
530
+ Postprocess a single generated text. Regular expressions used here are taken directly from the Nougat article
531
+ authors. These expressions are commented for clarity and tested end-to-end in most cases.
532
+
533
+ Args:
534
+ generation (str): The generated text to be postprocessed.
535
+ fix_markdown (bool, optional): Whether to perform Markdown formatting fixes. Default is True.
536
+
537
+ Returns:
538
+ str: The postprocessed text.
539
+ """
540
+ generation = re.sub(
541
+ r"(?:\n|^)#+ \d*\W? ?(.{100,})", r"\n\1", generation
542
+ ) # too long section titles probably are none
543
+ generation = generation.strip()
544
+ # Remove LaTeX left margin tag
545
+ generation = generation.replace("\n* [leftmargin=*]\n", "\n")
546
+ # Remove lines with markdown headings starting with #, with numerals,
547
+ # and possibly roman numerals with trailing spaces and newlines
548
+ generation = re.sub(r"^#+ (?:[\d+\.]+|[ixv\.]+)?\s*(?:$|\n\s*)", "", generation, flags=re.MULTILINE)
549
+ # most likely hallucinated titles
550
+ lines = generation.split("\n")
551
+ if lines[-1].startswith("#") and lines[-1].lstrip("#").startswith(" ") and len(lines) > 1:
552
+ logger.info("Likely hallucinated title at the end of the page: " + lines[-1])
553
+ generation = "\n".join(lines[:-1])
554
+ # obvious repetition detection
555
+ generation = truncate_repetitions(generation)
556
+ # Reference corrections
557
+ generation = self.remove_hallucinated_references(generation)
558
+ # Remove lines starting with asterisks and numbers like "*[1]" and followed by capital letters and periods (ie too long references)
559
+ generation = re.sub(r"^\* \[\d+\](\s?[A-W]\.+\s?){10,}.*$", "", generation, flags=re.MULTILINE)
560
+ # Remove empty brackets after a reference number in brackets. *[12][]ABC will become *[12]ABC
561
+ generation = re.sub(r"^(\* \[\d+\])\[\](.*)$", r"\1\2", generation, flags=re.MULTILINE)
562
+ # Remove single characters before or after 2 new lines
563
+ generation = re.sub(r"(^\w\n\n|\n\n\w$)", "", generation)
564
+ # pmc math artifact correction
565
+ generation = re.sub(
566
+ r"([\s.,()])_([a-zA-Z0-9])__([a-zA-Z0-9]){1,3}_([\s.,:()])",
567
+ r"\1\(\2_{\3}\)\4",
568
+ generation,
569
+ )
570
+ generation = re.sub(r"([\s.,\d])_([a-zA-Z0-9])_([\s.,\d;])", r"\1\(\2\)\3", generation)
571
+ # footnote mistakes
572
+ generation = re.sub(
573
+ r"(\nFootnote .*?:) (?:footnotetext|thanks):\W*(.*(?:\n\n|$))",
574
+ r"\1 \2",
575
+ generation,
576
+ )
577
+ # TODO Come up with footnote formatting inside a table
578
+ generation = re.sub(r"\[FOOTNOTE:.+?\](.*?)\[ENDFOOTNOTE\]", "", generation)
579
+ # itemize post processing
580
+ generation = normalize_list_like_lines(generation)
581
+
582
+ if generation.endswith((".", "}")):
583
+ generation += "\n\n"
584
+ if re.match(r"[A-Z0-9,;:]$", generation):
585
+ # add space in case it there is a comma or word ending
586
+ generation += " "
587
+ elif generation.startswith(("#", "**", "\\begin")):
588
+ generation = "\n\n" + generation
589
+ elif generation.split("\n")[-1].startswith(("#", "Figure", "Table")):
590
+ generation = generation + "\n\n"
591
+ else:
592
+ try:
593
+ last_word = generation.split(" ")[-1]
594
+ if last_word in nltk.corpus.words.words():
595
+ generation += " "
596
+ except LookupError:
597
+ # add space just in case. Will split words but better than concatenating them
598
+ generation += " "
599
+
600
+ # table corrections
601
+ generation = self.correct_tables(generation)
602
+ # Remove optional, empty square brackets after begin{array}
603
+ generation = generation.replace("\\begin{array}[]{", "\\begin{array}{")
604
+ # Remove empty or malformed LaTeX tabular blocks with 2 or more columns specified, with spaces and ampersands.
605
+ generation = re.sub(
606
+ r"\\begin{tabular}{([clr ]){2,}}\s*[& ]*\s*(\\\\)? \\end{tabular}",
607
+ "",
608
+ generation,
609
+ )
610
+ # Remove lines containing "S.A.B." one or more times. Was included in Nougat's code.
611
+ generation = re.sub(r"(\*\*S\. A\. B\.\*\*\n+){2,}", "", generation)
612
+ # Remove markdown-style headers that are incomplete or empty on multiple lines.
613
+ generation = re.sub(r"^#+( [\[\d\w])?$", "", generation, flags=re.MULTILINE)
614
+ # Remove lines with just one period.
615
+ generation = re.sub(r"^\.\s*$", "", generation, flags=re.MULTILINE)
616
+ # Replace instances of three or more newlines with just two newlines.
617
+ generation = re.sub(r"\n{3,}", "\n\n", generation)
618
+ if fix_markdown:
619
+ return markdown_compatible(generation)
620
+ else:
621
+ return generation
622
+
623
+ def post_process_generation(
624
+ self,
625
+ generation: str | list[str],
626
+ fix_markdown: bool = True,
627
+ num_workers: int | None = None,
628
+ ) -> str | list[str]:
629
+ """
630
+ Postprocess a generated text or a list of generated texts.
631
+
632
+ This function can be used to perform postprocessing on generated text, such as fixing Markdown formatting.
633
+
634
+ Postprocessing is quite slow so it is recommended to use multiprocessing to speed up the process.
635
+
636
+ Args:
637
+ generation (Union[str, list[str]]):
638
+ The generated text or a list of generated texts.
639
+ fix_markdown (`bool`, *optional*, defaults to `True`):
640
+ Whether to perform Markdown formatting fixes.
641
+ num_workers (`int`, *optional*):
642
+ Optional number of workers to pass to leverage multiprocessing (postprocessing several texts in
643
+ parallel).
644
+
645
+ Returns:
646
+ Union[str, list[str]]: The postprocessed text or list of postprocessed texts.
647
+ """
648
+ requires_backends(self, ["nltk", "levenshtein"])
649
+
650
+ if isinstance(generation, list):
651
+ if num_workers is not None and isinstance(num_workers, int):
652
+ with Pool(num_workers) as p:
653
+ return p.map(partial(self.post_process_single, fix_markdown=fix_markdown), generation)
654
+ else:
655
+ return [self.post_process_single(s, fix_markdown=fix_markdown) for s in generation]
656
+ else:
657
+ return self.post_process_single(generation, fix_markdown=fix_markdown)
658
+
659
+
660
+ __all__ = ["NougatTokenizer"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nystromformer/__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_nystromformer import *
22
+ from .modeling_nystromformer 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__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nystromformer/configuration_nystromformer.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 UW-Madison 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
+ """Nystromformer model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...configuration_utils import PreTrainedConfig
19
+ from ...utils import auto_docstring
20
+
21
+
22
+ @auto_docstring(checkpoint="uw-madison/nystromformer-512")
23
+ @strict
24
+ class NystromformerConfig(PreTrainedConfig):
25
+ r"""
26
+ segment_means_seq_len (`int`, *optional*, defaults to 64):
27
+ Sequence length used in segment-means.
28
+ num_landmarks (`int`, *optional*, defaults to 64):
29
+ The number of landmark (or Nystrom) points to use in Nystrom approximation of the softmax self-attention
30
+ matrix.
31
+ conv_kernel_size (`int`, *optional*, defaults to 65):
32
+ The kernel size of depthwise convolution used in Nystrom approximation.
33
+ inv_coeff_init_option (`bool`, *optional*, defaults to `False`):
34
+ Whether or not to use exact coefficient computation for the initial values for the iterative method of
35
+ calculating the Moore-Penrose inverse of a matrix.
36
+
37
+ Example:
38
+
39
+ ```python
40
+ >>> from transformers import NystromformerModel, NystromformerConfig
41
+
42
+ >>> # Initializing a Nystromformer uw-madison/nystromformer-512 style configuration
43
+ >>> configuration = NystromformerConfig()
44
+
45
+ >>> # Initializing a model from the uw-madison/nystromformer-512 style configuration
46
+ >>> model = NystromformerModel(configuration)
47
+
48
+ >>> # Accessing the model configuration
49
+ >>> configuration = model.config
50
+ ```"""
51
+
52
+ model_type = "nystromformer"
53
+
54
+ vocab_size: int = 30000
55
+ hidden_size: int = 768
56
+ num_hidden_layers: int = 12
57
+ num_attention_heads: int = 12
58
+ intermediate_size: int = 3072
59
+ hidden_act: str = "gelu_new"
60
+ hidden_dropout_prob: float | int = 0.1
61
+ attention_probs_dropout_prob: float | int = 0.1
62
+ max_position_embeddings: int = 510
63
+ type_vocab_size: int = 2
64
+ segment_means_seq_len: int = 64
65
+ num_landmarks: int = 64
66
+ conv_kernel_size: int = 65
67
+ inv_coeff_init_option: bool = False
68
+ initializer_range: float = 0.02
69
+ layer_norm_eps: float = 1e-5
70
+ pad_token_id: int | None = 1
71
+ bos_token_id: int | None = 0
72
+ eos_token_id: int | list[int] | None = 2
73
+ add_cross_attention: bool = False
74
+ tie_word_embeddings: bool = True
75
+
76
+
77
+ __all__ = ["NystromformerConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/nystromformer/modeling_nystromformer.py ADDED
@@ -0,0 +1,944 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 UW-Madison 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 Nystromformer model."""
15
+
16
+ import math
17
+
18
+ import torch
19
+ from torch import nn
20
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
21
+
22
+ from ... import initialization as init
23
+ from ...activations import ACT2FN
24
+ from ...modeling_layers import GradientCheckpointingLayer
25
+ from ...modeling_outputs import (
26
+ BaseModelOutputWithPastAndCrossAttentions,
27
+ MaskedLMOutput,
28
+ MultipleChoiceModelOutput,
29
+ QuestionAnsweringModelOutput,
30
+ SequenceClassifierOutput,
31
+ TokenClassifierOutput,
32
+ )
33
+ from ...modeling_utils import PreTrainedModel
34
+ from ...pytorch_utils import apply_chunking_to_forward
35
+ from ...utils import (
36
+ auto_docstring,
37
+ logging,
38
+ )
39
+ from .configuration_nystromformer import NystromformerConfig
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ class NystromformerEmbeddings(nn.Module):
46
+ """Construct the embeddings from word, position and token_type embeddings."""
47
+
48
+ def __init__(self, config):
49
+ super().__init__()
50
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
51
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings + 2, config.hidden_size)
52
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
53
+
54
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
55
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
56
+
57
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
58
+ self.register_buffer(
59
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)) + 2, persistent=False
60
+ )
61
+ self.register_buffer(
62
+ "token_type_ids",
63
+ torch.zeros(self.position_ids.size(), dtype=torch.long, device=self.position_ids.device),
64
+ persistent=False,
65
+ )
66
+
67
+ def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
68
+ if input_ids is not None:
69
+ input_shape = input_ids.size()
70
+ else:
71
+ input_shape = inputs_embeds.size()[:-1]
72
+
73
+ seq_length = input_shape[1]
74
+
75
+ if position_ids is None:
76
+ position_ids = self.position_ids[:, :seq_length]
77
+
78
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
79
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
80
+ # issue #5664
81
+ if token_type_ids is None:
82
+ if hasattr(self, "token_type_ids"):
83
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
84
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
85
+ token_type_ids = buffered_token_type_ids_expanded
86
+ else:
87
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
88
+
89
+ if inputs_embeds is None:
90
+ inputs_embeds = self.word_embeddings(input_ids)
91
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
92
+ embeddings = inputs_embeds + token_type_embeddings
93
+
94
+ position_embeddings = self.position_embeddings(position_ids)
95
+ embeddings += position_embeddings
96
+
97
+ embeddings = self.LayerNorm(embeddings)
98
+ embeddings = self.dropout(embeddings)
99
+ return embeddings
100
+
101
+
102
+ class NystromformerSelfAttention(nn.Module):
103
+ def __init__(self, config):
104
+ super().__init__()
105
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
106
+ raise ValueError(
107
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
108
+ f"heads ({config.num_attention_heads})"
109
+ )
110
+
111
+ self.num_attention_heads = config.num_attention_heads
112
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
113
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
114
+
115
+ self.num_landmarks = config.num_landmarks
116
+ self.seq_len = config.segment_means_seq_len
117
+ self.conv_kernel_size = config.conv_kernel_size
118
+
119
+ if config.inv_coeff_init_option:
120
+ self.init_option = config["inv_init_coeff_option"]
121
+ else:
122
+ self.init_option = "original"
123
+
124
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
125
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
126
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
127
+
128
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
129
+
130
+ if self.conv_kernel_size is not None:
131
+ self.conv = nn.Conv2d(
132
+ in_channels=self.num_attention_heads,
133
+ out_channels=self.num_attention_heads,
134
+ kernel_size=(self.conv_kernel_size, 1),
135
+ padding=(self.conv_kernel_size // 2, 0),
136
+ bias=False,
137
+ groups=self.num_attention_heads,
138
+ )
139
+
140
+ # Function to approximate Moore-Penrose inverse via the iterative method
141
+ def iterative_inv(self, mat, n_iter=6):
142
+ identity = torch.eye(mat.size(-1), device=mat.device)
143
+ key = mat
144
+
145
+ # The entries of key are positive and ||key||_{\infty} = 1 due to softmax
146
+ if self.init_option == "original":
147
+ # This original implementation is more conservative to compute coefficient of Z_0.
148
+ value = 1 / torch.max(torch.sum(key, dim=-2)) * key.transpose(-1, -2)
149
+ else:
150
+ # This is the exact coefficient computation, 1 / ||key||_1, of initialization of Z_0, leading to faster convergence.
151
+ value = 1 / torch.max(torch.sum(key, dim=-2), dim=-1).values[:, :, None, None] * key.transpose(-1, -2)
152
+
153
+ for _ in range(n_iter):
154
+ key_value = torch.matmul(key, value)
155
+ value = torch.matmul(
156
+ 0.25 * value,
157
+ 13 * identity
158
+ - torch.matmul(key_value, 15 * identity - torch.matmul(key_value, 7 * identity - key_value)),
159
+ )
160
+ return value
161
+
162
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
163
+ input_shape = hidden_states.shape[:-1]
164
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
165
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
166
+ key_layer = self.key(hidden_states).view(hidden_shape).transpose(1, 2)
167
+ value_layer = self.value(hidden_states).view(hidden_shape).transpose(1, 2)
168
+
169
+ query_layer = query_layer / math.sqrt(math.sqrt(self.attention_head_size))
170
+ key_layer = key_layer / math.sqrt(math.sqrt(self.attention_head_size))
171
+
172
+ if self.num_landmarks == self.seq_len:
173
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
174
+
175
+ if attention_mask is not None:
176
+ # Apply the attention mask is (precomputed for all layers in NystromformerModel forward() function)
177
+ attention_scores = attention_scores + attention_mask
178
+
179
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
180
+ context_layer = torch.matmul(attention_probs, value_layer)
181
+
182
+ else:
183
+ q_landmarks = query_layer.reshape(
184
+ -1,
185
+ self.num_attention_heads,
186
+ self.num_landmarks,
187
+ self.seq_len // self.num_landmarks,
188
+ self.attention_head_size,
189
+ ).mean(dim=-2)
190
+ k_landmarks = key_layer.reshape(
191
+ -1,
192
+ self.num_attention_heads,
193
+ self.num_landmarks,
194
+ self.seq_len // self.num_landmarks,
195
+ self.attention_head_size,
196
+ ).mean(dim=-2)
197
+
198
+ kernel_1 = torch.nn.functional.softmax(torch.matmul(query_layer, k_landmarks.transpose(-1, -2)), dim=-1)
199
+ kernel_2 = torch.nn.functional.softmax(torch.matmul(q_landmarks, k_landmarks.transpose(-1, -2)), dim=-1)
200
+
201
+ attention_scores = torch.matmul(q_landmarks, key_layer.transpose(-1, -2))
202
+
203
+ if attention_mask is not None:
204
+ # Apply the attention mask is (precomputed for all layers in NystromformerModel forward() function)
205
+ attention_scores = attention_scores + attention_mask
206
+
207
+ kernel_3 = nn.functional.softmax(attention_scores, dim=-1)
208
+ attention_probs = torch.matmul(kernel_1, self.iterative_inv(kernel_2))
209
+ new_value_layer = torch.matmul(kernel_3, value_layer)
210
+ context_layer = torch.matmul(attention_probs, new_value_layer)
211
+
212
+ if self.conv_kernel_size is not None:
213
+ context_layer += self.conv(value_layer)
214
+
215
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
216
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
217
+ context_layer = context_layer.view(*new_context_layer_shape)
218
+
219
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
220
+
221
+ return outputs
222
+
223
+
224
+ # Copied from transformers.models.bert.modeling_bert.BertSelfOutput
225
+ class NystromformerSelfOutput(nn.Module):
226
+ def __init__(self, config):
227
+ super().__init__()
228
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
229
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
230
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
231
+
232
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
233
+ hidden_states = self.dense(hidden_states)
234
+ hidden_states = self.dropout(hidden_states)
235
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
236
+ return hidden_states
237
+
238
+
239
+ class NystromformerAttention(nn.Module):
240
+ def __init__(self, config):
241
+ super().__init__()
242
+ self.self = NystromformerSelfAttention(config)
243
+ self.output = NystromformerSelfOutput(config)
244
+
245
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
246
+ self_outputs = self.self(hidden_states, attention_mask, output_attentions)
247
+ attention_output = self.output(self_outputs[0], hidden_states)
248
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
249
+ return outputs
250
+
251
+
252
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Nystromformer
253
+ class NystromformerIntermediate(nn.Module):
254
+ def __init__(self, config):
255
+ super().__init__()
256
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
257
+ if isinstance(config.hidden_act, str):
258
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
259
+ else:
260
+ self.intermediate_act_fn = config.hidden_act
261
+
262
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
263
+ hidden_states = self.dense(hidden_states)
264
+ hidden_states = self.intermediate_act_fn(hidden_states)
265
+ return hidden_states
266
+
267
+
268
+ # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Nystromformer
269
+ class NystromformerOutput(nn.Module):
270
+ def __init__(self, config):
271
+ super().__init__()
272
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
273
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
274
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
275
+
276
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
277
+ hidden_states = self.dense(hidden_states)
278
+ hidden_states = self.dropout(hidden_states)
279
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
280
+ return hidden_states
281
+
282
+
283
+ class NystromformerLayer(GradientCheckpointingLayer):
284
+ def __init__(self, config):
285
+ super().__init__()
286
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
287
+ self.seq_len_dim = 1
288
+ self.attention = NystromformerAttention(config)
289
+ self.add_cross_attention = config.add_cross_attention
290
+ self.intermediate = NystromformerIntermediate(config)
291
+ self.output = NystromformerOutput(config)
292
+
293
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
294
+ self_attention_outputs = self.attention(hidden_states, attention_mask, output_attentions=output_attentions)
295
+ attention_output = self_attention_outputs[0]
296
+
297
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
298
+
299
+ layer_output = apply_chunking_to_forward(
300
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
301
+ )
302
+ outputs = (layer_output,) + outputs
303
+
304
+ return outputs
305
+
306
+ def feed_forward_chunk(self, attention_output):
307
+ intermediate_output = self.intermediate(attention_output)
308
+ layer_output = self.output(intermediate_output, attention_output)
309
+ return layer_output
310
+
311
+
312
+ class NystromformerEncoder(nn.Module):
313
+ def __init__(self, config):
314
+ super().__init__()
315
+ self.config = config
316
+ self.layer = nn.ModuleList([NystromformerLayer(config) for _ in range(config.num_hidden_layers)])
317
+ self.gradient_checkpointing = False
318
+
319
+ def forward(
320
+ self,
321
+ hidden_states: torch.Tensor,
322
+ attention_mask: torch.Tensor | None = None,
323
+ output_attentions: bool = False,
324
+ output_hidden_states: bool = False,
325
+ return_dict: bool = True,
326
+ ):
327
+ all_hidden_states = () if output_hidden_states else None
328
+ all_self_attentions = () if output_attentions else None
329
+
330
+ for i, layer_module in enumerate(self.layer):
331
+ if output_hidden_states:
332
+ all_hidden_states = all_hidden_states + (hidden_states,)
333
+
334
+ layer_outputs = layer_module(hidden_states, attention_mask, output_attentions)
335
+
336
+ hidden_states = layer_outputs[0]
337
+ if output_attentions:
338
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
339
+
340
+ if output_hidden_states:
341
+ all_hidden_states = all_hidden_states + (hidden_states,)
342
+
343
+ if not return_dict:
344
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
345
+ return BaseModelOutputWithPastAndCrossAttentions(
346
+ last_hidden_state=hidden_states,
347
+ hidden_states=all_hidden_states,
348
+ attentions=all_self_attentions,
349
+ )
350
+
351
+
352
+ # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->Nystromformer
353
+ class NystromformerPredictionHeadTransform(nn.Module):
354
+ def __init__(self, config):
355
+ super().__init__()
356
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
357
+ if isinstance(config.hidden_act, str):
358
+ self.transform_act_fn = ACT2FN[config.hidden_act]
359
+ else:
360
+ self.transform_act_fn = config.hidden_act
361
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
362
+
363
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
364
+ hidden_states = self.dense(hidden_states)
365
+ hidden_states = self.transform_act_fn(hidden_states)
366
+ hidden_states = self.LayerNorm(hidden_states)
367
+ return hidden_states
368
+
369
+
370
+ # Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Nystromformer
371
+ class NystromformerLMPredictionHead(nn.Module):
372
+ def __init__(self, config):
373
+ super().__init__()
374
+ self.transform = NystromformerPredictionHeadTransform(config)
375
+
376
+ # The output weights are the same as the input embeddings, but there is
377
+ # an output-only bias for each token.
378
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
379
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
380
+
381
+ def forward(self, hidden_states):
382
+ hidden_states = self.transform(hidden_states)
383
+ hidden_states = self.decoder(hidden_states)
384
+ return hidden_states
385
+
386
+
387
+ # Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Nystromformer
388
+ class NystromformerOnlyMLMHead(nn.Module):
389
+ def __init__(self, config):
390
+ super().__init__()
391
+ self.predictions = NystromformerLMPredictionHead(config)
392
+
393
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
394
+ prediction_scores = self.predictions(sequence_output)
395
+ return prediction_scores
396
+
397
+
398
+ @auto_docstring
399
+ class NystromformerPreTrainedModel(PreTrainedModel):
400
+ config: NystromformerConfig
401
+ base_model_prefix = "nystromformer"
402
+ supports_gradient_checkpointing = True
403
+
404
+ def _init_weights(self, module):
405
+ super()._init_weights(module)
406
+ if isinstance(module, NystromformerEmbeddings):
407
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)) + 2)
408
+ init.zeros_(module.token_type_ids)
409
+
410
+
411
+ @auto_docstring
412
+ class NystromformerModel(NystromformerPreTrainedModel):
413
+ def __init__(self, config):
414
+ super().__init__(config)
415
+ self.config = config
416
+
417
+ self.embeddings = NystromformerEmbeddings(config)
418
+ self.encoder = NystromformerEncoder(config)
419
+
420
+ # Initialize weights and apply final processing
421
+ self.post_init()
422
+
423
+ def get_input_embeddings(self):
424
+ return self.embeddings.word_embeddings
425
+
426
+ def set_input_embeddings(self, value):
427
+ self.embeddings.word_embeddings = value
428
+
429
+ @auto_docstring
430
+ def forward(
431
+ self,
432
+ input_ids: torch.LongTensor | None = None,
433
+ attention_mask: torch.FloatTensor | None = None,
434
+ token_type_ids: torch.LongTensor | None = None,
435
+ position_ids: torch.LongTensor | None = None,
436
+ inputs_embeds: torch.FloatTensor | None = None,
437
+ output_attentions: bool | None = None,
438
+ output_hidden_states: bool | None = None,
439
+ return_dict: bool | None = None,
440
+ **kwargs,
441
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
442
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
443
+ output_hidden_states = (
444
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
445
+ )
446
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
447
+
448
+ if input_ids is not None and inputs_embeds is not None:
449
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
450
+ elif input_ids is not None:
451
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
452
+ input_shape = input_ids.size()
453
+ elif inputs_embeds is not None:
454
+ input_shape = inputs_embeds.size()[:-1]
455
+ else:
456
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
457
+
458
+ batch_size, seq_length = input_shape
459
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
460
+
461
+ if attention_mask is None:
462
+ attention_mask = torch.ones(((batch_size, seq_length)), device=device)
463
+
464
+ if token_type_ids is None:
465
+ if hasattr(self.embeddings, "token_type_ids"):
466
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
467
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
468
+ token_type_ids = buffered_token_type_ids_expanded
469
+ else:
470
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
471
+
472
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
473
+ # ourselves in which case we just need to make it broadcastable to all heads.
474
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
475
+
476
+ embedding_output = self.embeddings(
477
+ input_ids=input_ids,
478
+ position_ids=position_ids,
479
+ token_type_ids=token_type_ids,
480
+ inputs_embeds=inputs_embeds,
481
+ )
482
+ encoder_outputs = self.encoder(
483
+ embedding_output,
484
+ attention_mask=extended_attention_mask,
485
+ output_attentions=output_attentions,
486
+ output_hidden_states=output_hidden_states,
487
+ return_dict=return_dict,
488
+ )
489
+ sequence_output = encoder_outputs[0]
490
+
491
+ if not return_dict:
492
+ return (sequence_output,) + encoder_outputs[1:]
493
+
494
+ return BaseModelOutputWithPastAndCrossAttentions(
495
+ last_hidden_state=sequence_output,
496
+ hidden_states=encoder_outputs.hidden_states,
497
+ attentions=encoder_outputs.attentions,
498
+ cross_attentions=encoder_outputs.cross_attentions,
499
+ )
500
+
501
+
502
+ @auto_docstring
503
+ class NystromformerForMaskedLM(NystromformerPreTrainedModel):
504
+ _tied_weights_keys = {
505
+ "cls.predictions.decoder.weight": "nystromformer.embeddings.word_embeddings.weight",
506
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
507
+ }
508
+
509
+ def __init__(self, config):
510
+ super().__init__(config)
511
+
512
+ self.nystromformer = NystromformerModel(config)
513
+ self.cls = NystromformerOnlyMLMHead(config)
514
+
515
+ # Initialize weights and apply final processing
516
+ self.post_init()
517
+
518
+ def get_output_embeddings(self):
519
+ return self.cls.predictions.decoder
520
+
521
+ def set_output_embeddings(self, new_embeddings):
522
+ self.cls.predictions.decoder = new_embeddings
523
+ self.cls.predictions.bias = new_embeddings.bias
524
+
525
+ @auto_docstring
526
+ def forward(
527
+ self,
528
+ input_ids: torch.LongTensor | None = None,
529
+ attention_mask: torch.FloatTensor | None = None,
530
+ token_type_ids: torch.LongTensor | None = None,
531
+ position_ids: torch.LongTensor | None = None,
532
+ inputs_embeds: torch.FloatTensor | None = None,
533
+ labels: torch.LongTensor | None = None,
534
+ output_attentions: bool | None = None,
535
+ output_hidden_states: bool | None = None,
536
+ return_dict: bool | None = None,
537
+ **kwargs,
538
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
539
+ r"""
540
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
541
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
542
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
543
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
544
+ """
545
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
546
+
547
+ outputs = self.nystromformer(
548
+ input_ids,
549
+ attention_mask=attention_mask,
550
+ token_type_ids=token_type_ids,
551
+ position_ids=position_ids,
552
+ inputs_embeds=inputs_embeds,
553
+ output_attentions=output_attentions,
554
+ output_hidden_states=output_hidden_states,
555
+ return_dict=return_dict,
556
+ )
557
+
558
+ sequence_output = outputs[0]
559
+ prediction_scores = self.cls(sequence_output)
560
+
561
+ masked_lm_loss = None
562
+ if labels is not None:
563
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
564
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
565
+
566
+ if not return_dict:
567
+ output = (prediction_scores,) + outputs[1:]
568
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
569
+
570
+ return MaskedLMOutput(
571
+ loss=masked_lm_loss,
572
+ logits=prediction_scores,
573
+ hidden_states=outputs.hidden_states,
574
+ attentions=outputs.attentions,
575
+ )
576
+
577
+
578
+ class NystromformerClassificationHead(nn.Module):
579
+ """Head for sentence-level classification tasks."""
580
+
581
+ def __init__(self, config):
582
+ super().__init__()
583
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
584
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
585
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
586
+
587
+ self.config = config
588
+
589
+ def forward(self, features, **kwargs):
590
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
591
+ x = self.dropout(x)
592
+ x = self.dense(x)
593
+ x = ACT2FN[self.config.hidden_act](x)
594
+ x = self.dropout(x)
595
+ x = self.out_proj(x)
596
+ return x
597
+
598
+
599
+ @auto_docstring(
600
+ custom_intro="""
601
+ Nyströmformer Model transformer with a sequence classification/regression head on top (a linear layer on top of the
602
+ pooled output) e.g. for GLUE tasks.
603
+ """
604
+ )
605
+ class NystromformerForSequenceClassification(NystromformerPreTrainedModel):
606
+ def __init__(self, config):
607
+ super().__init__(config)
608
+ self.num_labels = config.num_labels
609
+ self.nystromformer = NystromformerModel(config)
610
+ self.classifier = NystromformerClassificationHead(config)
611
+
612
+ # Initialize weights and apply final processing
613
+ self.post_init()
614
+
615
+ @auto_docstring
616
+ def forward(
617
+ self,
618
+ input_ids: torch.LongTensor | None = None,
619
+ attention_mask: torch.FloatTensor | None = None,
620
+ token_type_ids: torch.LongTensor | None = None,
621
+ position_ids: torch.LongTensor | None = None,
622
+ inputs_embeds: torch.FloatTensor | None = None,
623
+ labels: torch.LongTensor | None = None,
624
+ output_attentions: bool | None = None,
625
+ output_hidden_states: bool | None = None,
626
+ return_dict: bool | None = None,
627
+ **kwargs,
628
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
629
+ r"""
630
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
631
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
632
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
633
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
634
+ """
635
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
636
+
637
+ outputs = self.nystromformer(
638
+ input_ids,
639
+ attention_mask=attention_mask,
640
+ token_type_ids=token_type_ids,
641
+ position_ids=position_ids,
642
+ inputs_embeds=inputs_embeds,
643
+ output_attentions=output_attentions,
644
+ output_hidden_states=output_hidden_states,
645
+ return_dict=return_dict,
646
+ )
647
+
648
+ sequence_output = outputs[0]
649
+ logits = self.classifier(sequence_output)
650
+
651
+ loss = None
652
+ if labels is not None:
653
+ if self.config.problem_type is None:
654
+ if self.num_labels == 1:
655
+ self.config.problem_type = "regression"
656
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
657
+ self.config.problem_type = "single_label_classification"
658
+ else:
659
+ self.config.problem_type = "multi_label_classification"
660
+
661
+ if self.config.problem_type == "regression":
662
+ loss_fct = MSELoss()
663
+ if self.num_labels == 1:
664
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
665
+ else:
666
+ loss = loss_fct(logits, labels)
667
+ elif self.config.problem_type == "single_label_classification":
668
+ loss_fct = CrossEntropyLoss()
669
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
670
+ elif self.config.problem_type == "multi_label_classification":
671
+ loss_fct = BCEWithLogitsLoss()
672
+ loss = loss_fct(logits, labels)
673
+ if not return_dict:
674
+ output = (logits,) + outputs[1:]
675
+ return ((loss,) + output) if loss is not None else output
676
+
677
+ return SequenceClassifierOutput(
678
+ loss=loss,
679
+ logits=logits,
680
+ hidden_states=outputs.hidden_states,
681
+ attentions=outputs.attentions,
682
+ )
683
+
684
+
685
+ @auto_docstring
686
+ class NystromformerForMultipleChoice(NystromformerPreTrainedModel):
687
+ def __init__(self, config):
688
+ super().__init__(config)
689
+
690
+ self.nystromformer = NystromformerModel(config)
691
+ self.pre_classifier = nn.Linear(config.hidden_size, config.hidden_size)
692
+ self.classifier = nn.Linear(config.hidden_size, 1)
693
+
694
+ # Initialize weights and apply final processing
695
+ self.post_init()
696
+
697
+ @auto_docstring
698
+ def forward(
699
+ self,
700
+ input_ids: torch.LongTensor | None = None,
701
+ attention_mask: torch.FloatTensor | None = None,
702
+ token_type_ids: torch.LongTensor | None = None,
703
+ position_ids: torch.LongTensor | None = None,
704
+ inputs_embeds: torch.FloatTensor | None = None,
705
+ labels: torch.LongTensor | None = None,
706
+ output_attentions: bool | None = None,
707
+ output_hidden_states: bool | None = None,
708
+ return_dict: bool | None = None,
709
+ **kwargs,
710
+ ) -> tuple[torch.Tensor] | MultipleChoiceModelOutput:
711
+ r"""
712
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
713
+ Indices of input sequence tokens in the vocabulary.
714
+
715
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
716
+ [`PreTrainedTokenizer.__call__`] for details.
717
+
718
+ [What are input IDs?](../glossary#input-ids)
719
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
720
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
721
+ 1]`:
722
+
723
+ - 0 corresponds to a *sentence A* token,
724
+ - 1 corresponds to a *sentence B* token.
725
+
726
+ [What are token type IDs?](../glossary#token-type-ids)
727
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
728
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
729
+ config.max_position_embeddings - 1]`.
730
+
731
+ [What are position IDs?](../glossary#position-ids)
732
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
733
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
734
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
735
+ model's internal embedding lookup matrix.
736
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
737
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
738
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
739
+ `input_ids` above)
740
+ """
741
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
742
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
743
+
744
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
745
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
746
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
747
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
748
+ inputs_embeds = (
749
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
750
+ if inputs_embeds is not None
751
+ else None
752
+ )
753
+
754
+ outputs = self.nystromformer(
755
+ input_ids,
756
+ attention_mask=attention_mask,
757
+ token_type_ids=token_type_ids,
758
+ position_ids=position_ids,
759
+ inputs_embeds=inputs_embeds,
760
+ output_attentions=output_attentions,
761
+ output_hidden_states=output_hidden_states,
762
+ return_dict=return_dict,
763
+ )
764
+
765
+ hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)
766
+ pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)
767
+ pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)
768
+ pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)
769
+ logits = self.classifier(pooled_output)
770
+
771
+ reshaped_logits = logits.view(-1, num_choices)
772
+
773
+ loss = None
774
+ if labels is not None:
775
+ loss_fct = CrossEntropyLoss()
776
+ loss = loss_fct(reshaped_logits, labels)
777
+
778
+ if not return_dict:
779
+ output = (reshaped_logits,) + outputs[1:]
780
+ return ((loss,) + output) if loss is not None else output
781
+
782
+ return MultipleChoiceModelOutput(
783
+ loss=loss,
784
+ logits=reshaped_logits,
785
+ hidden_states=outputs.hidden_states,
786
+ attentions=outputs.attentions,
787
+ )
788
+
789
+
790
+ @auto_docstring
791
+ class NystromformerForTokenClassification(NystromformerPreTrainedModel):
792
+ def __init__(self, config):
793
+ super().__init__(config)
794
+ self.num_labels = config.num_labels
795
+
796
+ self.nystromformer = NystromformerModel(config)
797
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
798
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
799
+
800
+ # Initialize weights and apply final processing
801
+ self.post_init()
802
+
803
+ @auto_docstring
804
+ def forward(
805
+ self,
806
+ input_ids: torch.LongTensor | None = None,
807
+ attention_mask: torch.FloatTensor | None = None,
808
+ token_type_ids: torch.LongTensor | None = None,
809
+ position_ids: torch.LongTensor | None = None,
810
+ inputs_embeds: torch.FloatTensor | None = None,
811
+ labels: torch.LongTensor | None = None,
812
+ output_attentions: bool | None = None,
813
+ output_hidden_states: bool | None = None,
814
+ return_dict: bool | None = None,
815
+ **kwargs,
816
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
817
+ r"""
818
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
819
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
820
+ """
821
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
822
+
823
+ outputs = self.nystromformer(
824
+ input_ids,
825
+ attention_mask=attention_mask,
826
+ token_type_ids=token_type_ids,
827
+ position_ids=position_ids,
828
+ inputs_embeds=inputs_embeds,
829
+ output_attentions=output_attentions,
830
+ output_hidden_states=output_hidden_states,
831
+ return_dict=return_dict,
832
+ )
833
+
834
+ sequence_output = outputs[0]
835
+
836
+ sequence_output = self.dropout(sequence_output)
837
+ logits = self.classifier(sequence_output)
838
+
839
+ loss = None
840
+ if labels is not None:
841
+ loss_fct = CrossEntropyLoss()
842
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
843
+
844
+ if not return_dict:
845
+ output = (logits,) + outputs[1:]
846
+ return ((loss,) + output) if loss is not None else output
847
+
848
+ return TokenClassifierOutput(
849
+ loss=loss,
850
+ logits=logits,
851
+ hidden_states=outputs.hidden_states,
852
+ attentions=outputs.attentions,
853
+ )
854
+
855
+
856
+ @auto_docstring
857
+ class NystromformerForQuestionAnswering(NystromformerPreTrainedModel):
858
+ def __init__(self, config):
859
+ super().__init__(config)
860
+
861
+ config.num_labels = 2
862
+ self.num_labels = config.num_labels
863
+
864
+ self.nystromformer = NystromformerModel(config)
865
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
866
+
867
+ # Initialize weights and apply final processing
868
+ self.post_init()
869
+
870
+ @auto_docstring
871
+ def forward(
872
+ self,
873
+ input_ids: torch.LongTensor | None = None,
874
+ attention_mask: torch.FloatTensor | None = None,
875
+ token_type_ids: torch.LongTensor | None = None,
876
+ position_ids: torch.LongTensor | None = None,
877
+ inputs_embeds: torch.FloatTensor | None = None,
878
+ start_positions: torch.LongTensor | None = None,
879
+ end_positions: torch.LongTensor | None = None,
880
+ output_attentions: bool | None = None,
881
+ output_hidden_states: bool | None = None,
882
+ return_dict: bool | None = None,
883
+ **kwargs,
884
+ ) -> tuple[torch.Tensor] | QuestionAnsweringModelOutput:
885
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
886
+
887
+ outputs = self.nystromformer(
888
+ input_ids,
889
+ attention_mask=attention_mask,
890
+ token_type_ids=token_type_ids,
891
+ position_ids=position_ids,
892
+ inputs_embeds=inputs_embeds,
893
+ output_attentions=output_attentions,
894
+ output_hidden_states=output_hidden_states,
895
+ return_dict=return_dict,
896
+ )
897
+
898
+ sequence_output = outputs[0]
899
+
900
+ logits = self.qa_outputs(sequence_output)
901
+ start_logits, end_logits = logits.split(1, dim=-1)
902
+ start_logits = start_logits.squeeze(-1)
903
+ end_logits = end_logits.squeeze(-1)
904
+
905
+ total_loss = None
906
+ if start_positions is not None and end_positions is not None:
907
+ # If we are on multi-GPU, split add a dimension
908
+ if len(start_positions.size()) > 1:
909
+ start_positions = start_positions.squeeze(-1)
910
+ if len(end_positions.size()) > 1:
911
+ end_positions = end_positions.squeeze(-1)
912
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
913
+ ignored_index = start_logits.size(1)
914
+ start_positions = start_positions.clamp(0, ignored_index)
915
+ end_positions = end_positions.clamp(0, ignored_index)
916
+
917
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
918
+ start_loss = loss_fct(start_logits, start_positions)
919
+ end_loss = loss_fct(end_logits, end_positions)
920
+ total_loss = (start_loss + end_loss) / 2
921
+
922
+ if not return_dict:
923
+ output = (start_logits, end_logits) + outputs[1:]
924
+ return ((total_loss,) + output) if total_loss is not None else output
925
+
926
+ return QuestionAnsweringModelOutput(
927
+ loss=total_loss,
928
+ start_logits=start_logits,
929
+ end_logits=end_logits,
930
+ hidden_states=outputs.hidden_states,
931
+ attentions=outputs.attentions,
932
+ )
933
+
934
+
935
+ __all__ = [
936
+ "NystromformerForMaskedLM",
937
+ "NystromformerForMultipleChoice",
938
+ "NystromformerForQuestionAnswering",
939
+ "NystromformerForSequenceClassification",
940
+ "NystromformerForTokenClassification",
941
+ "NystromformerLayer",
942
+ "NystromformerModel",
943
+ "NystromformerPreTrainedModel",
944
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 EleutherAI and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ 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_olmo import *
22
+ from .modeling_olmo 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__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo/configuration_olmo.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 EleutherAI and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
4
+ # and OPT implementations in this library. It has been modified from its
5
+ # original forms to accommodate minor architectural differences compared
6
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ """OLMo model configuration"""
20
+
21
+ from huggingface_hub.dataclasses import strict
22
+
23
+ from ...configuration_utils import PreTrainedConfig
24
+ from ...modeling_rope_utils import RopeParameters
25
+ from ...utils import auto_docstring
26
+
27
+
28
+ @auto_docstring(checkpoint="allenai/OLMo-7B-hf")
29
+ @strict
30
+ class OlmoConfig(PreTrainedConfig):
31
+ r"""
32
+ clip_qkv (`float`, *optional*):
33
+ If not `None`, elements of query, key and value attention states are clipped so that their
34
+ absolute value does not exceed this value.
35
+
36
+ ```python
37
+ >>> from transformers import OlmoModel, OlmoConfig
38
+
39
+ >>> # Initializing a OLMo 7B style configuration
40
+ >>> configuration = OlmoConfig()
41
+
42
+ >>> # Initializing a model from the OLMo 7B style configuration
43
+ >>> model = OlmoModel(configuration)
44
+
45
+ >>> # Accessing the model configuration
46
+ >>> configuration = model.config
47
+ ```
48
+ """
49
+
50
+ model_type = "olmo"
51
+ keys_to_ignore_at_inference = ["past_key_values"]
52
+ base_model_tp_plan = {
53
+ "layers.*.self_attn.q_proj": "colwise",
54
+ "layers.*.self_attn.k_proj": "colwise",
55
+ "layers.*.self_attn.v_proj": "colwise",
56
+ "layers.*.self_attn.o_proj": "rowwise",
57
+ "layers.*.mlp.gate_proj": "colwise",
58
+ "layers.*.mlp.up_proj": "colwise",
59
+ "layers.*.mlp.down_proj": "rowwise",
60
+ }
61
+ base_model_pp_plan = {
62
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
63
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
64
+ "norm": (["hidden_states"], ["hidden_states"]),
65
+ }
66
+
67
+ vocab_size: int = 50304
68
+ hidden_size: int = 4096
69
+ intermediate_size: int = 11008
70
+ num_hidden_layers: int = 32
71
+ num_attention_heads: int = 32
72
+ num_key_value_heads: int | None = None
73
+ hidden_act: str = "silu"
74
+ max_position_embeddings: int = 2048
75
+ initializer_range: float = 0.02
76
+ use_cache: bool = True
77
+ pad_token_id: int | None = 1
78
+ bos_token_id: int | None = None
79
+ eos_token_id: int | list[int] | None = 50279
80
+ tie_word_embeddings: bool = False
81
+ rope_parameters: RopeParameters | dict | None = None
82
+ attention_bias: bool = False
83
+ attention_dropout: float | int = 0.0
84
+ clip_qkv: float | None = None
85
+
86
+ def __post_init__(self, **kwargs):
87
+ if self.num_key_value_heads is None:
88
+ self.num_key_value_heads = self.num_attention_heads
89
+ super().__post_init__(**kwargs)
90
+
91
+
92
+ __all__ = ["OlmoConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo/modeling_olmo.py ADDED
@@ -0,0 +1,503 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/olmo/modular_olmo.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_olmo.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
10
+ # and OPT implementations in this library. It has been modified from its
11
+ # original forms to accommodate minor architectural differences compared
12
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
13
+ #
14
+ # Licensed under the Apache License, Version 2.0 (the "License");
15
+ # you may not use this file except in compliance with the License.
16
+ # You may obtain a copy of the License at
17
+ #
18
+ # http://www.apache.org/licenses/LICENSE-2.0
19
+ #
20
+ # Unless required by applicable law or agreed to in writing, software
21
+ # distributed under the License is distributed on an "AS IS" BASIS,
22
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
+ # See the License for the specific language governing permissions and
24
+ # limitations under the License.
25
+
26
+ from collections.abc import Callable
27
+ from typing import Optional
28
+
29
+ import torch
30
+ import torch.nn as nn
31
+ import torch.nn.functional as F
32
+
33
+ from ...activations import ACT2FN
34
+ from ...cache_utils import Cache, DynamicCache
35
+ from ...generation import GenerationMixin
36
+ from ...integrations import use_kernelized_func
37
+ from ...masking_utils import create_causal_mask
38
+ from ...modeling_layers import GenericForSequenceClassification, GradientCheckpointingLayer
39
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
40
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
41
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
42
+ from ...processing_utils import Unpack
43
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
44
+ from ...utils.generic import maybe_autocast, merge_with_config_defaults
45
+ from ...utils.output_capturing import capture_outputs
46
+ from .configuration_olmo import OlmoConfig
47
+
48
+
49
+ class OlmoLayerNorm(nn.Module):
50
+ """LayerNorm but with no learnable weight or bias."""
51
+
52
+ def __init__(self, hidden_size: int) -> None:
53
+ super().__init__()
54
+ self.normalized_shape = (hidden_size,)
55
+
56
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
57
+ orig_dtype = hidden_states.dtype
58
+ return F.layer_norm(hidden_states.to(dtype=torch.float32), self.normalized_shape, None, None, eps=1e-5).to(
59
+ orig_dtype
60
+ )
61
+
62
+
63
+ class OlmoMLP(nn.Module):
64
+ def __init__(self, config):
65
+ super().__init__()
66
+ self.config = config
67
+ self.hidden_size = config.hidden_size
68
+ self.intermediate_size = config.intermediate_size
69
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
70
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
71
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
72
+ self.act_fn = ACT2FN[config.hidden_act]
73
+
74
+ def forward(self, x):
75
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
76
+ return down_proj
77
+
78
+
79
+ class OlmoRotaryEmbedding(nn.Module):
80
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
81
+
82
+ def __init__(self, config: OlmoConfig, device=None):
83
+ super().__init__()
84
+ self.max_seq_len_cached = config.max_position_embeddings
85
+ self.original_max_seq_len = config.max_position_embeddings
86
+
87
+ self.config = config
88
+
89
+ self.rope_type = self.config.rope_parameters["rope_type"]
90
+ rope_init_fn: Callable = self.compute_default_rope_parameters
91
+ if self.rope_type != "default":
92
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
93
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
94
+
95
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
96
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
97
+
98
+ @staticmethod
99
+ def compute_default_rope_parameters(
100
+ config: OlmoConfig | None = None,
101
+ device: Optional["torch.device"] = None,
102
+ seq_len: int | None = None,
103
+ ) -> tuple["torch.Tensor", float]:
104
+ """
105
+ Computes the inverse frequencies according to the original RoPE implementation
106
+ Args:
107
+ config ([`~transformers.PreTrainedConfig`]):
108
+ The model configuration.
109
+ device (`torch.device`):
110
+ The device to use for initialization of the inverse frequencies.
111
+ seq_len (`int`, *optional*):
112
+ The current sequence length. Unused for this type of RoPE.
113
+ Returns:
114
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
115
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
116
+ """
117
+ base = config.rope_parameters["rope_theta"]
118
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
119
+
120
+ attention_factor = 1.0 # Unused in this type of RoPE
121
+
122
+ # Compute the inverse frequencies
123
+ inv_freq = 1.0 / (
124
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
125
+ )
126
+ return inv_freq, attention_factor
127
+
128
+ @torch.no_grad()
129
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
130
+ def forward(self, x, position_ids):
131
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
132
+ position_ids_expanded = position_ids[:, None, :].float()
133
+
134
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
135
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
136
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
137
+ emb = torch.cat((freqs, freqs), dim=-1)
138
+ cos = emb.cos() * self.attention_scaling
139
+ sin = emb.sin() * self.attention_scaling
140
+ return cos, sin
141
+
142
+
143
+ def rotate_half(x):
144
+ """Rotates half the hidden dims of the input."""
145
+ x1 = x[..., : x.shape[-1] // 2]
146
+ x2 = x[..., x.shape[-1] // 2 :]
147
+ return torch.cat((-x2, x1), dim=-1)
148
+
149
+
150
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
151
+ """
152
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
153
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
154
+ """
155
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
156
+ if n_rep == 1:
157
+ return hidden_states
158
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
159
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
160
+
161
+
162
+ def eager_attention_forward(
163
+ module: nn.Module,
164
+ query: torch.Tensor,
165
+ key: torch.Tensor,
166
+ value: torch.Tensor,
167
+ attention_mask: torch.Tensor | None,
168
+ scaling: float,
169
+ dropout: float = 0.0,
170
+ **kwargs: Unpack[TransformersKwargs],
171
+ ):
172
+ key_states = repeat_kv(key, module.num_key_value_groups)
173
+ value_states = repeat_kv(value, module.num_key_value_groups)
174
+
175
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
176
+ if attention_mask is not None:
177
+ attn_weights = attn_weights + attention_mask
178
+
179
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
180
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
181
+ attn_output = torch.matmul(attn_weights, value_states)
182
+ attn_output = attn_output.transpose(1, 2).contiguous()
183
+
184
+ return attn_output, attn_weights
185
+
186
+
187
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
188
+ """Applies Rotary Position Embedding to the query and key tensors.
189
+
190
+ Args:
191
+ q (`torch.Tensor`): The query tensor.
192
+ k (`torch.Tensor`): The key tensor.
193
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
194
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
195
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
196
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
197
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
198
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
199
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
200
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
201
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
202
+ Returns:
203
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
204
+ """
205
+ q_type, k_type = q.dtype, k.dtype
206
+ cos = cos.unsqueeze(unsqueeze_dim)
207
+ sin = sin.unsqueeze(unsqueeze_dim)
208
+ q_embed = (q * cos) + (rotate_half(q) * sin)
209
+ k_embed = (k * cos) + (rotate_half(k) * sin)
210
+ return q_embed.to(q_type), k_embed.to(k_type)
211
+
212
+
213
+ @use_kernelized_func(apply_rotary_pos_emb)
214
+ class OlmoAttention(nn.Module):
215
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
216
+
217
+ def __init__(self, config: OlmoConfig, layer_idx: int):
218
+ super().__init__()
219
+ self.config = config
220
+ self.layer_idx = layer_idx
221
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
222
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
223
+ self.scaling = self.head_dim**-0.5
224
+ self.attention_dropout = config.attention_dropout
225
+ self.is_causal = True
226
+
227
+ self.q_proj = nn.Linear(
228
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
229
+ )
230
+ self.k_proj = nn.Linear(
231
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
232
+ )
233
+ self.v_proj = nn.Linear(
234
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
235
+ )
236
+ self.o_proj = nn.Linear(
237
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
238
+ )
239
+
240
+ def forward(
241
+ self,
242
+ hidden_states: torch.Tensor,
243
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
244
+ attention_mask: torch.Tensor | None,
245
+ past_key_values: Cache | None = None,
246
+ **kwargs,
247
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
248
+ input_shape = hidden_states.shape[:-1]
249
+ hidden_shape = (*input_shape, -1, self.head_dim)
250
+
251
+ query_states = self.q_proj(hidden_states)
252
+ key_states = self.k_proj(hidden_states)
253
+ value_states = self.v_proj(hidden_states)
254
+
255
+ if self.config.clip_qkv is not None:
256
+ query_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
257
+ key_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
258
+ value_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
259
+
260
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
261
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
262
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
263
+
264
+ cos, sin = position_embeddings
265
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
266
+
267
+ if past_key_values is not None:
268
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
269
+
270
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
271
+ self.config._attn_implementation, eager_attention_forward
272
+ )
273
+
274
+ attn_output, attn_weights = attention_interface(
275
+ self,
276
+ query_states,
277
+ key_states,
278
+ value_states,
279
+ attention_mask,
280
+ dropout=0.0 if not self.training else self.attention_dropout,
281
+ scaling=self.scaling,
282
+ **kwargs,
283
+ )
284
+
285
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
286
+ attn_output = self.o_proj(attn_output)
287
+ return attn_output, attn_weights
288
+
289
+
290
+ class OlmoDecoderLayer(GradientCheckpointingLayer):
291
+ def __init__(self, config: OlmoConfig, layer_idx: int):
292
+ super().__init__()
293
+ self.hidden_size = config.hidden_size
294
+ self.self_attn = OlmoAttention(config=config, layer_idx=layer_idx)
295
+
296
+ self.mlp = OlmoMLP(config)
297
+ self.input_layernorm = OlmoLayerNorm(config.hidden_size)
298
+ self.post_attention_layernorm = OlmoLayerNorm(config.hidden_size)
299
+
300
+ def forward(
301
+ self,
302
+ hidden_states: torch.Tensor,
303
+ attention_mask: torch.Tensor | None = None,
304
+ position_ids: torch.LongTensor | None = None,
305
+ past_key_values: Cache | None = None,
306
+ use_cache: bool | None = False,
307
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
308
+ **kwargs: Unpack[TransformersKwargs],
309
+ ) -> torch.Tensor:
310
+ residual = hidden_states
311
+ hidden_states = self.input_layernorm(hidden_states)
312
+ # Self Attention
313
+ hidden_states, _ = self.self_attn(
314
+ hidden_states=hidden_states,
315
+ attention_mask=attention_mask,
316
+ position_ids=position_ids,
317
+ past_key_values=past_key_values,
318
+ use_cache=use_cache,
319
+ position_embeddings=position_embeddings,
320
+ **kwargs,
321
+ )
322
+ hidden_states = residual + hidden_states
323
+
324
+ # Fully Connected
325
+ residual = hidden_states
326
+ hidden_states = self.post_attention_layernorm(hidden_states)
327
+ hidden_states = self.mlp(hidden_states)
328
+ hidden_states = residual + hidden_states
329
+ return hidden_states
330
+
331
+
332
+ @auto_docstring
333
+ class OlmoPreTrainedModel(PreTrainedModel):
334
+ config: OlmoConfig
335
+ base_model_prefix = "model"
336
+ supports_gradient_checkpointing = True
337
+ _no_split_modules = ["OlmoDecoderLayer"]
338
+ _skip_keys_device_placement = ["past_key_values"]
339
+ _supports_flash_attn = True
340
+ _supports_sdpa = True
341
+ _supports_flex_attn = True
342
+
343
+ _can_compile_fullgraph = True
344
+ _supports_attention_backend = True
345
+ _can_record_outputs = {
346
+ "hidden_states": OlmoDecoderLayer,
347
+ "attentions": OlmoAttention,
348
+ }
349
+
350
+
351
+ @auto_docstring
352
+ class OlmoModel(OlmoPreTrainedModel):
353
+ def __init__(self, config: OlmoConfig):
354
+ super().__init__(config)
355
+ self.padding_idx = config.pad_token_id
356
+ self.vocab_size = config.vocab_size
357
+
358
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
359
+ self.layers = nn.ModuleList(
360
+ [OlmoDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
361
+ )
362
+ self.norm = OlmoLayerNorm(config.hidden_size)
363
+ self.rotary_emb = OlmoRotaryEmbedding(config=config)
364
+ self.gradient_checkpointing = False
365
+
366
+ # Initialize weights and apply final processing
367
+ self.post_init()
368
+
369
+ @merge_with_config_defaults
370
+ @capture_outputs
371
+ @auto_docstring
372
+ def forward(
373
+ self,
374
+ input_ids: torch.LongTensor | None = None,
375
+ attention_mask: torch.Tensor | None = None,
376
+ position_ids: torch.LongTensor | None = None,
377
+ past_key_values: Cache | None = None,
378
+ inputs_embeds: torch.FloatTensor | None = None,
379
+ use_cache: bool | None = None,
380
+ **kwargs: Unpack[TransformersKwargs],
381
+ ) -> BaseModelOutputWithPast:
382
+ if (input_ids is None) ^ (inputs_embeds is not None):
383
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
384
+
385
+ if inputs_embeds is None:
386
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
387
+
388
+ if use_cache and past_key_values is None:
389
+ past_key_values = DynamicCache(config=self.config)
390
+
391
+ if position_ids is None:
392
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
393
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
394
+ position_ids = position_ids.unsqueeze(0)
395
+
396
+ causal_mask = create_causal_mask(
397
+ config=self.config,
398
+ inputs_embeds=inputs_embeds,
399
+ attention_mask=attention_mask,
400
+ past_key_values=past_key_values,
401
+ position_ids=position_ids,
402
+ )
403
+
404
+ hidden_states = inputs_embeds
405
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
406
+
407
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
408
+ hidden_states = decoder_layer(
409
+ hidden_states,
410
+ attention_mask=causal_mask,
411
+ position_embeddings=position_embeddings,
412
+ position_ids=position_ids,
413
+ past_key_values=past_key_values,
414
+ use_cache=use_cache,
415
+ **kwargs,
416
+ )
417
+
418
+ hidden_states = self.norm(hidden_states)
419
+ return BaseModelOutputWithPast(
420
+ last_hidden_state=hidden_states,
421
+ past_key_values=past_key_values,
422
+ )
423
+
424
+
425
+ @auto_docstring
426
+ class OlmoForCausalLM(OlmoPreTrainedModel, GenerationMixin):
427
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
428
+ _tp_plan = {"lm_head": "colwise_gather_output"}
429
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
430
+
431
+ def __init__(self, config):
432
+ super().__init__(config)
433
+ self.model = OlmoModel(config)
434
+ self.vocab_size = config.vocab_size
435
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
436
+
437
+ # Initialize weights and apply final processing
438
+ self.post_init()
439
+
440
+ @can_return_tuple
441
+ @auto_docstring
442
+ def forward(
443
+ self,
444
+ input_ids: torch.LongTensor | None = None,
445
+ attention_mask: torch.Tensor | None = None,
446
+ position_ids: torch.LongTensor | None = None,
447
+ past_key_values: Cache | None = None,
448
+ inputs_embeds: torch.FloatTensor | None = None,
449
+ labels: torch.LongTensor | None = None,
450
+ use_cache: bool | None = None,
451
+ logits_to_keep: int | torch.Tensor = 0,
452
+ **kwargs: Unpack[TransformersKwargs],
453
+ ) -> CausalLMOutputWithPast:
454
+ r"""
455
+ Example:
456
+
457
+ ```python
458
+ >>> from transformers import AutoTokenizer, OlmoForCausalLM
459
+
460
+ >>> model = OlmoForCausalLM.from_pretrained("meta-olmo/Olmo-2-7b-hf")
461
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-olmo/Olmo-2-7b-hf")
462
+
463
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
464
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
465
+
466
+ >>> # Generate
467
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
468
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
469
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
470
+ ```"""
471
+ outputs: BaseModelOutputWithPast = self.model(
472
+ input_ids=input_ids,
473
+ attention_mask=attention_mask,
474
+ position_ids=position_ids,
475
+ past_key_values=past_key_values,
476
+ inputs_embeds=inputs_embeds,
477
+ use_cache=use_cache,
478
+ **kwargs,
479
+ )
480
+
481
+ hidden_states = outputs.last_hidden_state
482
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
483
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
484
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
485
+
486
+ loss = None
487
+ if labels is not None:
488
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
489
+
490
+ return CausalLMOutputWithPast(
491
+ loss=loss,
492
+ logits=logits,
493
+ past_key_values=outputs.past_key_values,
494
+ hidden_states=outputs.hidden_states,
495
+ attentions=outputs.attentions,
496
+ )
497
+
498
+
499
+ class OlmoForSequenceClassification(GenericForSequenceClassification, OlmoPreTrainedModel):
500
+ pass
501
+
502
+
503
+ __all__ = ["OlmoForCausalLM", "OlmoForSequenceClassification", "OlmoModel", "OlmoPreTrainedModel"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo/modular_olmo.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
4
+ # and OPT implementations in this library. It has been modified from its
5
+ # original forms to accommodate minor architectural differences compared
6
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+
20
+ from collections.abc import Callable
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+ import torch.nn.functional as F
25
+
26
+ from ...cache_utils import Cache
27
+ from ...modeling_rope_utils import dynamic_rope_update
28
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
29
+ from ...utils import logging
30
+ from ...utils.generic import maybe_autocast
31
+ from ..llama.modeling_llama import (
32
+ LlamaAttention,
33
+ LlamaDecoderLayer,
34
+ LlamaForCausalLM,
35
+ LlamaForSequenceClassification,
36
+ LlamaMLP,
37
+ LlamaModel,
38
+ LlamaRotaryEmbedding,
39
+ eager_attention_forward,
40
+ rotate_half,
41
+ )
42
+ from .configuration_olmo import OlmoConfig
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+
48
+ class OlmoLayerNorm(nn.Module):
49
+ """LayerNorm but with no learnable weight or bias."""
50
+
51
+ def __init__(self, hidden_size: int) -> None:
52
+ super().__init__()
53
+ self.normalized_shape = (hidden_size,)
54
+
55
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
56
+ orig_dtype = hidden_states.dtype
57
+ return F.layer_norm(hidden_states.to(dtype=torch.float32), self.normalized_shape, None, None, eps=1e-5).to(
58
+ orig_dtype
59
+ )
60
+
61
+
62
+ class OlmoMLP(LlamaMLP):
63
+ def __init__(self, config):
64
+ super().__init__(config)
65
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
66
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
67
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
68
+
69
+
70
+ # This is identical to LlamaRotaryEmbedding except the output cos and sin are returned
71
+ # as float32 rather than the input type.
72
+ class OlmoRotaryEmbedding(LlamaRotaryEmbedding):
73
+ @torch.no_grad()
74
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
75
+ def forward(self, x, position_ids):
76
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
77
+ position_ids_expanded = position_ids[:, None, :].float()
78
+
79
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
80
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
81
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
82
+ emb = torch.cat((freqs, freqs), dim=-1)
83
+ cos = emb.cos() * self.attention_scaling
84
+ sin = emb.sin() * self.attention_scaling
85
+ return cos, sin
86
+
87
+
88
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
89
+ """Applies Rotary Position Embedding to the query and key tensors.
90
+
91
+ Args:
92
+ q (`torch.Tensor`): The query tensor.
93
+ k (`torch.Tensor`): The key tensor.
94
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
95
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
96
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
97
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
98
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
99
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
100
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
101
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
102
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
103
+ Returns:
104
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
105
+ """
106
+ q_type, k_type = q.dtype, k.dtype
107
+ cos = cos.unsqueeze(unsqueeze_dim)
108
+ sin = sin.unsqueeze(unsqueeze_dim)
109
+ q_embed = (q * cos) + (rotate_half(q) * sin)
110
+ k_embed = (k * cos) + (rotate_half(k) * sin)
111
+ return q_embed.to(q_type), k_embed.to(k_type)
112
+
113
+
114
+ class OlmoAttention(LlamaAttention):
115
+ def forward(
116
+ self,
117
+ hidden_states: torch.Tensor,
118
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
119
+ attention_mask: torch.Tensor | None,
120
+ past_key_values: Cache | None = None,
121
+ **kwargs,
122
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
123
+ input_shape = hidden_states.shape[:-1]
124
+ hidden_shape = (*input_shape, -1, self.head_dim)
125
+
126
+ query_states = self.q_proj(hidden_states)
127
+ key_states = self.k_proj(hidden_states)
128
+ value_states = self.v_proj(hidden_states)
129
+
130
+ if self.config.clip_qkv is not None:
131
+ query_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
132
+ key_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
133
+ value_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
134
+
135
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
136
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
137
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
138
+
139
+ cos, sin = position_embeddings
140
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
141
+
142
+ if past_key_values is not None:
143
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
144
+
145
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
146
+ self.config._attn_implementation, eager_attention_forward
147
+ )
148
+
149
+ attn_output, attn_weights = attention_interface(
150
+ self,
151
+ query_states,
152
+ key_states,
153
+ value_states,
154
+ attention_mask,
155
+ dropout=0.0 if not self.training else self.attention_dropout,
156
+ scaling=self.scaling,
157
+ **kwargs,
158
+ )
159
+
160
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
161
+ attn_output = self.o_proj(attn_output)
162
+ return attn_output, attn_weights
163
+
164
+
165
+ class OlmoDecoderLayer(LlamaDecoderLayer):
166
+ def __init__(self, config: OlmoConfig, layer_idx: int):
167
+ super().__init__(config, layer_idx)
168
+ self.input_layernorm = OlmoLayerNorm(config.hidden_size)
169
+ self.post_attention_layernorm = OlmoLayerNorm(config.hidden_size)
170
+ self.self_attn = OlmoAttention(config=config, layer_idx=layer_idx)
171
+
172
+
173
+ class OlmoModel(LlamaModel):
174
+ def __init__(self, config: OlmoConfig):
175
+ super().__init__(config)
176
+ self.layers = nn.ModuleList(
177
+ [OlmoDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
178
+ )
179
+ self.norm = OlmoLayerNorm(config.hidden_size)
180
+
181
+
182
+ class OlmoForCausalLM(LlamaForCausalLM):
183
+ pass
184
+
185
+
186
+ class OlmoForSequenceClassification(LlamaForSequenceClassification):
187
+ pass
188
+
189
+
190
+ __all__ = [
191
+ "OlmoForCausalLM",
192
+ "OlmoForSequenceClassification",
193
+ "OlmoModel",
194
+ "OlmoPreTrainedModel", # noqa: F822
195
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo2/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 EleutherAI and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ 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_olmo2 import *
22
+ from .modeling_olmo2 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__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo2/configuration_olmo2.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/olmo2/modular_olmo2.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_olmo2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
10
+ # and OPT implementations in this library. It has been modified from its
11
+ # original forms to accommodate minor architectural differences compared
12
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
13
+ #
14
+ # Licensed under the Apache License, Version 2.0 (the "License");
15
+ # you may not use this file except in compliance with the License.
16
+ # You may obtain a copy of the License at
17
+ #
18
+ # http://www.apache.org/licenses/LICENSE-2.0
19
+ #
20
+ # Unless required by applicable law or agreed to in writing, software
21
+ # distributed under the License is distributed on an "AS IS" BASIS,
22
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
+ # See the License for the specific language governing permissions and
24
+ # limitations under the License.
25
+
26
+ from huggingface_hub.dataclasses import strict
27
+
28
+ from ...configuration_utils import PreTrainedConfig
29
+ from ...modeling_rope_utils import RopeParameters
30
+ from ...utils import auto_docstring
31
+
32
+
33
+ @auto_docstring(checkpoint="allenai/Olmo2-7B-1124-hf")
34
+ @strict
35
+ class Olmo2Config(PreTrainedConfig):
36
+ r"""
37
+ Example:
38
+
39
+ ```python
40
+ >>> from transformers import Olmo2Model, Olmo2Config
41
+
42
+ >>> # Initializing a Olmo2 7B style configuration
43
+ >>> configuration = Olmo2Config()
44
+
45
+ >>> # Initializing a model from the Olmo2 7B style configuration
46
+ >>> model = Olmo2Model(configuration)
47
+
48
+ >>> # Accessing the model configuration
49
+ >>> configuration = model.config
50
+ ```
51
+ """
52
+
53
+ model_type = "olmo2"
54
+ keys_to_ignore_at_inference = ["past_key_values"]
55
+ base_model_tp_plan = {
56
+ "layers.*.self_attn.q_proj": "colwise_gather_output", # we need to replicate here due to the added norm on q and k
57
+ "layers.*.self_attn.k_proj": "colwise_gather_output", # we need to replicate here due to the added norm on q and k
58
+ "layers.*.self_attn.v_proj": "colwise_gather_output", # we need to replicate here due to the added norm on q and k
59
+ "layers.*.self_attn.o_proj": "rowwise_split_input", # input is replicated due to the added norm on q and k
60
+ "layers.*.mlp.gate_proj": "colwise",
61
+ "layers.*.mlp.up_proj": "colwise",
62
+ "layers.*.mlp.down_proj": "rowwise",
63
+ }
64
+ base_model_pp_plan = {
65
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
66
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
67
+ "norm": (["hidden_states"], ["hidden_states"]),
68
+ }
69
+
70
+ vocab_size: int = 50304
71
+ hidden_size: int = 4096
72
+ intermediate_size: int = 11008
73
+ num_hidden_layers: int = 32
74
+ num_attention_heads: int = 32
75
+ num_key_value_heads: int | None = None
76
+ hidden_act: str = "silu"
77
+ max_position_embeddings: int = 2048
78
+ initializer_range: float = 0.02
79
+ use_cache: bool = True
80
+ pad_token_id: int | None = 1
81
+ bos_token_id: int | None = None
82
+ eos_token_id: int | list[int] | None = 50279
83
+ tie_word_embeddings: bool = False
84
+ rope_parameters: RopeParameters | dict | None = None
85
+ attention_bias: bool = False
86
+ attention_dropout: float | int = 0.0
87
+
88
+ rms_norm_eps: float = 1e-5
89
+
90
+ def __post_init__(self, **kwargs):
91
+ if self.num_key_value_heads is None:
92
+ self.num_key_value_heads = self.num_attention_heads
93
+ super().__post_init__(**kwargs)
94
+
95
+
96
+ __all__ = ["Olmo2Config"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo2/modeling_olmo2.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/olmo2/modular_olmo2.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_olmo2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
10
+ # and OPT implementations in this library. It has been modified from its
11
+ # original forms to accommodate minor architectural differences compared
12
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
13
+ #
14
+ # Licensed under the Apache License, Version 2.0 (the "License");
15
+ # you may not use this file except in compliance with the License.
16
+ # You may obtain a copy of the License at
17
+ #
18
+ # http://www.apache.org/licenses/LICENSE-2.0
19
+ #
20
+ # Unless required by applicable law or agreed to in writing, software
21
+ # distributed under the License is distributed on an "AS IS" BASIS,
22
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
+ # See the License for the specific language governing permissions and
24
+ # limitations under the License.
25
+
26
+ from collections.abc import Callable
27
+ from typing import Optional
28
+
29
+ import torch
30
+ import torch.nn as nn
31
+
32
+ from transformers.utils.generic import TransformersKwargs
33
+
34
+ from ...activations import ACT2FN
35
+ from ...cache_utils import Cache, DynamicCache
36
+ from ...generation import GenerationMixin
37
+ from ...integrations import use_kernel_forward_from_hub, use_kernelized_func
38
+ from ...masking_utils import create_causal_mask
39
+ from ...modeling_layers import GenericForSequenceClassification, GradientCheckpointingLayer
40
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
41
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
42
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
43
+ from ...processing_utils import Unpack
44
+ from ...utils import auto_docstring, can_return_tuple
45
+ from ...utils.generic import maybe_autocast, merge_with_config_defaults
46
+ from ...utils.output_capturing import capture_outputs
47
+ from .configuration_olmo2 import Olmo2Config
48
+
49
+
50
+ @use_kernel_forward_from_hub("RMSNorm")
51
+ class Olmo2RMSNorm(nn.Module):
52
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
53
+ """
54
+ Olmo2RMSNorm is equivalent to T5LayerNorm
55
+ """
56
+ super().__init__()
57
+ self.weight = nn.Parameter(torch.ones(hidden_size))
58
+ self.variance_epsilon = eps
59
+
60
+ def forward(self, hidden_states) -> torch.Tensor:
61
+ input_dtype = hidden_states.dtype
62
+ hidden_states = hidden_states.to(torch.float32)
63
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
64
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
65
+ return (self.weight * hidden_states).to(input_dtype)
66
+
67
+ def extra_repr(self):
68
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
69
+
70
+
71
+ class Olmo2RotaryEmbedding(nn.Module):
72
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
73
+
74
+ def __init__(self, config: Olmo2Config, device=None):
75
+ super().__init__()
76
+ self.max_seq_len_cached = config.max_position_embeddings
77
+ self.original_max_seq_len = config.max_position_embeddings
78
+
79
+ self.config = config
80
+
81
+ self.rope_type = self.config.rope_parameters["rope_type"]
82
+ rope_init_fn: Callable = self.compute_default_rope_parameters
83
+ if self.rope_type != "default":
84
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
85
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
86
+
87
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
88
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
89
+
90
+ @staticmethod
91
+ def compute_default_rope_parameters(
92
+ config: Olmo2Config | None = None,
93
+ device: Optional["torch.device"] = None,
94
+ seq_len: int | None = None,
95
+ ) -> tuple["torch.Tensor", float]:
96
+ """
97
+ Computes the inverse frequencies according to the original RoPE implementation
98
+ Args:
99
+ config ([`~transformers.PreTrainedConfig`]):
100
+ The model configuration.
101
+ device (`torch.device`):
102
+ The device to use for initialization of the inverse frequencies.
103
+ seq_len (`int`, *optional*):
104
+ The current sequence length. Unused for this type of RoPE.
105
+ Returns:
106
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
107
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
108
+ """
109
+ base = config.rope_parameters["rope_theta"]
110
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
111
+
112
+ attention_factor = 1.0 # Unused in this type of RoPE
113
+
114
+ # Compute the inverse frequencies
115
+ inv_freq = 1.0 / (
116
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
117
+ )
118
+ return inv_freq, attention_factor
119
+
120
+ @torch.no_grad()
121
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
122
+ def forward(self, x, position_ids):
123
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
124
+ position_ids_expanded = position_ids[:, None, :].float()
125
+
126
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
127
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
128
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
129
+ emb = torch.cat((freqs, freqs), dim=-1)
130
+ cos = emb.cos() * self.attention_scaling
131
+ sin = emb.sin() * self.attention_scaling
132
+ return cos, sin
133
+
134
+
135
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
136
+ """
137
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
138
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
139
+ """
140
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
141
+ if n_rep == 1:
142
+ return hidden_states
143
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
144
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
145
+
146
+
147
+ def eager_attention_forward(
148
+ module: nn.Module,
149
+ query: torch.Tensor,
150
+ key: torch.Tensor,
151
+ value: torch.Tensor,
152
+ attention_mask: torch.Tensor | None,
153
+ scaling: float,
154
+ dropout: float = 0.0,
155
+ **kwargs: Unpack[TransformersKwargs],
156
+ ):
157
+ key_states = repeat_kv(key, module.num_key_value_groups)
158
+ value_states = repeat_kv(value, module.num_key_value_groups)
159
+
160
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
161
+ if attention_mask is not None:
162
+ attn_weights = attn_weights + attention_mask
163
+
164
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
165
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
166
+ attn_output = torch.matmul(attn_weights, value_states)
167
+ attn_output = attn_output.transpose(1, 2).contiguous()
168
+
169
+ return attn_output, attn_weights
170
+
171
+
172
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
173
+ """Applies Rotary Position Embedding to the query and key tensors.
174
+
175
+ Args:
176
+ q (`torch.Tensor`): The query tensor.
177
+ k (`torch.Tensor`): The key tensor.
178
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
179
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
180
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
181
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
182
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
183
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
184
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
185
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
186
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
187
+ Returns:
188
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
189
+ """
190
+ q_type, k_type = q.dtype, k.dtype
191
+ cos = cos.unsqueeze(unsqueeze_dim)
192
+ sin = sin.unsqueeze(unsqueeze_dim)
193
+ q_embed = (q * cos) + (rotate_half(q) * sin)
194
+ k_embed = (k * cos) + (rotate_half(k) * sin)
195
+ return q_embed.to(q_type), k_embed.to(k_type)
196
+
197
+
198
+ def rotate_half(x):
199
+ """Rotates half the hidden dims of the input."""
200
+ x1 = x[..., : x.shape[-1] // 2]
201
+ x2 = x[..., x.shape[-1] // 2 :]
202
+ return torch.cat((-x2, x1), dim=-1)
203
+
204
+
205
+ @use_kernelized_func(apply_rotary_pos_emb)
206
+ class Olmo2Attention(nn.Module):
207
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
208
+
209
+ def __init__(self, config: Olmo2Config, layer_idx: int | None = None):
210
+ super().__init__()
211
+ self.config = config
212
+ self.layer_idx = layer_idx
213
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
214
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
215
+ self.scaling = self.head_dim**-0.5
216
+ self.attention_dropout = config.attention_dropout
217
+ self.is_causal = True
218
+
219
+ self.q_proj = nn.Linear(
220
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
221
+ )
222
+ self.k_proj = nn.Linear(
223
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
224
+ )
225
+ self.v_proj = nn.Linear(
226
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
227
+ )
228
+ self.o_proj = nn.Linear(
229
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
230
+ )
231
+ self.q_norm = Olmo2RMSNorm(config.num_attention_heads * self.head_dim, config.rms_norm_eps)
232
+ self.k_norm = Olmo2RMSNorm(config.num_key_value_heads * self.head_dim, config.rms_norm_eps)
233
+
234
+ def forward(
235
+ self,
236
+ hidden_states: torch.Tensor,
237
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
238
+ attention_mask: torch.Tensor | None,
239
+ past_key_values: Cache | None = None,
240
+ **kwargs: Unpack[TransformersKwargs],
241
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
242
+ input_shape = hidden_states.shape[:-1]
243
+ hidden_shape = (*input_shape, -1, self.head_dim)
244
+
245
+ query_states = self.q_norm(self.q_proj(hidden_states))
246
+ key_states = self.k_norm(self.k_proj(hidden_states))
247
+ value_states = self.v_proj(hidden_states)
248
+
249
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
250
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
251
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
252
+
253
+ cos, sin = position_embeddings
254
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
255
+
256
+ if past_key_values is not None:
257
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
258
+
259
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
260
+ self.config._attn_implementation, eager_attention_forward
261
+ )
262
+
263
+ attn_output, attn_weights = attention_interface(
264
+ self,
265
+ query_states,
266
+ key_states,
267
+ value_states,
268
+ attention_mask,
269
+ dropout=0.0 if not self.training else self.attention_dropout,
270
+ scaling=self.scaling,
271
+ **kwargs,
272
+ )
273
+
274
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
275
+ attn_output = self.o_proj(attn_output)
276
+ return attn_output, attn_weights
277
+
278
+
279
+ class Olmo2MLP(nn.Module):
280
+ def __init__(self, config):
281
+ super().__init__()
282
+ self.config = config
283
+ self.hidden_size = config.hidden_size
284
+ self.intermediate_size = config.intermediate_size
285
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
286
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
287
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
288
+ self.act_fn = ACT2FN[config.hidden_act]
289
+
290
+ def forward(self, x):
291
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
292
+ return down_proj
293
+
294
+
295
+ class Olmo2DecoderLayer(GradientCheckpointingLayer):
296
+ def __init__(self, config: Olmo2Config, layer_idx: int):
297
+ super().__init__()
298
+ self.hidden_size = config.hidden_size
299
+ self.self_attn = Olmo2Attention(config=config, layer_idx=layer_idx)
300
+
301
+ self.mlp = Olmo2MLP(config)
302
+ self.post_attention_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
303
+ self.post_feedforward_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
304
+
305
+ def forward(
306
+ self,
307
+ hidden_states: torch.Tensor,
308
+ attention_mask: torch.Tensor | None = None,
309
+ position_ids: torch.LongTensor | None = None,
310
+ past_key_values: Cache | None = None,
311
+ use_cache: bool | None = False,
312
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
313
+ **kwargs: Unpack[TransformersKwargs],
314
+ ) -> torch.Tensor:
315
+ residual = hidden_states
316
+ hidden_states, _ = self.self_attn(
317
+ hidden_states=hidden_states,
318
+ attention_mask=attention_mask,
319
+ position_ids=position_ids,
320
+ past_key_values=past_key_values,
321
+ use_cache=use_cache,
322
+ position_embeddings=position_embeddings,
323
+ **kwargs,
324
+ )
325
+ hidden_states = self.post_attention_layernorm(hidden_states)
326
+ hidden_states = residual + hidden_states
327
+
328
+ # Fully Connected
329
+ residual = hidden_states
330
+ hidden_states = self.mlp(hidden_states)
331
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
332
+ hidden_states = residual + hidden_states
333
+ return hidden_states
334
+
335
+
336
+ @auto_docstring
337
+ class Olmo2PreTrainedModel(PreTrainedModel):
338
+ config: Olmo2Config
339
+ base_model_prefix = "model"
340
+ supports_gradient_checkpointing = True
341
+ _no_split_modules = ["Olmo2DecoderLayer"]
342
+ _skip_keys_device_placement = ["past_key_values"]
343
+ _supports_flash_attn = True
344
+ _supports_sdpa = True
345
+ _supports_flex_attn = True
346
+
347
+ _can_compile_fullgraph = True
348
+ _supports_attention_backend = True
349
+ _can_record_outputs = {
350
+ "hidden_states": Olmo2DecoderLayer,
351
+ "attentions": Olmo2Attention,
352
+ }
353
+
354
+
355
+ @auto_docstring
356
+ class Olmo2Model(Olmo2PreTrainedModel):
357
+ def __init__(self, config: Olmo2Config):
358
+ super().__init__(config)
359
+ self.padding_idx = config.pad_token_id
360
+ self.vocab_size = config.vocab_size
361
+
362
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
363
+ self.layers = nn.ModuleList(
364
+ [Olmo2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
365
+ )
366
+ self.norm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
367
+ self.rotary_emb = Olmo2RotaryEmbedding(config=config)
368
+ self.gradient_checkpointing = False
369
+
370
+ # Initialize weights and apply final processing
371
+ self.post_init()
372
+
373
+ @merge_with_config_defaults
374
+ @capture_outputs
375
+ @auto_docstring
376
+ def forward(
377
+ self,
378
+ input_ids: torch.LongTensor | None = None,
379
+ attention_mask: torch.Tensor | None = None,
380
+ position_ids: torch.LongTensor | None = None,
381
+ past_key_values: Cache | None = None,
382
+ inputs_embeds: torch.FloatTensor | None = None,
383
+ use_cache: bool | None = None,
384
+ **kwargs: Unpack[TransformersKwargs],
385
+ ) -> BaseModelOutputWithPast:
386
+ if (input_ids is None) ^ (inputs_embeds is not None):
387
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
388
+
389
+ if inputs_embeds is None:
390
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
391
+
392
+ if use_cache and past_key_values is None:
393
+ past_key_values = DynamicCache(config=self.config)
394
+
395
+ if position_ids is None:
396
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
397
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
398
+ position_ids = position_ids.unsqueeze(0)
399
+
400
+ causal_mask = create_causal_mask(
401
+ config=self.config,
402
+ inputs_embeds=inputs_embeds,
403
+ attention_mask=attention_mask,
404
+ past_key_values=past_key_values,
405
+ position_ids=position_ids,
406
+ )
407
+
408
+ hidden_states = inputs_embeds
409
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
410
+
411
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
412
+ hidden_states = decoder_layer(
413
+ hidden_states,
414
+ attention_mask=causal_mask,
415
+ position_embeddings=position_embeddings,
416
+ position_ids=position_ids,
417
+ past_key_values=past_key_values,
418
+ use_cache=use_cache,
419
+ **kwargs,
420
+ )
421
+
422
+ hidden_states = self.norm(hidden_states)
423
+ return BaseModelOutputWithPast(
424
+ last_hidden_state=hidden_states,
425
+ past_key_values=past_key_values,
426
+ )
427
+
428
+
429
+ @auto_docstring
430
+ class Olmo2ForCausalLM(Olmo2PreTrainedModel, GenerationMixin):
431
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
432
+ _tp_plan = {"lm_head": "colwise_gather_output"}
433
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
434
+
435
+ def __init__(self, config):
436
+ super().__init__(config)
437
+ self.model = Olmo2Model(config)
438
+ self.vocab_size = config.vocab_size
439
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
440
+
441
+ # Initialize weights and apply final processing
442
+ self.post_init()
443
+
444
+ @can_return_tuple
445
+ @auto_docstring
446
+ def forward(
447
+ self,
448
+ input_ids: torch.LongTensor | None = None,
449
+ attention_mask: torch.Tensor | None = None,
450
+ position_ids: torch.LongTensor | None = None,
451
+ past_key_values: Cache | None = None,
452
+ inputs_embeds: torch.FloatTensor | None = None,
453
+ labels: torch.LongTensor | None = None,
454
+ use_cache: bool | None = None,
455
+ logits_to_keep: int | torch.Tensor = 0,
456
+ **kwargs: Unpack[TransformersKwargs],
457
+ ) -> CausalLMOutputWithPast:
458
+ r"""
459
+ Example:
460
+
461
+ ```python
462
+ >>> from transformers import AutoTokenizer, Olmo2ForCausalLM
463
+
464
+ >>> model = Olmo2ForCausalLM.from_pretrained("meta-olmo2/Olmo2-2-7b-hf")
465
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-olmo2/Olmo2-2-7b-hf")
466
+
467
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
468
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
469
+
470
+ >>> # Generate
471
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
472
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
473
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
474
+ ```"""
475
+ outputs: BaseModelOutputWithPast = self.model(
476
+ input_ids=input_ids,
477
+ attention_mask=attention_mask,
478
+ position_ids=position_ids,
479
+ past_key_values=past_key_values,
480
+ inputs_embeds=inputs_embeds,
481
+ use_cache=use_cache,
482
+ **kwargs,
483
+ )
484
+
485
+ hidden_states = outputs.last_hidden_state
486
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
487
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
488
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
489
+
490
+ loss = None
491
+ if labels is not None:
492
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
493
+
494
+ return CausalLMOutputWithPast(
495
+ loss=loss,
496
+ logits=logits,
497
+ past_key_values=outputs.past_key_values,
498
+ hidden_states=outputs.hidden_states,
499
+ attentions=outputs.attentions,
500
+ )
501
+
502
+
503
+ class Olmo2ForSequenceClassification(GenericForSequenceClassification, Olmo2PreTrainedModel):
504
+ pass
505
+
506
+
507
+ __all__ = ["Olmo2ForCausalLM", "Olmo2ForSequenceClassification", "Olmo2Model", "Olmo2PreTrainedModel"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/olmo2/modular_olmo2.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
4
+ # and OPT implementations in this library. It has been modified from its
5
+ # original forms to accommodate minor architectural differences compared
6
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+
20
+ from collections.abc import Callable
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+ from huggingface_hub.dataclasses import strict
25
+
26
+ from transformers.utils.generic import TransformersKwargs
27
+
28
+ from ...cache_utils import Cache
29
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
30
+ from ...processing_utils import Unpack
31
+ from ...utils import auto_docstring, logging
32
+ from ..llama.modeling_llama import LlamaPreTrainedModel, LlamaRMSNorm, eager_attention_forward
33
+ from ..olmo.configuration_olmo import OlmoConfig
34
+ from ..olmo.modeling_olmo import (
35
+ OlmoAttention,
36
+ OlmoDecoderLayer,
37
+ OlmoForCausalLM,
38
+ OlmoForSequenceClassification,
39
+ OlmoModel,
40
+ OlmoRotaryEmbedding,
41
+ apply_rotary_pos_emb,
42
+ )
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+
48
+ @auto_docstring(checkpoint="allenai/Olmo2-7B-1124-hf")
49
+ @strict
50
+ class Olmo2Config(OlmoConfig):
51
+ r"""
52
+ Example:
53
+
54
+ ```python
55
+ >>> from transformers import Olmo2Model, Olmo2Config
56
+
57
+ >>> # Initializing a Olmo2 7B style configuration
58
+ >>> configuration = Olmo2Config()
59
+
60
+ >>> # Initializing a model from the Olmo2 7B style configuration
61
+ >>> model = Olmo2Model(configuration)
62
+
63
+ >>> # Accessing the model configuration
64
+ >>> configuration = model.config
65
+ ```
66
+ """
67
+
68
+ model_type = "olmo2"
69
+ base_model_tp_plan = {
70
+ "layers.*.self_attn.q_proj": "colwise_gather_output", # we need to replicate here due to the added norm on q and k
71
+ "layers.*.self_attn.k_proj": "colwise_gather_output", # we need to replicate here due to the added norm on q and k
72
+ "layers.*.self_attn.v_proj": "colwise_gather_output", # we need to replicate here due to the added norm on q and k
73
+ "layers.*.self_attn.o_proj": "rowwise_split_input", # input is replicated due to the added norm on q and k
74
+ "layers.*.mlp.gate_proj": "colwise",
75
+ "layers.*.mlp.up_proj": "colwise",
76
+ "layers.*.mlp.down_proj": "rowwise",
77
+ }
78
+ base_model_pp_plan = {
79
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
80
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
81
+ "norm": (["hidden_states"], ["hidden_states"]),
82
+ }
83
+
84
+ rms_norm_eps: float = 1e-5
85
+ clip_qkv = AttributeError()
86
+
87
+
88
+ # OLMo2 RMS norm is identical to Llama RMS norm except:
89
+ # - Weight and hidden states are multiplied before converting back to the input dtype, rather than after.
90
+ class Olmo2RMSNorm(LlamaRMSNorm):
91
+ def forward(self, hidden_states):
92
+ input_dtype = hidden_states.dtype
93
+ hidden_states = hidden_states.to(torch.float32)
94
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
95
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
96
+ return (self.weight * hidden_states).to(input_dtype)
97
+
98
+
99
+ class Olmo2RotaryEmbedding(OlmoRotaryEmbedding):
100
+ pass
101
+
102
+
103
+ def rotate_half(x):
104
+ """Rotates half the hidden dims of the input."""
105
+ x1 = x[..., : x.shape[-1] // 2]
106
+ x2 = x[..., x.shape[-1] // 2 :]
107
+ return torch.cat((-x2, x1), dim=-1)
108
+
109
+
110
+ # Olmo2 attention is identical to OLMo attention except:
111
+ # - Norm is applied to attention queries and keys.
112
+ # - No qkv clipping.
113
+ class Olmo2Attention(OlmoAttention):
114
+ def __init__(self, config: Olmo2Config, layer_idx: int | None = None):
115
+ super().__init__(config, layer_idx=layer_idx)
116
+ self.q_norm = Olmo2RMSNorm(config.num_attention_heads * self.head_dim, config.rms_norm_eps)
117
+ self.k_norm = Olmo2RMSNorm(config.num_key_value_heads * self.head_dim, config.rms_norm_eps)
118
+
119
+ def forward(
120
+ self,
121
+ hidden_states: torch.Tensor,
122
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
123
+ attention_mask: torch.Tensor | None,
124
+ past_key_values: Cache | None = None,
125
+ **kwargs: Unpack[TransformersKwargs],
126
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
127
+ input_shape = hidden_states.shape[:-1]
128
+ hidden_shape = (*input_shape, -1, self.head_dim)
129
+
130
+ query_states = self.q_norm(self.q_proj(hidden_states))
131
+ key_states = self.k_norm(self.k_proj(hidden_states))
132
+ value_states = self.v_proj(hidden_states)
133
+
134
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
135
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
136
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
137
+
138
+ cos, sin = position_embeddings
139
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
140
+
141
+ if past_key_values is not None:
142
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
143
+
144
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
145
+ self.config._attn_implementation, eager_attention_forward
146
+ )
147
+
148
+ attn_output, attn_weights = attention_interface(
149
+ self,
150
+ query_states,
151
+ key_states,
152
+ value_states,
153
+ attention_mask,
154
+ dropout=0.0 if not self.training else self.attention_dropout,
155
+ scaling=self.scaling,
156
+ **kwargs,
157
+ )
158
+
159
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
160
+ attn_output = self.o_proj(attn_output)
161
+ return attn_output, attn_weights
162
+
163
+
164
+ # The OLMo2 layers are identical to those of the OLMo model except:
165
+ # - RMSNorm is used instead of standard layer norm.
166
+ # - Norm is applied after attention/feedforward rather than before.
167
+ class Olmo2DecoderLayer(OlmoDecoderLayer):
168
+ def __init__(self, config: Olmo2Config, layer_idx: int):
169
+ super().__init__(config, layer_idx=layer_idx)
170
+ self.post_attention_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
171
+ self.post_feedforward_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
172
+ self.self_attn = Olmo2Attention(config=config, layer_idx=layer_idx)
173
+ del self.input_layernorm
174
+
175
+ def forward(
176
+ self,
177
+ hidden_states: torch.Tensor,
178
+ attention_mask: torch.Tensor | None = None,
179
+ position_ids: torch.LongTensor | None = None,
180
+ past_key_values: Cache | None = None,
181
+ use_cache: bool | None = False,
182
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
183
+ **kwargs: Unpack[TransformersKwargs],
184
+ ) -> torch.Tensor:
185
+ residual = hidden_states
186
+ hidden_states, _ = self.self_attn(
187
+ hidden_states=hidden_states,
188
+ attention_mask=attention_mask,
189
+ position_ids=position_ids,
190
+ past_key_values=past_key_values,
191
+ use_cache=use_cache,
192
+ position_embeddings=position_embeddings,
193
+ **kwargs,
194
+ )
195
+ hidden_states = self.post_attention_layernorm(hidden_states)
196
+ hidden_states = residual + hidden_states
197
+
198
+ # Fully Connected
199
+ residual = hidden_states
200
+ hidden_states = self.mlp(hidden_states)
201
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
202
+ hidden_states = residual + hidden_states
203
+ return hidden_states
204
+
205
+
206
+ class Olmo2PreTrainedModel(LlamaPreTrainedModel):
207
+ pass
208
+
209
+
210
+ # The OLMo2 model is identical to the OLMo model, except RMSNorm is used instead of
211
+ # standard layer norm for the output norm.
212
+ class Olmo2Model(OlmoModel):
213
+ def __init__(self, config: Olmo2Config):
214
+ super().__init__(config)
215
+ self.norm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
216
+ self.layers = nn.ModuleList(
217
+ [Olmo2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
218
+ )
219
+
220
+
221
+ # The heads now only need to redefine the model inside to the correct `RobertaModel`
222
+ class Olmo2ForCausalLM(OlmoForCausalLM):
223
+ pass
224
+
225
+
226
+ class Olmo2ForSequenceClassification(OlmoForSequenceClassification):
227
+ pass
228
+
229
+
230
+ __all__ = [
231
+ "Olmo2Config",
232
+ "Olmo2ForCausalLM",
233
+ "Olmo2ForSequenceClassification",
234
+ "Olmo2Model",
235
+ "Olmo2PreTrainedModel",
236
+ ]