KoichiYasuoka commited on
Commit
8379940
·
1 Parent(s): 853441b

initial release

Browse files
README.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - "ja"
4
+ tags:
5
+ - "japanese"
6
+ - "pos"
7
+ - "dependency-parsing"
8
+ - "modernbert"
9
+ base_model: KoichiYasuoka/modernbert-base-japanese-aozora
10
+ datasets:
11
+ - "universal_dependencies"
12
+ license: "apache-2.0"
13
+ pipeline_tag: "token-classification"
14
+ widget:
15
+ - text: "全学年にわたって小学校の国語の教科書に挿し絵が用いられている"
16
+ ---
17
+
18
+ # modernbert-base-japanese-aozora-ud-goeswith
19
+
20
+ ## Model Description
21
+
22
+ This is a ModernBERT model pretrained for POS-tagging and dependency-parsing (using `goeswith` for subwords), derived from [modernbert-base-japanese-aozora](https://huggingface.co/KoichiYasuoka/modernbert-base-japanese-aozora) and [UD_Japanese-GSDLUW](https://github.com/UniversalDependencies/UD_Japanese-GSDLUW).
23
+
24
+ ## How to Use
25
+
26
+ ```py
27
+ from transformers import pipeline
28
+ nlp=pipeline("universal-dependencies","KoichiYasuoka/modernbert-base-japanese-aozora-ud-goeswith",trust_remote_code=True,aggregation_strategy="simple")
29
+ print(nlp("全学年にわたって小学校の国語の教科書に挿し絵が用いられている"))
30
+ ```
31
+
config.json ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ModernBertForTokenClassification"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_modernbert.ModernBertConfig",
9
+ "AutoModel": "modeling_modernbert.ModernBertModel",
10
+ "AutoModelForMaskedLM": "modeling_modernbert.ModernBertForMaskedLM",
11
+ "AutoModelForSequenceClassification": "modeling_modernbert.ModernBertForSequenceClassification",
12
+ "AutoModelForTokenClassification": "modeling_modernbert.ModernBertForTokenClassification"
13
+ },
14
+ "bos_token_id": 0,
15
+ "classifier_activation": "gelu",
16
+ "classifier_bias": false,
17
+ "classifier_dropout": 0.0,
18
+ "classifier_pooling": "mean",
19
+ "cls_token_id": 0,
20
+ "custom_pipelines": {
21
+ "universal-dependencies": {
22
+ "impl": "ud.UniversalDependenciesPipeline",
23
+ "pt": "AutoModelForTokenClassification"
24
+ }
25
+ },
26
+ "decoder_bias": true,
27
+ "deterministic_flash_attn": false,
28
+ "embedding_dropout": 0.0,
29
+ "eos_token_id": 2,
30
+ "global_attn_every_n_layers": 3,
31
+ "global_rope_theta": 160000.0,
32
+ "gradient_checkpointing": false,
33
+ "hidden_activation": "gelu",
34
+ "hidden_size": 768,
35
+ "id2label": {
36
+ "0": "-|_|dep",
37
+ "1": "ADJ|_|acl",
38
+ "2": "ADJ|_|advcl",
39
+ "3": "ADJ|_|amod",
40
+ "4": "ADJ|_|ccomp",
41
+ "5": "ADJ|_|csubj",
42
+ "6": "ADJ|_|csubj:outer",
43
+ "7": "ADJ|_|dep",
44
+ "8": "ADJ|_|nmod",
45
+ "9": "ADJ|_|nsubj",
46
+ "10": "ADJ|_|obj",
47
+ "11": "ADJ|_|obl",
48
+ "12": "ADJ|_|root",
49
+ "13": "ADP|_|case",
50
+ "14": "ADP|_|fixed",
51
+ "15": "ADV|_|advcl",
52
+ "16": "ADV|_|advmod",
53
+ "17": "ADV|_|dep",
54
+ "18": "ADV|_|obj",
55
+ "19": "ADV|_|root",
56
+ "20": "AUX|Polarity=Neg|aux",
57
+ "21": "AUX|Polarity=Neg|fixed",
58
+ "22": "AUX|_|aux",
59
+ "23": "AUX|_|cop",
60
+ "24": "AUX|_|fixed",
61
+ "25": "AUX|_|root",
62
+ "26": "CCONJ|_|cc",
63
+ "27": "DET|_|det",
64
+ "28": "INTJ|_|discourse",
65
+ "29": "INTJ|_|root",
66
+ "30": "NOUN|Polarity=Neg|obl",
67
+ "31": "NOUN|Polarity=Neg|root",
68
+ "32": "NOUN|_|acl",
69
+ "33": "NOUN|_|advcl",
70
+ "34": "NOUN|_|ccomp",
71
+ "35": "NOUN|_|compound",
72
+ "36": "NOUN|_|csubj",
73
+ "37": "NOUN|_|csubj:outer",
74
+ "38": "NOUN|_|nmod",
75
+ "39": "NOUN|_|nsubj",
76
+ "40": "NOUN|_|nsubj:outer",
77
+ "41": "NOUN|_|obj",
78
+ "42": "NOUN|_|obl",
79
+ "43": "NOUN|_|root",
80
+ "44": "NUM|_|advcl",
81
+ "45": "NUM|_|compound",
82
+ "46": "NUM|_|nmod",
83
+ "47": "NUM|_|nsubj",
84
+ "48": "NUM|_|nsubj:outer",
85
+ "49": "NUM|_|nummod",
86
+ "50": "NUM|_|obj",
87
+ "51": "NUM|_|obl",
88
+ "52": "NUM|_|root",
89
+ "53": "PART|_|mark",
90
+ "54": "PRON|_|acl",
91
+ "55": "PRON|_|advcl",
92
+ "56": "PRON|_|nmod",
93
+ "57": "PRON|_|nsubj",
94
+ "58": "PRON|_|nsubj:outer",
95
+ "59": "PRON|_|obj",
96
+ "60": "PRON|_|obl",
97
+ "61": "PRON|_|root",
98
+ "62": "PROPN|_|acl",
99
+ "63": "PROPN|_|advcl",
100
+ "64": "PROPN|_|compound",
101
+ "65": "PROPN|_|nmod",
102
+ "66": "PROPN|_|nsubj",
103
+ "67": "PROPN|_|nsubj:outer",
104
+ "68": "PROPN|_|obj",
105
+ "69": "PROPN|_|obl",
106
+ "70": "PROPN|_|root",
107
+ "71": "PUNCT|_|punct",
108
+ "72": "SCONJ|_|dep",
109
+ "73": "SCONJ|_|fixed",
110
+ "74": "SCONJ|_|mark",
111
+ "75": "SYM|_|compound",
112
+ "76": "SYM|_|dep",
113
+ "77": "SYM|_|nmod",
114
+ "78": "SYM|_|obl",
115
+ "79": "VERB|_|acl",
116
+ "80": "VERB|_|advcl",
117
+ "81": "VERB|_|ccomp",
118
+ "82": "VERB|_|compound",
119
+ "83": "VERB|_|csubj",
120
+ "84": "VERB|_|csubj:outer",
121
+ "85": "VERB|_|nmod",
122
+ "86": "VERB|_|obj",
123
+ "87": "VERB|_|obl",
124
+ "88": "VERB|_|root",
125
+ "89": "X|_|dep",
126
+ "90": "X|_|goeswith",
127
+ "91": "X|_|nmod"
128
+ },
129
+ "initializer_cutoff_factor": 2.0,
130
+ "initializer_range": 0.02,
131
+ "intermediate_size": 1152,
132
+ "label2id": {
133
+ "-|_|dep": 0,
134
+ "ADJ|_|acl": 1,
135
+ "ADJ|_|advcl": 2,
136
+ "ADJ|_|amod": 3,
137
+ "ADJ|_|ccomp": 4,
138
+ "ADJ|_|csubj": 5,
139
+ "ADJ|_|csubj:outer": 6,
140
+ "ADJ|_|dep": 7,
141
+ "ADJ|_|nmod": 8,
142
+ "ADJ|_|nsubj": 9,
143
+ "ADJ|_|obj": 10,
144
+ "ADJ|_|obl": 11,
145
+ "ADJ|_|root": 12,
146
+ "ADP|_|case": 13,
147
+ "ADP|_|fixed": 14,
148
+ "ADV|_|advcl": 15,
149
+ "ADV|_|advmod": 16,
150
+ "ADV|_|dep": 17,
151
+ "ADV|_|obj": 18,
152
+ "ADV|_|root": 19,
153
+ "AUX|Polarity=Neg|aux": 20,
154
+ "AUX|Polarity=Neg|fixed": 21,
155
+ "AUX|_|aux": 22,
156
+ "AUX|_|cop": 23,
157
+ "AUX|_|fixed": 24,
158
+ "AUX|_|root": 25,
159
+ "CCONJ|_|cc": 26,
160
+ "DET|_|det": 27,
161
+ "INTJ|_|discourse": 28,
162
+ "INTJ|_|root": 29,
163
+ "NOUN|Polarity=Neg|obl": 30,
164
+ "NOUN|Polarity=Neg|root": 31,
165
+ "NOUN|_|acl": 32,
166
+ "NOUN|_|advcl": 33,
167
+ "NOUN|_|ccomp": 34,
168
+ "NOUN|_|compound": 35,
169
+ "NOUN|_|csubj": 36,
170
+ "NOUN|_|csubj:outer": 37,
171
+ "NOUN|_|nmod": 38,
172
+ "NOUN|_|nsubj": 39,
173
+ "NOUN|_|nsubj:outer": 40,
174
+ "NOUN|_|obj": 41,
175
+ "NOUN|_|obl": 42,
176
+ "NOUN|_|root": 43,
177
+ "NUM|_|advcl": 44,
178
+ "NUM|_|compound": 45,
179
+ "NUM|_|nmod": 46,
180
+ "NUM|_|nsubj": 47,
181
+ "NUM|_|nsubj:outer": 48,
182
+ "NUM|_|nummod": 49,
183
+ "NUM|_|obj": 50,
184
+ "NUM|_|obl": 51,
185
+ "NUM|_|root": 52,
186
+ "PART|_|mark": 53,
187
+ "PRON|_|acl": 54,
188
+ "PRON|_|advcl": 55,
189
+ "PRON|_|nmod": 56,
190
+ "PRON|_|nsubj": 57,
191
+ "PRON|_|nsubj:outer": 58,
192
+ "PRON|_|obj": 59,
193
+ "PRON|_|obl": 60,
194
+ "PRON|_|root": 61,
195
+ "PROPN|_|acl": 62,
196
+ "PROPN|_|advcl": 63,
197
+ "PROPN|_|compound": 64,
198
+ "PROPN|_|nmod": 65,
199
+ "PROPN|_|nsubj": 66,
200
+ "PROPN|_|nsubj:outer": 67,
201
+ "PROPN|_|obj": 68,
202
+ "PROPN|_|obl": 69,
203
+ "PROPN|_|root": 70,
204
+ "PUNCT|_|punct": 71,
205
+ "SCONJ|_|dep": 72,
206
+ "SCONJ|_|fixed": 73,
207
+ "SCONJ|_|mark": 74,
208
+ "SYM|_|compound": 75,
209
+ "SYM|_|dep": 76,
210
+ "SYM|_|nmod": 77,
211
+ "SYM|_|obl": 78,
212
+ "VERB|_|acl": 79,
213
+ "VERB|_|advcl": 80,
214
+ "VERB|_|ccomp": 81,
215
+ "VERB|_|compound": 82,
216
+ "VERB|_|csubj": 83,
217
+ "VERB|_|csubj:outer": 84,
218
+ "VERB|_|nmod": 85,
219
+ "VERB|_|obj": 86,
220
+ "VERB|_|obl": 87,
221
+ "VERB|_|root": 88,
222
+ "X|_|dep": 89,
223
+ "X|_|goeswith": 90,
224
+ "X|_|nmod": 91
225
+ },
226
+ "layer_norm_eps": 1e-05,
227
+ "local_attention": 128,
228
+ "local_rope_theta": 10000.0,
229
+ "max_position_embeddings": 8192,
230
+ "mlp_bias": false,
231
+ "mlp_dropout": 0.0,
232
+ "model_type": "modernbert",
233
+ "norm_bias": false,
234
+ "norm_eps": 1e-05,
235
+ "num_attention_heads": 12,
236
+ "num_hidden_layers": 22,
237
+ "pad_token_id": 1,
238
+ "position_embedding_type": "absolute",
239
+ "reference_compile": true,
240
+ "sep_token_id": 2,
241
+ "sparse_pred_ignore_index": -100,
242
+ "sparse_prediction": false,
243
+ "tokenizer_class": "DebertaV2TokenizerFast",
244
+ "torch_dtype": "float32",
245
+ "transformers_version": "4.47.1",
246
+ "vocab_size": 65000
247
+ }
configuration_modernbert.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/modernbert/modular_modernbert.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_modernbert.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 Answer.AI, LightOn, and contributors, and the HuggingFace Inc. team. All rights reserved.
8
+ #
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
+ from typing import Literal
23
+
24
+ from transformers.configuration_utils import PretrainedConfig
25
+
26
+
27
+ class ModernBertConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`ModernBertModel`]. It is used to instantiate an ModernBert
30
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
31
+ defaults will yield a similar configuration to that of the ModernBERT-base.
32
+ e.g. [answerdotai/ModernBERT-base](https://huggingface.co/answerdotai/ModernBERT-base)
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 50368):
39
+ Vocabulary size of the ModernBert model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`ModernBertModel`]
41
+ hidden_size (`int`, *optional*, defaults to 768):
42
+ Dimension of the hidden representations.
43
+ intermediate_size (`int`, *optional*, defaults to 1152):
44
+ Dimension of the MLP representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 22):
46
+ Number of hidden layers in the Transformer decoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 12):
48
+ Number of attention heads for each attention layer in the Transformer decoder.
49
+ hidden_activation (`str` or `function`, *optional*, defaults to `"gelu"`):
50
+ The non-linear activation function (function or string) in the decoder. Will default to `"gelu"`
51
+ if not specified.
52
+ max_position_embeddings (`int`, *optional*, defaults to 8192):
53
+ The maximum sequence length that this model might ever be used with.
54
+ initializer_range (`float`, *optional*, defaults to 0.02):
55
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
56
+ initializer_cutoff_factor (`float`, *optional*, defaults to 2.0):
57
+ The cutoff factor for the truncated_normal_initializer for initializing all weight matrices.
58
+ norm_eps (`float`, *optional*, defaults to 1e-05):
59
+ The epsilon used by the rms normalization layers.
60
+ norm_bias (`bool`, *optional*, defaults to `False`):
61
+ Whether to use bias in the normalization layers.
62
+ pad_token_id (`int`, *optional*, defaults to 50283):
63
+ Padding token id.
64
+ eos_token_id (`int`, *optional*, defaults to 50282):
65
+ End of stream token id.
66
+ bos_token_id (`int`, *optional*, defaults to 50281):
67
+ Beginning of stream token id.
68
+ cls_token_id (`int`, *optional*, defaults to 50281):
69
+ Classification token id.
70
+ sep_token_id (`int`, *optional*, defaults to 50282):
71
+ Separation token id.
72
+ global_rope_theta (`float`, *optional*, defaults to 160000.0):
73
+ The base period of the global RoPE embeddings.
74
+ attention_bias (`bool`, *optional*, defaults to `False`):
75
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
76
+ attention_dropout (`float`, *optional*, defaults to 0.0):
77
+ The dropout ratio for the attention probabilities.
78
+ global_attn_every_n_layers (`int`, *optional*, defaults to 3):
79
+ The number of layers between global attention layers.
80
+ local_attention (`int`, *optional*, defaults to 128):
81
+ The window size for local attention.
82
+ local_rope_theta (`float`, *optional*, defaults to 10000.0):
83
+ The base period of the local RoPE embeddings.
84
+ embedding_dropout (`float`, *optional*, defaults to 0.0):
85
+ The dropout ratio for the embeddings.
86
+ mlp_bias (`bool`, *optional*, defaults to `False`):
87
+ Whether to use bias in the MLP layers.
88
+ mlp_dropout (`float`, *optional*, defaults to 0.0):
89
+ The dropout ratio for the MLP layers.
90
+ decoder_bias (`bool`, *optional*, defaults to `True`):
91
+ Whether to use bias in the decoder layers.
92
+ classifier_pooling (`str`, *optional*, defaults to `"cls"`):
93
+ The pooling method for the classifier. Should be either `"cls"` or `"mean"`. In local attention layers, the
94
+ CLS token doesn't attend to all tokens on long sequences.
95
+ classifier_dropout (`float`, *optional*, defaults to 0.0):
96
+ The dropout ratio for the classifier.
97
+ classifier_bias (`bool`, *optional*, defaults to `False`):
98
+ Whether to use bias in the classifier.
99
+ classifier_activation (`str`, *optional*, defaults to `"gelu"`):
100
+ The activation function for the classifier.
101
+ deterministic_flash_attn (`bool`, *optional*, defaults to `False`):
102
+ Whether to use deterministic flash attention. If `False`, inference will be faster but not deterministic.
103
+ sparse_prediction (`bool`, *optional*, defaults to `False`):
104
+ Whether to use sparse prediction for the masked language model instead of returning the full dense logits.
105
+ sparse_pred_ignore_index (`int`, *optional*, defaults to -100):
106
+ The index to ignore for the sparse prediction.
107
+ reference_compile (`bool`, *optional*):
108
+ Whether to compile the layers of the model which were compiled during pretraining. If `None`, then parts of
109
+ the model will be compiled if 1) `triton` is installed, 2) the model is not on MPS, 3) the model is not
110
+ shared between devices, and 4) the model is not resized after initialization. If `True`, then the model may
111
+ be faster in some scenarios.
112
+
113
+ Examples:
114
+
115
+ ```python
116
+ >>> from transformers import ModernBertModel, ModernBertConfig
117
+
118
+ >>> # Initializing a ModernBert style configuration
119
+ >>> configuration = ModernBertConfig()
120
+
121
+ >>> # Initializing a model from the modernbert-base style configuration
122
+ >>> model = ModernBertModel(configuration)
123
+
124
+ >>> # Accessing the model configuration
125
+ >>> configuration = model.config
126
+ ```"""
127
+
128
+ model_type = "modernbert"
129
+ keys_to_ignore_at_inference = ["past_key_values"]
130
+
131
+ def __init__(
132
+ self,
133
+ vocab_size=50368,
134
+ hidden_size=768,
135
+ intermediate_size=1152,
136
+ num_hidden_layers=22,
137
+ num_attention_heads=12,
138
+ hidden_activation="gelu",
139
+ max_position_embeddings=8192,
140
+ initializer_range=0.02,
141
+ initializer_cutoff_factor=2.0,
142
+ norm_eps=1e-5,
143
+ norm_bias=False,
144
+ pad_token_id=50283,
145
+ eos_token_id=50282,
146
+ bos_token_id=50281,
147
+ cls_token_id=50281,
148
+ sep_token_id=50282,
149
+ global_rope_theta=160000.0,
150
+ attention_bias=False,
151
+ attention_dropout=0.0,
152
+ global_attn_every_n_layers=3,
153
+ local_attention=128,
154
+ local_rope_theta=10000.0,
155
+ embedding_dropout=0.0,
156
+ mlp_bias=False,
157
+ mlp_dropout=0.0,
158
+ decoder_bias=True,
159
+ classifier_pooling: Literal["cls", "mean"] = "cls",
160
+ classifier_dropout=0.0,
161
+ classifier_bias=False,
162
+ classifier_activation="gelu",
163
+ deterministic_flash_attn=False,
164
+ sparse_prediction=False,
165
+ sparse_pred_ignore_index=-100,
166
+ reference_compile=None,
167
+ **kwargs,
168
+ ):
169
+ super().__init__(
170
+ pad_token_id=pad_token_id,
171
+ bos_token_id=bos_token_id,
172
+ eos_token_id=eos_token_id,
173
+ cls_token_id=cls_token_id,
174
+ sep_token_id=sep_token_id,
175
+ **kwargs,
176
+ )
177
+ self.vocab_size = vocab_size
178
+ self.max_position_embeddings = max_position_embeddings
179
+ self.hidden_size = hidden_size
180
+ self.intermediate_size = intermediate_size
181
+ self.num_hidden_layers = num_hidden_layers
182
+ self.num_attention_heads = num_attention_heads
183
+ self.initializer_range = initializer_range
184
+ self.initializer_cutoff_factor = initializer_cutoff_factor
185
+ self.norm_eps = norm_eps
186
+ self.norm_bias = norm_bias
187
+ self.global_rope_theta = global_rope_theta
188
+ self.attention_bias = attention_bias
189
+ self.attention_dropout = attention_dropout
190
+ self.hidden_activation = hidden_activation
191
+ self.global_attn_every_n_layers = global_attn_every_n_layers
192
+ self.local_attention = local_attention
193
+ self.local_rope_theta = local_rope_theta
194
+ self.embedding_dropout = embedding_dropout
195
+ self.mlp_bias = mlp_bias
196
+ self.mlp_dropout = mlp_dropout
197
+ self.decoder_bias = decoder_bias
198
+ self.classifier_pooling = classifier_pooling
199
+ self.classifier_dropout = classifier_dropout
200
+ self.classifier_bias = classifier_bias
201
+ self.classifier_activation = classifier_activation
202
+ self.deterministic_flash_attn = deterministic_flash_attn
203
+ self.sparse_prediction = sparse_prediction
204
+ self.sparse_pred_ignore_index = sparse_pred_ignore_index
205
+ self.reference_compile = reference_compile
206
+
207
+ if self.classifier_pooling not in ["cls", "mean"]:
208
+ raise ValueError(
209
+ f'Invalid value for `classifier_pooling`, should be either "cls" or "mean", but is {self.classifier_pooling}.'
210
+ )
211
+
212
+
213
+ __all__ = ["ModernBertConfig"]
maker.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/python3
2
+ src="KoichiYasuoka/modernbert-base-japanese-aozora"
3
+ tgt="KoichiYasuoka/modernbert-base-japanese-aozora-ud-goeswith"
4
+ url="https://github.com/UniversalDependencies/UD_Japanese-GSDLUW"
5
+ import os
6
+ d=os.path.basename(url)
7
+ os.system("test -d "+d+" || git clone --depth=1 "+url)
8
+ os.system("for F in train dev test ; do cp "+d+"/*-$F.conllu $F.conllu ; done")
9
+ class UDgoeswithDataset(object):
10
+ def __init__(self,conllu,tokenizer):
11
+ self.ids,self.tags,label=[],[],set()
12
+ with open(conllu,"r",encoding="utf-8") as r:
13
+ cls,sep,msk=tokenizer.cls_token_id,tokenizer.sep_token_id,tokenizer.mask_token_id
14
+ dep,c="-|_|dep",[]
15
+ for s in r:
16
+ t=s.split("\t")
17
+ if len(t)==10 and t[0].isdecimal():
18
+ c.append(t)
19
+ elif c!=[] and s.strip()=="":
20
+ v=tokenizer([t[1] for t in c],add_special_tokens=False)["input_ids"]
21
+ for i in range(len(v)-1,-1,-1):
22
+ for j in range(1,len(v[i])):
23
+ c.insert(i+1,[c[i][0],"_","_","X","_","_",c[i][0],"goeswith","_","_"])
24
+ y=["0"]+[t[0] for t in c]
25
+ h=[i if t[6]=="0" else y.index(t[6]) for i,t in enumerate(c,1)]
26
+ p,v=[t[3]+"|"+t[5]+"|"+t[7] for t in c],sum(v,[])
27
+ self.ids.append([cls]+v+[sep])
28
+ self.tags.append([dep]+p+[dep])
29
+ label=set(sum([self.tags[-1],list(label)],[]))
30
+ for i,k in enumerate(v):
31
+ self.ids.append([cls]+v[0:i]+[msk]+v[i+1:]+[sep,k])
32
+ self.tags.append([dep]+[t if h[j]==i+1 else dep for j,t in enumerate(p)]+[dep,dep])
33
+ c=[]
34
+ self.label2id={l:i for i,l in enumerate(sorted(label))}
35
+ def __call__(*args):
36
+ label=set(sum([list(t.label2id) for t in args],[]))
37
+ lid={l:i for i,l in enumerate(sorted(label))}
38
+ for t in args:
39
+ t.label2id=lid
40
+ return lid
41
+ __len__=lambda self:len(self.ids)
42
+ __getitem__=lambda self,i:{"input_ids":self.ids[i],"labels":[self.label2id[t] for t in self.tags[i]]}
43
+ from transformers import AutoTokenizer,AutoConfig,AutoModelForTokenClassification,DataCollatorForTokenClassification,TrainingArguments,Trainer
44
+ tkz=AutoTokenizer.from_pretrained(src)
45
+ trainDS=UDgoeswithDataset("train.conllu",tkz)
46
+ devDS=UDgoeswithDataset("dev.conllu",tkz)
47
+ testDS=UDgoeswithDataset("test.conllu",tkz)
48
+ lid=trainDS(devDS,testDS)
49
+ cfg=AutoConfig.from_pretrained(src,num_labels=len(lid),label2id=lid,id2label={i:l for l,i in lid.items()},ignore_mismatched_sizes=True,trust_remote_code=True)
50
+ arg=TrainingArguments(num_train_epochs=3,per_device_train_batch_size=64,output_dir="/tmp",overwrite_output_dir=True,save_total_limit=2,learning_rate=5e-05,warmup_ratio=0.1,save_safetensors=False)
51
+ trn=Trainer(args=arg,data_collator=DataCollatorForTokenClassification(tkz),model=AutoModelForTokenClassification.from_pretrained(src,config=cfg,ignore_mismatched_sizes=True,trust_remote_code=True),train_dataset=trainDS,eval_dataset=devDS)
52
+ trn.train()
53
+ trn.save_model(tgt)
54
+ tkz.save_pretrained(tgt)
modeling_modernbert.py ADDED
@@ -0,0 +1,1312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/modernbert/modular_modernbert.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_modernbert.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 Answer.AI, LightOn, and contributors, and the HuggingFace Inc. team. All rights reserved.
8
+ #
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
+ import math
23
+ from typing import Dict, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
32
+ from transformers.modeling_outputs import BaseModelOutput, MaskedLMOutput, SequenceClassifierOutput, TokenClassifierOutput
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.utils import (
35
+ add_code_sample_docstrings,
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ is_flash_attn_2_available,
39
+ logging,
40
+ )
41
+ import importlib
42
+ is_triton_available = lambda: importlib.util.find_spec("triton") is not None
43
+ from .configuration_modernbert import ModernBertConfig
44
+
45
+
46
+ if is_flash_attn_2_available():
47
+ from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func
48
+ from flash_attn.layers.rotary import RotaryEmbedding
49
+ from flash_attn.ops.triton.rotary import apply_rotary
50
+ else:
51
+ RotaryEmbedding = object
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CHECKPOINT_FOR_DOC = "answerdotai/ModernBERT-base"
56
+ _CONFIG_FOR_DOC = "ModernBertConfig"
57
+
58
+
59
+ class ApplyRotaryEmbUnpad(torch.autograd.Function):
60
+ @staticmethod
61
+ def forward(
62
+ ctx,
63
+ qkv,
64
+ cos,
65
+ sin,
66
+ cu_seqlens: Optional[torch.Tensor] = None,
67
+ max_seqlen: Optional[int] = None,
68
+ ):
69
+ # (total_nnz, 3, nheads, headdim)
70
+ qkv = qkv.contiguous()
71
+ total_nnz, _three, _nheads, headdim = qkv.shape
72
+ # We need qkv to be contiguous so that when we reshape to combine (3, nheads) dimensions,
73
+ # we get the same tensor
74
+ # qk = rearrange(qkv[:, :2], "b_s t h d -> b_s (t h) d")
75
+ qk = qkv[:, :2].view(total_nnz, -1, headdim)
76
+ apply_rotary(
77
+ qk,
78
+ cos,
79
+ sin,
80
+ seqlen_offsets=0,
81
+ cu_seqlens=cu_seqlens,
82
+ max_seqlen=max_seqlen,
83
+ interleaved=False,
84
+ inplace=True,
85
+ )
86
+
87
+ ctx.save_for_backward(cos, sin, cu_seqlens)
88
+ ctx.max_seqlen = max_seqlen
89
+ return qkv
90
+
91
+ @staticmethod
92
+ def backward(ctx, do):
93
+ cos, sin, cu_seqlens = ctx.saved_tensors
94
+ do = do.contiguous()
95
+ total_nnz, _three, _nheads, headdim = do.shape
96
+ # We need dqkv to be contiguous so that when we reshape to combine (3, nheads) dimensions,
97
+ # we get the same tensor
98
+ dqk = do[:, :2].view(total_nnz, -1, headdim)
99
+ apply_rotary(
100
+ dqk,
101
+ cos,
102
+ sin,
103
+ seqlen_offsets=0,
104
+ cu_seqlens=cu_seqlens,
105
+ max_seqlen=ctx.max_seqlen,
106
+ interleaved=False,
107
+ inplace=True,
108
+ conjugate=True,
109
+ )
110
+
111
+ return do, None, None, None, None, None, None
112
+
113
+
114
+ def apply_rotary_unpadded(
115
+ qkv,
116
+ cos,
117
+ sin,
118
+ cu_seqlens: Optional[torch.Tensor] = None,
119
+ max_seqlen: Optional[int] = None,
120
+ ):
121
+ """
122
+ Arguments:
123
+ qkv: (total_nnz, 3, nheads, headdim) - input tensor for packed QKV.
124
+ cos, sin: (seqlen_rotary, rotary_dim / 2)
125
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
126
+ of 1st half and 2nd half (GPT-NeoX style).
127
+ inplace: if True, apply rotary embedding in-place.
128
+ seqlen_offsets: (batch_size,) or int. Each sequence in x is shifted by this amount.
129
+ Most commonly used in inference when we have KV cache.
130
+ cu_seqlens: (batch + 1,) or None
131
+ max_seqlen: int
132
+ Return:
133
+ out: (total_nnz, dim)
134
+ rotary_dim must be <= headdim
135
+ Apply rotary embedding to the first rotary_dim of x.
136
+ """
137
+ return ApplyRotaryEmbUnpad.apply(qkv, cos, sin, cu_seqlens, max_seqlen)
138
+
139
+
140
+ class ModernBertUnpaddedRotaryEmbedding(RotaryEmbedding):
141
+ """
142
+ The rotary position embeddings applied directly to unpadded sequences.
143
+ """
144
+
145
+ def __init__(
146
+ self,
147
+ dim: int,
148
+ base: float = 10000.0,
149
+ max_seqlen: Optional[int] = None,
150
+ device: Optional[torch.device] = None,
151
+ dtype: Optional[torch.dtype] = None,
152
+ ):
153
+ """
154
+ max_seqlen: if max_seqlen, device, and dtype are provided, we precompute the cos_sin_cache
155
+ up to max_seqlen. If the max_seqlen, device, or dtype during training/inference differ,
156
+ the cos_sin_cache wll be recomputed during the forward pass.
157
+ """
158
+ super().__init__(dim=dim, base=base, pos_idx_in_fp32=True, device=device, interleaved=False)
159
+ self.max_seqlen = max_seqlen
160
+
161
+ if max_seqlen is not None and device is not None and dtype is not None:
162
+ self._update_cos_sin_cache(max_seqlen, device=device, dtype=dtype)
163
+
164
+ def forward(
165
+ self,
166
+ qkv: torch.Tensor,
167
+ cu_seqlens: torch.Tensor,
168
+ max_seqlen: Optional[int] = None,
169
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
170
+ """
171
+ Apply rotary embedding *inplace* to qkv.
172
+ qkv: (total_nnz, 3, nheads, headdim)
173
+ cu_seqlens: (batch + 1,) cumulative sequence lengths
174
+ max_seqlen: int max seq length in the batch
175
+ """
176
+ if max_seqlen is not None:
177
+ self._update_cos_sin_cache(max_seqlen, device=qkv.device, dtype=qkv.dtype)
178
+
179
+ qkv = apply_rotary_unpadded(
180
+ qkv,
181
+ self._cos_cached,
182
+ self._sin_cached,
183
+ cu_seqlens=cu_seqlens,
184
+ max_seqlen=max_seqlen,
185
+ )
186
+
187
+ return qkv
188
+
189
+ def extra_repr(self) -> str:
190
+ return f"dim={self.dim}, base={self.base}, scale_base={self.scale_base}"
191
+
192
+
193
+ class ModernBertEmbeddings(nn.Module):
194
+ """
195
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
196
+ """
197
+
198
+ def __init__(self, config: ModernBertConfig):
199
+ super().__init__()
200
+ self.config = config
201
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
202
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias)
203
+ self.drop = nn.Dropout(config.embedding_dropout)
204
+
205
+ @torch.compile(dynamic=True)
206
+ def compiled_embeddings(self, input_ids: torch.LongTensor) -> torch.Tensor:
207
+ return self.drop(self.norm(self.tok_embeddings(input_ids)))
208
+
209
+ def forward(self, input_ids: torch.LongTensor, position_ids: Optional[torch.LongTensor] = None) -> torch.Tensor:
210
+ hidden_states = (
211
+ self.compiled_embeddings(input_ids)
212
+ if self.config.reference_compile
213
+ else self.drop(self.norm(self.tok_embeddings(input_ids)))
214
+ )
215
+ return hidden_states
216
+
217
+
218
+ class ModernBertMLP(nn.Module):
219
+ """Applies the GLU at the end of each ModernBERT layer.
220
+
221
+ Compared to the default BERT architecture, this block replaces :class:`~transformers.model.bert.modeling_bert.BertIntermediate`
222
+ and :class:`~transformers.model.bert.modeling_bert.SelfOutput` with a single module that has similar functionality.
223
+ """
224
+
225
+ def __init__(self, config: ModernBertConfig):
226
+ super().__init__()
227
+ self.config = config
228
+ self.Wi = nn.Linear(config.hidden_size, int(config.intermediate_size) * 2, bias=config.mlp_bias)
229
+ self.act = ACT2FN[config.hidden_activation]
230
+ self.drop = nn.Dropout(config.mlp_dropout)
231
+ self.Wo = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.mlp_bias)
232
+
233
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
234
+ input, gate = self.Wi(hidden_states).chunk(2, dim=-1)
235
+ return self.Wo(self.drop(self.act(input) * gate))
236
+
237
+
238
+ class ModernBertRotaryEmbedding(nn.Module):
239
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
240
+ super().__init__()
241
+
242
+ self.dim = dim
243
+ self.max_position_embeddings = max_position_embeddings
244
+ self.base = base
245
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim))
246
+ self.register_buffer("inv_freq", tensor=inv_freq, persistent=False)
247
+
248
+ @torch.no_grad()
249
+ def forward(self, x, position_ids, seq_len=None):
250
+ # x: [bs, num_attention_heads, seq_len, head_size]
251
+ self.inv_freq.to(x.device)
252
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
253
+ position_ids_expanded = position_ids[:, None, :].float()
254
+ # Force float32 since bfloat16 loses precision on long contexts
255
+ # See https://github.com/huggingface/transformers/pull/29285
256
+ device_type = x.device.type
257
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
258
+ with torch.autocast(device_type=device_type, enabled=False):
259
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
260
+ emb = torch.cat((freqs, freqs), dim=-1)
261
+ cos = emb.cos()
262
+ sin = emb.sin()
263
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
264
+
265
+
266
+ def rotate_half(x):
267
+ """Rotates half the hidden dims of the input."""
268
+ x1 = x[..., : x.shape[-1] // 2]
269
+ x2 = x[..., x.shape[-1] // 2 :]
270
+ return torch.cat((-x2, x1), dim=-1)
271
+
272
+
273
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
274
+ """Applies Rotary Position Embedding to the query and key tensors.
275
+
276
+ Args:
277
+ q (`torch.Tensor`): The query tensor.
278
+ k (`torch.Tensor`): The key tensor.
279
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
280
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
281
+ position_ids (`torch.Tensor`, *optional*):
282
+ Deprecated and unused.
283
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
284
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
285
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
286
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
287
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
288
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
289
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
290
+ Returns:
291
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
292
+ """
293
+ cos = cos.unsqueeze(unsqueeze_dim)
294
+ sin = sin.unsqueeze(unsqueeze_dim)
295
+ q_embed = (q * cos) + (rotate_half(q) * sin)
296
+ k_embed = (k * cos) + (rotate_half(k) * sin)
297
+ return q_embed, k_embed
298
+
299
+
300
+ def eager_attention_forward(
301
+ module: "ModernBertAttention",
302
+ qkv: torch.Tensor,
303
+ attention_mask: torch.Tensor,
304
+ sliding_window_mask: torch.Tensor,
305
+ position_ids: Optional[torch.LongTensor],
306
+ local_attention: Tuple[int, int],
307
+ bs: int,
308
+ dim: int,
309
+ output_attentions: Optional[bool] = False,
310
+ **_kwargs,
311
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
312
+ # qkv: [batch_size, seqlen, 3, nheads, headdim]
313
+ cos, sin = module.rotary_emb(qkv, position_ids=position_ids)
314
+ query, key, value = qkv.transpose(3, 1).unbind(dim=2)
315
+ # query, key, value: [batch_size, heads, seq_len, head_dim]
316
+ query, key = apply_rotary_pos_emb(query, key, cos, sin)
317
+
318
+ scale = module.head_dim**-0.5
319
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scale
320
+
321
+ if local_attention != (-1, -1):
322
+ attention_mask = sliding_window_mask
323
+
324
+ attn_weights = attn_weights + attention_mask
325
+
326
+ # upcast attention to fp32
327
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
328
+ attn_weights = nn.functional.dropout(attn_weights, p=module.attention_dropout, training=module.training)
329
+ attn_output = torch.matmul(attn_weights, value)
330
+ attn_output = attn_output.transpose(1, 2).contiguous()
331
+ attn_output = attn_output.view(bs, -1, dim)
332
+ if output_attentions:
333
+ return (attn_output, attn_weights)
334
+ return (attn_output,)
335
+
336
+
337
+ def flash_attention_forward(
338
+ module: "ModernBertAttention",
339
+ qkv: torch.Tensor,
340
+ rotary_emb: ModernBertUnpaddedRotaryEmbedding,
341
+ cu_seqlens: torch.Tensor,
342
+ max_seqlen: int,
343
+ local_attention: Tuple[int, int],
344
+ bs: int,
345
+ dim: int,
346
+ target_dtype: torch.dtype = torch.bfloat16,
347
+ **_kwargs,
348
+ ) -> Tuple[torch.Tensor]:
349
+ # (total_seqlen, 3, nheads, headdim)
350
+ qkv = rotary_emb(qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen)
351
+
352
+ convert_dtype = qkv.dtype not in (torch.float16, torch.bfloat16)
353
+ if convert_dtype:
354
+ # FA2 implementation only supports fp16 and bf16. If FA2 is supported,
355
+ # bfloat16 must be supported as of FA2 2.5.7. (Turing GPUs not supported)
356
+ orig_dtype = qkv.dtype
357
+ qkv = qkv.to(target_dtype)
358
+
359
+ attn = flash_attn_varlen_qkvpacked_func(
360
+ qkv,
361
+ cu_seqlens=cu_seqlens,
362
+ max_seqlen=max_seqlen,
363
+ dropout_p=module.attention_dropout if module.training else 0.0,
364
+ deterministic=module.deterministic_flash_attn,
365
+ window_size=local_attention,
366
+ )
367
+ attn = attn.to(orig_dtype) # type: ignore
368
+ else:
369
+ attn = flash_attn_varlen_qkvpacked_func(
370
+ qkv,
371
+ cu_seqlens=cu_seqlens,
372
+ max_seqlen=max_seqlen,
373
+ dropout_p=module.attention_dropout if module.training else 0.0,
374
+ deterministic=module.deterministic_flash_attn,
375
+ window_size=local_attention,
376
+ )
377
+ return (attn.view(bs, dim),)
378
+
379
+
380
+ def sdpa_attention_forward(
381
+ module: "ModernBertAttention",
382
+ qkv: torch.Tensor,
383
+ attention_mask: torch.Tensor,
384
+ sliding_window_mask: torch.Tensor,
385
+ position_ids: Optional[torch.LongTensor],
386
+ local_attention: Tuple[int, int],
387
+ bs: int,
388
+ dim: int,
389
+ **_kwargs,
390
+ ) -> Tuple[torch.Tensor]:
391
+ # qkv: [batch_size, seqlen, 3, nheads, headdim]
392
+ cos, sin = module.rotary_emb(qkv, position_ids=position_ids)
393
+ query, key, value = qkv.transpose(3, 1).unbind(dim=2)
394
+ # query, key, value: [batch_size, heads, seq_len, head_dim]
395
+ query, key = apply_rotary_pos_emb(query, key, cos, sin)
396
+
397
+ if local_attention != (-1, -1):
398
+ attention_mask = sliding_window_mask
399
+
400
+ attn_output = (
401
+ F.scaled_dot_product_attention(
402
+ query,
403
+ key,
404
+ value,
405
+ dropout_p=module.attention_dropout if module.training else 0.0,
406
+ attn_mask=attention_mask,
407
+ )
408
+ .transpose(1, 2)
409
+ .contiguous()
410
+ )
411
+ attn_output = attn_output.view(bs, -1, dim)
412
+ return (attn_output,)
413
+
414
+
415
+ MODERNBERT_ATTENTION_FUNCTION = {
416
+ "flash_attention_2": flash_attention_forward,
417
+ "eager": eager_attention_forward,
418
+ "sdpa": sdpa_attention_forward,
419
+ }
420
+
421
+
422
+ class ModernBertAttention(nn.Module):
423
+ """Performs multi-headed self attention on a batch of unpadded sequences.
424
+
425
+ If Flash Attention 2 is installed, this module uses Flash Attention to improve throughput.
426
+ If Flash Attention 2 is not installed, the implementation will use PyTorch's SDPA kernel,
427
+ which requires padding and unpadding inputs, adding some overhead.
428
+
429
+ See `forward` method for additional details.
430
+ """
431
+
432
+ def __init__(self, config: ModernBertConfig, layer_id: Optional[int] = None):
433
+ super().__init__()
434
+ self.config = config
435
+ self.layer_id = layer_id
436
+
437
+ if config.hidden_size % config.num_attention_heads != 0:
438
+ raise ValueError(
439
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention heads ({config.num_attention_heads})"
440
+ )
441
+
442
+ self.attention_dropout = config.attention_dropout
443
+ self.deterministic_flash_attn = config.deterministic_flash_attn
444
+ self.num_heads = config.num_attention_heads
445
+ self.head_dim = config.hidden_size // config.num_attention_heads
446
+ self.all_head_size = self.head_dim * self.num_heads
447
+ self.Wqkv = nn.Linear(config.hidden_size, 3 * self.all_head_size, bias=config.attention_bias)
448
+
449
+ if layer_id % config.global_attn_every_n_layers != 0:
450
+ self.local_attention = (config.local_attention // 2, config.local_attention // 2)
451
+ else:
452
+ self.local_attention = (-1, -1)
453
+
454
+ rope_theta = config.global_rope_theta
455
+ max_position_embeddings = config.max_position_embeddings
456
+ if self.local_attention != (-1, -1):
457
+ if config.local_rope_theta is not None:
458
+ rope_theta = config.local_rope_theta
459
+ max_position_embeddings = config.local_attention
460
+
461
+ if config._attn_implementation == "flash_attention_2":
462
+ self.rotary_emb = ModernBertUnpaddedRotaryEmbedding(
463
+ dim=self.head_dim, max_seqlen=max_position_embeddings, base=rope_theta
464
+ )
465
+ else:
466
+ self.rotary_emb = ModernBertRotaryEmbedding(
467
+ dim=self.head_dim, max_position_embeddings=max_position_embeddings, base=rope_theta
468
+ )
469
+
470
+ self.Wo = nn.Linear(config.hidden_size, config.hidden_size, bias=config.attention_bias)
471
+ self.out_drop = nn.Dropout(config.attention_dropout) if config.attention_dropout > 0.0 else nn.Identity()
472
+ self.pruned_heads = set()
473
+
474
+ def forward(
475
+ self,
476
+ hidden_states: torch.Tensor,
477
+ output_attentions: Optional[bool] = False,
478
+ **kwargs,
479
+ ) -> torch.Tensor:
480
+ qkv = self.Wqkv(hidden_states)
481
+
482
+ bs = hidden_states.shape[0]
483
+ if self.config._attn_implementation == "flash_attention_2":
484
+ qkv = qkv.view(-1, 3, self.num_heads, self.head_dim)
485
+ else:
486
+ qkv = qkv.view(bs, -1, 3, self.num_heads, self.head_dim)
487
+
488
+ attn_outputs = MODERNBERT_ATTENTION_FUNCTION[self.config._attn_implementation](
489
+ self,
490
+ qkv=qkv,
491
+ rotary_emb=self.rotary_emb,
492
+ local_attention=self.local_attention,
493
+ bs=bs,
494
+ dim=self.all_head_size,
495
+ output_attentions=output_attentions,
496
+ **kwargs,
497
+ )
498
+ hidden_states = attn_outputs[0]
499
+ hidden_states = self.out_drop(self.Wo(hidden_states))
500
+
501
+ return (hidden_states,) + attn_outputs[1:] # add attentions if outputted
502
+
503
+
504
+ class ModernBertEncoderLayer(nn.Module):
505
+ def __init__(self, config: ModernBertConfig, layer_id: Optional[int] = None):
506
+ super().__init__()
507
+ self.config = config
508
+ if layer_id == 0:
509
+ self.attn_norm = nn.Identity()
510
+ else:
511
+ self.attn_norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias)
512
+ self.attn = ModernBertAttention(config=config, layer_id=layer_id)
513
+ self.mlp_norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias)
514
+ self.mlp = ModernBertMLP(config)
515
+
516
+ @torch.compile(dynamic=True)
517
+ def compiled_mlp(self, hidden_states: torch.Tensor) -> torch.Tensor:
518
+ return self.mlp(self.mlp_norm(hidden_states))
519
+
520
+ def forward(
521
+ self,
522
+ hidden_states: torch.Tensor,
523
+ attention_mask: Optional[torch.Tensor] = None,
524
+ sliding_window_mask: Optional[torch.Tensor] = None,
525
+ position_ids: Optional[torch.LongTensor] = None,
526
+ cu_seqlens: Optional[torch.Tensor] = None,
527
+ max_seqlen: Optional[int] = None,
528
+ output_attentions: Optional[bool] = False,
529
+ ) -> torch.Tensor:
530
+ attn_outputs = self.attn(
531
+ self.attn_norm(hidden_states),
532
+ attention_mask=attention_mask,
533
+ sliding_window_mask=sliding_window_mask,
534
+ position_ids=position_ids,
535
+ cu_seqlens=cu_seqlens,
536
+ max_seqlen=max_seqlen,
537
+ output_attentions=output_attentions,
538
+ )
539
+ hidden_states = hidden_states + attn_outputs[0]
540
+ mlp_output = (
541
+ self.compiled_mlp(hidden_states)
542
+ if self.config.reference_compile
543
+ else self.mlp(self.mlp_norm(hidden_states))
544
+ )
545
+ hidden_states = hidden_states + mlp_output
546
+
547
+ return (hidden_states,) + attn_outputs[1:] # add attentions if outputted
548
+
549
+
550
+ MODERNBERT_START_DOCSTRING = r"""
551
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
552
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
553
+ etc.)
554
+
555
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
556
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
557
+ and behavior.
558
+
559
+ Parameters:
560
+ config ([`ModernBertConfig`]):
561
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
562
+ load the weights associated with the model, only the configuration. Check out the
563
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
564
+ """
565
+
566
+
567
+ @add_start_docstrings(
568
+ "The bare ModernBert Model outputting raw hidden-states without any specific head on top.",
569
+ MODERNBERT_START_DOCSTRING,
570
+ )
571
+ class ModernBertPreTrainedModel(PreTrainedModel):
572
+ config_class = ModernBertConfig
573
+ base_model_prefix = "model"
574
+ supports_gradient_checkpointing = True
575
+ _no_split_modules = ["ModernBertEmbeddings", "ModernBertEncoderLayer"]
576
+ _supports_flash_attn_2 = True
577
+ _supports_sdpa = True
578
+ _supports_flex_attn = False
579
+
580
+ def _init_weights(self, module: nn.Module):
581
+ cutoff_factor = self.config.initializer_cutoff_factor
582
+ if cutoff_factor is None:
583
+ cutoff_factor = 3
584
+
585
+ def init_weight(module: nn.Module, std: float):
586
+ nn.init.trunc_normal_(
587
+ module.weight,
588
+ mean=0.0,
589
+ std=std,
590
+ a=-cutoff_factor * std,
591
+ b=cutoff_factor * std,
592
+ )
593
+
594
+ if isinstance(module, nn.Linear):
595
+ if module.bias is not None:
596
+ nn.init.zeros_(module.bias)
597
+
598
+ stds = {
599
+ "in": self.config.initializer_range,
600
+ "out": self.config.initializer_range / math.sqrt(2.0 * self.config.num_hidden_layers),
601
+ "embedding": self.config.initializer_range,
602
+ "final_out": self.config.hidden_size**-0.5,
603
+ }
604
+
605
+ if isinstance(module, ModernBertEmbeddings):
606
+ init_weight(module.tok_embeddings, stds["embedding"])
607
+ elif isinstance(module, ModernBertMLP):
608
+ init_weight(module.Wi, stds["in"])
609
+ init_weight(module.Wo, stds["out"])
610
+ elif isinstance(module, ModernBertAttention):
611
+ init_weight(module.Wqkv, stds["in"])
612
+ init_weight(module.Wo, stds["out"])
613
+ elif isinstance(module, ModernBertPredictionHead):
614
+ init_weight(module.dense, stds["out"])
615
+ elif isinstance(module, ModernBertForMaskedLM):
616
+ init_weight(module.decoder, stds["out"])
617
+ elif isinstance(module, (ModernBertForSequenceClassification, ModernBertForTokenClassification)):
618
+ init_weight(module.classifier, stds["final_out"])
619
+
620
+ @classmethod
621
+ def _autoset_attn_implementation(
622
+ cls,
623
+ config,
624
+ use_flash_attention_2: bool = False,
625
+ torch_dtype: Optional[torch.dtype] = None,
626
+ device_map: Optional[Union[str, Dict[str, int]]] = None,
627
+ check_device_map: bool = True,
628
+ ):
629
+ # If the user didn't specify anything, try to use flash_attention_2 if available.
630
+ # Otherwise we fall back to the default SDPA -> Eager from the super() method.
631
+ if config._attn_implementation_internal is None:
632
+ config._attn_implementation_internal = "flash_attention_2"
633
+ try:
634
+ return cls._check_and_enable_flash_attn_2(
635
+ config,
636
+ torch_dtype=torch_dtype,
637
+ device_map=device_map,
638
+ hard_check_only=False,
639
+ check_device_map=check_device_map,
640
+ )
641
+ except (ValueError, ImportError):
642
+ config._attn_implementation_internal = None
643
+ return super()._autoset_attn_implementation(
644
+ config,
645
+ use_flash_attention_2=use_flash_attention_2,
646
+ torch_dtype=torch_dtype,
647
+ device_map=device_map,
648
+ check_device_map=check_device_map,
649
+ )
650
+
651
+ def _maybe_set_compile(self):
652
+ if self.config.reference_compile is False:
653
+ return
654
+
655
+ if hasattr(self, "hf_device_map") and len(self.hf_device_map) > 1:
656
+ if self.config.reference_compile:
657
+ logger.warning_once(
658
+ "If `accelerate` split the model across devices, `torch.compile` will not work. "
659
+ "Falling back to non-compiled mode."
660
+ )
661
+ self.config.reference_compile = False
662
+
663
+ if self.device.type == "mps":
664
+ if self.config.reference_compile:
665
+ logger.warning_once(
666
+ "Compiling the model with `torch.compile` and using a `torch.mps` device is not supported. "
667
+ "Falling back to non-compiled mode."
668
+ )
669
+ self.config.reference_compile = False
670
+
671
+ if self.config.reference_compile is None:
672
+ self.config.reference_compile = is_triton_available()
673
+
674
+ def resize_token_embeddings(self, *args, **kwargs):
675
+ model_embeds = super().resize_token_embeddings(*args, **kwargs)
676
+
677
+ if self.config.reference_compile in {True, None}:
678
+ if self.config.reference_compile:
679
+ logger.warning_once(
680
+ "Resizing token embeddings with `torch.compile` is not supported. Falling back to non-compiled mode."
681
+ )
682
+ self.config.reference_compile = False
683
+
684
+ return model_embeds
685
+
686
+
687
+ def _unpad_modernbert_input(
688
+ inputs: torch.Tensor,
689
+ attention_mask: torch.Tensor,
690
+ position_ids: Optional[torch.Tensor] = None,
691
+ labels: Optional[torch.Tensor] = None,
692
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int, Optional[torch.Tensor], Optional[torch.Tensor]]:
693
+ """
694
+ Remove padding from input sequences.
695
+
696
+ Args:
697
+ inputs: (batch, seqlen, ...) or (batch, seqlen)
698
+ attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
699
+ position_ids: (batch, seqlen), int, position ids
700
+ labels: (batch, seqlen), int, labels
701
+
702
+ Returns:
703
+ unpadded_inputs: (total_nnz, ...), where total_nnz = number of tokens selected in attention_mask.
704
+ indices: (total_nnz)
705
+ cu_seqlens: (batch + 1), the cumulative sequence lengths
706
+ max_seqlen_in_batch: int
707
+ unpadded_position_ids: (total_nnz) or None
708
+ unpadded_labels: (total_nnz) or None
709
+ """
710
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
711
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
712
+ max_seqlen_in_batch = int(seqlens_in_batch.max().item())
713
+ cu_seqlens = torch.nn.functional.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
714
+
715
+ if inputs.dim() == 2:
716
+ unpadded_inputs = inputs.flatten()[indices]
717
+ else:
718
+ batch, seqlen, *rest = inputs.shape
719
+ shape = batch * seqlen
720
+ unpadded_inputs = inputs.view(shape, *rest)[indices]
721
+
722
+ unpadded_position_ids = position_ids.flatten()[indices] if position_ids is not None else None
723
+ unpadded_labels = labels.flatten()[indices] if labels is not None else None
724
+
725
+ return unpadded_inputs, indices, cu_seqlens, max_seqlen_in_batch, unpadded_position_ids, unpadded_labels
726
+
727
+
728
+ def _pad_modernbert_output(
729
+ inputs: torch.Tensor,
730
+ indices: torch.Tensor,
731
+ batch: int,
732
+ seqlen: int,
733
+ ) -> torch.Tensor:
734
+ """
735
+ Add padding to sequences.
736
+
737
+ Args:
738
+ inputs: (total_nnz, ...) or (total_nnz,), where total_nnz = number of tokens selected in attention_mask.
739
+ indices: (total_nnz)
740
+ batch: int, batch size
741
+ seqlen: int, max sequence length
742
+
743
+ Returns:
744
+ padded_inputs: (batch, seqlen, ...) or (batch, seqlen)
745
+ """
746
+ if inputs.dim() == 1:
747
+ output = torch.zeros(batch * seqlen, dtype=inputs.dtype, device=inputs.device)
748
+ output[indices] = inputs
749
+ padded_inputs = output.view(batch, seqlen)
750
+ else:
751
+ _, *rest = inputs.shape
752
+ output = torch.zeros(batch * seqlen, *rest, dtype=inputs.dtype, device=inputs.device)
753
+ output[indices] = inputs
754
+ padded_inputs = output.view(batch, seqlen, *rest)
755
+
756
+ return padded_inputs
757
+
758
+
759
+ MODERNBERT_INPUTS_DOCSTRING = r"""
760
+ Args:
761
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
762
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
763
+ it.
764
+
765
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
766
+ [`PreTrainedTokenizer.__call__`] for details.
767
+
768
+ [What are input IDs?](../glossary#input-ids)
769
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
770
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
771
+
772
+ - 1 for tokens that are **not masked**,
773
+ - 0 for tokens that are **masked**.
774
+
775
+ [What are attention masks?](../glossary#attention-mask)
776
+
777
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
778
+ [`PreTrainedTokenizer.__call__`] for details.
779
+
780
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
781
+ `past_key_values`).
782
+
783
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
784
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
785
+ information on the default strategy.
786
+
787
+ - 1 indicates the head is **not masked**,
788
+ - 0 indicates the head is **masked**.
789
+ sliding_window_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
790
+ Mask to avoid performing attention on padding or far-away tokens. In ModernBert, only every few layers
791
+ perform global attention, while the rest perform local attention. This mask is used to avoid attending to
792
+ far-away tokens in the local attention layers.
793
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
794
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
795
+ config.n_positions - 1]`.
796
+
797
+ [What are position IDs?](../glossary#position-ids)
798
+ indices (`torch.Tensor` of shape `(total_unpadded_tokens,)`, *optional*):
799
+ Indices of the non-padding tokens in the input sequence. Used for unpadding the output.
800
+ cu_seqlens (`torch.Tensor` of shape `(batch + 1,)`, *optional*):
801
+ Cumulative sequence lengths of the input sequences. Used to index the unpadded tensors.
802
+ max_seqlen (`int`, *optional*):
803
+ Maximum sequence length in the batch. Used to pad the output tensors.
804
+ batch_size (`int`, *optional*):
805
+ Batch size of the input sequences. Used to pad the output tensors.
806
+ seq_len (`int`, *optional*):
807
+ Sequence length of the input sequences. Used to pad the output tensors.
808
+ output_attentions (`bool`, *optional*):
809
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
810
+ tensors for more detail.
811
+ output_hidden_states (`bool`, *optional*):
812
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
813
+ more detail.
814
+ return_dict (`bool`, *optional*):
815
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
816
+ """
817
+
818
+
819
+ @add_start_docstrings(
820
+ "The bare ModernBert Model outputting raw hidden-states without any specific head on top.",
821
+ MODERNBERT_START_DOCSTRING,
822
+ )
823
+ class ModernBertModel(ModernBertPreTrainedModel):
824
+ def __init__(self, config: ModernBertConfig):
825
+ super().__init__(config)
826
+ self.config = config
827
+ self.embeddings = ModernBertEmbeddings(config)
828
+ self.layers = nn.ModuleList(
829
+ [ModernBertEncoderLayer(config, layer_id) for layer_id in range(config.num_hidden_layers)]
830
+ )
831
+ self.final_norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias)
832
+ self.gradient_checkpointing = False
833
+ self.post_init()
834
+
835
+ def get_input_embeddings(self):
836
+ return self.embeddings.tok_embeddings
837
+
838
+ def set_input_embeddings(self, value):
839
+ self.embeddings.tok_embeddings = value
840
+
841
+ @add_start_docstrings_to_model_forward(MODERNBERT_INPUTS_DOCSTRING)
842
+ @add_code_sample_docstrings(
843
+ checkpoint=_CHECKPOINT_FOR_DOC,
844
+ output_type=BaseModelOutput,
845
+ config_class=_CONFIG_FOR_DOC,
846
+ )
847
+ def forward(
848
+ self,
849
+ input_ids: torch.LongTensor = None,
850
+ attention_mask: Optional[torch.Tensor] = None,
851
+ sliding_window_mask: Optional[torch.Tensor] = None,
852
+ position_ids: Optional[torch.LongTensor] = None,
853
+ indices: Optional[torch.Tensor] = None,
854
+ cu_seqlens: Optional[torch.Tensor] = None,
855
+ max_seqlen: Optional[int] = None,
856
+ batch_size: Optional[int] = None,
857
+ seq_len: Optional[int] = None,
858
+ output_attentions: Optional[bool] = None,
859
+ output_hidden_states: Optional[bool] = None,
860
+ return_dict: Optional[bool] = None,
861
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutput]:
862
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
863
+ output_hidden_states = (
864
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
865
+ )
866
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
867
+
868
+ all_hidden_states = () if output_hidden_states else None
869
+ all_self_attentions = () if output_attentions else None
870
+
871
+ self._maybe_set_compile()
872
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
873
+
874
+ if batch_size is None and seq_len is None:
875
+ batch_size, seq_len = input_ids.shape[:2]
876
+
877
+ if attention_mask is None:
878
+ attention_mask = torch.ones((batch_size, seq_len), device=input_ids.device, dtype=torch.bool)
879
+
880
+ repad = False
881
+ if self.config._attn_implementation == "flash_attention_2":
882
+ if indices is None and cu_seqlens is None and max_seqlen is None:
883
+ repad = True
884
+ with torch.no_grad():
885
+ input_ids, indices, cu_seqlens, max_seqlen, *_ = _unpad_modernbert_input(
886
+ inputs=input_ids, attention_mask=attention_mask
887
+ )
888
+ else:
889
+ if position_ids is None:
890
+ position_ids = torch.arange(seq_len, device=input_ids.device).unsqueeze(0)
891
+
892
+ attention_mask, sliding_window_mask = self._update_attention_mask(
893
+ attention_mask, output_attentions=output_attentions
894
+ )
895
+
896
+ hidden_states = self.embeddings(input_ids)
897
+
898
+ for encoder_layer in self.layers:
899
+ if output_hidden_states:
900
+ all_hidden_states = all_hidden_states + (hidden_states,)
901
+
902
+ if self.gradient_checkpointing and self.training:
903
+ layer_outputs = self._gradient_checkpointing_func(
904
+ encoder_layer.__call__,
905
+ hidden_states,
906
+ attention_mask,
907
+ sliding_window_mask,
908
+ position_ids,
909
+ cu_seqlens,
910
+ max_seqlen,
911
+ output_attentions,
912
+ )
913
+ else:
914
+ layer_outputs = encoder_layer(
915
+ hidden_states,
916
+ attention_mask=attention_mask,
917
+ sliding_window_mask=sliding_window_mask,
918
+ position_ids=position_ids,
919
+ cu_seqlens=cu_seqlens,
920
+ max_seqlen=max_seqlen,
921
+ output_attentions=output_attentions,
922
+ )
923
+ hidden_states = layer_outputs[0]
924
+ if output_attentions and len(layer_outputs) > 1:
925
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
926
+
927
+ if output_hidden_states:
928
+ all_hidden_states = all_hidden_states + (hidden_states,)
929
+
930
+ hidden_states = self.final_norm(hidden_states)
931
+
932
+ if repad:
933
+ hidden_states = _pad_modernbert_output(
934
+ inputs=hidden_states, indices=indices, batch=batch_size, seqlen=seq_len
935
+ )
936
+ if all_hidden_states is not None:
937
+ all_hidden_states = tuple(
938
+ _pad_modernbert_output(inputs=hs, indices=indices, batch=batch_size, seqlen=seq_len)
939
+ for hs in all_hidden_states
940
+ )
941
+
942
+ if not return_dict:
943
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
944
+ return BaseModelOutput(
945
+ last_hidden_state=hidden_states,
946
+ hidden_states=all_hidden_states,
947
+ attentions=all_self_attentions,
948
+ )
949
+
950
+ def _update_attention_mask(self, attention_mask: torch.Tensor, output_attentions: bool) -> torch.Tensor:
951
+ if output_attentions:
952
+ if self.config._attn_implementation == "sdpa":
953
+ logger.warning_once(
954
+ "Outputting attentions is only supported with the 'eager' attention implementation, "
955
+ 'not with "sdpa". Falling back to `attn_implementation="eager"`.'
956
+ )
957
+ self.config._attn_implementation = "eager"
958
+ elif self.config._attn_implementation != "eager":
959
+ logger.warning_once(
960
+ "Outputting attentions is only supported with the eager attention implementation, "
961
+ f'not with {self.config._attn_implementation}. Consider setting `attn_implementation="eager"`.'
962
+ " Setting `output_attentions=False`."
963
+ )
964
+
965
+ global_attention_mask = _prepare_4d_attention_mask(attention_mask, self.dtype)
966
+
967
+ # Create position indices
968
+ rows = torch.arange(global_attention_mask.shape[2]).unsqueeze(0)
969
+ # Calculate distance between positions
970
+ distance = torch.abs(rows - rows.T)
971
+
972
+ # Create sliding window mask (1 for positions within window, 0 outside)
973
+ window_mask = (
974
+ (distance <= self.config.local_attention // 2).unsqueeze(0).unsqueeze(0).to(attention_mask.device)
975
+ )
976
+ # Combine with existing mask
977
+ sliding_window_mask = global_attention_mask.masked_fill(window_mask.logical_not(), torch.finfo(self.dtype).min)
978
+
979
+ return global_attention_mask, sliding_window_mask
980
+
981
+
982
+ class ModernBertPredictionHead(nn.Module):
983
+ def __init__(self, config: ModernBertConfig):
984
+ super().__init__()
985
+ self.config = config
986
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size, config.classifier_bias)
987
+ self.act = ACT2FN[config.classifier_activation]
988
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias)
989
+
990
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
991
+ return self.norm(self.act(self.dense(hidden_states)))
992
+
993
+
994
+ @add_start_docstrings(
995
+ "The ModernBert Model with a decoder head on top that is used for masked language modeling.",
996
+ MODERNBERT_START_DOCSTRING,
997
+ )
998
+ class ModernBertForMaskedLM(ModernBertPreTrainedModel):
999
+ _tied_weights_keys = ["decoder.weight"]
1000
+
1001
+ def __init__(self, config: ModernBertConfig):
1002
+ super().__init__(config)
1003
+ self.config = config
1004
+ self.model = ModernBertModel(config)
1005
+ self.head = ModernBertPredictionHead(config)
1006
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=config.decoder_bias)
1007
+
1008
+ self.sparse_prediction = self.config.sparse_prediction
1009
+ self.sparse_pred_ignore_index = self.config.sparse_pred_ignore_index
1010
+
1011
+ # Initialize weights and apply final processing
1012
+ self.post_init()
1013
+
1014
+ def get_output_embeddings(self):
1015
+ return self.decoder
1016
+
1017
+ def set_output_embeddings(self, new_embeddings: nn.Linear):
1018
+ self.decoder = new_embeddings
1019
+
1020
+ @torch.compile(dynamic=True)
1021
+ def compiled_head(self, output: torch.Tensor) -> torch.Tensor:
1022
+ return self.decoder(self.head(output))
1023
+
1024
+ @add_start_docstrings_to_model_forward(MODERNBERT_INPUTS_DOCSTRING)
1025
+ @add_code_sample_docstrings(
1026
+ checkpoint=_CHECKPOINT_FOR_DOC,
1027
+ output_type=MaskedLMOutput,
1028
+ config_class=_CONFIG_FOR_DOC,
1029
+ )
1030
+ def forward(
1031
+ self,
1032
+ input_ids: Optional[torch.Tensor],
1033
+ attention_mask: Optional[torch.Tensor] = None,
1034
+ sliding_window_mask: Optional[torch.Tensor] = None,
1035
+ position_ids: Optional[torch.Tensor] = None,
1036
+ labels: Optional[torch.Tensor] = None,
1037
+ indices: Optional[torch.Tensor] = None,
1038
+ cu_seqlens: Optional[torch.Tensor] = None,
1039
+ max_seqlen: Optional[int] = None,
1040
+ batch_size: Optional[int] = None,
1041
+ seq_len: Optional[int] = None,
1042
+ output_attentions: Optional[bool] = None,
1043
+ output_hidden_states: Optional[bool] = None,
1044
+ return_dict: Optional[bool] = None,
1045
+ **kwargs,
1046
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
1047
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1048
+ self._maybe_set_compile()
1049
+
1050
+ if self.config._attn_implementation == "flash_attention_2":
1051
+ if indices is None and cu_seqlens is None and max_seqlen is None:
1052
+ batch_size, seq_len = input_ids.shape[:2]
1053
+ if attention_mask is None:
1054
+ attention_mask = torch.ones((batch_size, seq_len), device=input_ids.device, dtype=torch.bool)
1055
+ with torch.no_grad():
1056
+ input_ids, indices, cu_seqlens, max_seqlen, position_ids, labels = _unpad_modernbert_input(
1057
+ inputs=input_ids, attention_mask=attention_mask, position_ids=position_ids, labels=labels
1058
+ )
1059
+
1060
+ outputs = self.model(
1061
+ input_ids,
1062
+ attention_mask=attention_mask,
1063
+ sliding_window_mask=sliding_window_mask,
1064
+ position_ids=position_ids,
1065
+ indices=indices,
1066
+ cu_seqlens=cu_seqlens,
1067
+ max_seqlen=max_seqlen,
1068
+ batch_size=batch_size,
1069
+ seq_len=seq_len,
1070
+ output_attentions=output_attentions,
1071
+ output_hidden_states=output_hidden_states,
1072
+ return_dict=return_dict,
1073
+ )
1074
+ last_hidden_state = outputs[0]
1075
+
1076
+ if self.sparse_prediction and labels is not None:
1077
+ # flatten labels and output first
1078
+ labels = labels.view(-1)
1079
+ last_hidden_state = last_hidden_state.view(labels.shape[0], -1)
1080
+
1081
+ # then filter out the non-masked tokens
1082
+ mask_tokens = labels != self.sparse_pred_ignore_index
1083
+ last_hidden_state = last_hidden_state[mask_tokens]
1084
+ labels = labels[mask_tokens]
1085
+
1086
+ logits = (
1087
+ self.compiled_head(last_hidden_state)
1088
+ if self.config.reference_compile
1089
+ else self.decoder(self.head(last_hidden_state))
1090
+ )
1091
+
1092
+ loss = None
1093
+ if labels is not None:
1094
+ loss = self.loss_function(logits, labels, vocab_size=self.config.vocab_size)
1095
+
1096
+ if self.config._attn_implementation == "flash_attention_2":
1097
+ with torch.no_grad():
1098
+ logits = _pad_modernbert_output(inputs=logits, indices=indices, batch=batch_size, seqlen=seq_len)
1099
+ if not return_dict:
1100
+ output = (logits,)
1101
+ return ((loss,) + output) if loss is not None else output
1102
+
1103
+ return MaskedLMOutput(
1104
+ loss=loss,
1105
+ logits=logits,
1106
+ hidden_states=outputs.hidden_states,
1107
+ attentions=outputs.attentions,
1108
+ )
1109
+
1110
+
1111
+ @add_start_docstrings(
1112
+ "The ModernBert Model with a sequence classification head on top that performs pooling.",
1113
+ MODERNBERT_START_DOCSTRING,
1114
+ )
1115
+ class ModernBertForSequenceClassification(ModernBertPreTrainedModel):
1116
+ def __init__(self, config: ModernBertConfig):
1117
+ super().__init__(config)
1118
+ self.num_labels = config.num_labels
1119
+ self.config = config
1120
+
1121
+ self.model = ModernBertModel(config)
1122
+ self.head = ModernBertPredictionHead(config)
1123
+ self.drop = torch.nn.Dropout(config.classifier_dropout)
1124
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1125
+
1126
+ # Initialize weights and apply final processing
1127
+ self.post_init()
1128
+
1129
+ @add_start_docstrings_to_model_forward(MODERNBERT_INPUTS_DOCSTRING)
1130
+ @add_code_sample_docstrings(
1131
+ checkpoint=_CHECKPOINT_FOR_DOC,
1132
+ output_type=SequenceClassifierOutput,
1133
+ config_class=_CONFIG_FOR_DOC,
1134
+ )
1135
+ def forward(
1136
+ self,
1137
+ input_ids: Optional[torch.Tensor],
1138
+ attention_mask: Optional[torch.Tensor] = None,
1139
+ sliding_window_mask: Optional[torch.Tensor] = None,
1140
+ position_ids: Optional[torch.Tensor] = None,
1141
+ labels: Optional[torch.Tensor] = None,
1142
+ indices: Optional[torch.Tensor] = None,
1143
+ cu_seqlens: Optional[torch.Tensor] = None,
1144
+ max_seqlen: Optional[int] = None,
1145
+ batch_size: Optional[int] = None,
1146
+ seq_len: Optional[int] = None,
1147
+ output_attentions: Optional[bool] = None,
1148
+ output_hidden_states: Optional[bool] = None,
1149
+ return_dict: Optional[bool] = None,
1150
+ **kwargs,
1151
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1152
+ r"""
1153
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1154
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1155
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1156
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1157
+ """
1158
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1159
+ self._maybe_set_compile()
1160
+
1161
+ outputs = self.model(
1162
+ input_ids,
1163
+ attention_mask=attention_mask,
1164
+ sliding_window_mask=sliding_window_mask,
1165
+ position_ids=position_ids,
1166
+ indices=indices,
1167
+ cu_seqlens=cu_seqlens,
1168
+ max_seqlen=max_seqlen,
1169
+ batch_size=batch_size,
1170
+ seq_len=seq_len,
1171
+ output_attentions=output_attentions,
1172
+ output_hidden_states=output_hidden_states,
1173
+ return_dict=return_dict,
1174
+ )
1175
+ last_hidden_state = outputs[0]
1176
+
1177
+ if self.config.classifier_pooling == "cls":
1178
+ last_hidden_state = last_hidden_state[:, 0]
1179
+ elif self.config.classifier_pooling == "mean":
1180
+ last_hidden_state = (last_hidden_state * attention_mask.unsqueeze(-1)).sum(dim=1) / attention_mask.sum(
1181
+ dim=1, keepdim=True
1182
+ )
1183
+
1184
+ pooled_output = self.head(last_hidden_state)
1185
+ pooled_output = self.drop(pooled_output)
1186
+ logits = self.classifier(pooled_output)
1187
+
1188
+ loss = None
1189
+ if labels is not None:
1190
+ if self.config.problem_type is None:
1191
+ if self.num_labels == 1:
1192
+ self.config.problem_type = "regression"
1193
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1194
+ self.config.problem_type = "single_label_classification"
1195
+ else:
1196
+ self.config.problem_type = "multi_label_classification"
1197
+
1198
+ if self.config.problem_type == "regression":
1199
+ loss_fct = MSELoss()
1200
+ if self.num_labels == 1:
1201
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1202
+ else:
1203
+ loss = loss_fct(logits, labels)
1204
+ elif self.config.problem_type == "single_label_classification":
1205
+ loss_fct = CrossEntropyLoss()
1206
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1207
+ elif self.config.problem_type == "multi_label_classification":
1208
+ loss_fct = BCEWithLogitsLoss()
1209
+ loss = loss_fct(logits, labels)
1210
+
1211
+ if not return_dict:
1212
+ output = (logits,)
1213
+ return ((loss,) + output) if loss is not None else output
1214
+
1215
+ return SequenceClassifierOutput(
1216
+ loss=loss,
1217
+ logits=logits,
1218
+ hidden_states=outputs.hidden_states,
1219
+ attentions=outputs.attentions,
1220
+ )
1221
+
1222
+
1223
+ @add_start_docstrings(
1224
+ "The ModernBert Model with a token classification head on top, e.g. for Named Entity Recognition (NER) tasks.",
1225
+ MODERNBERT_START_DOCSTRING,
1226
+ )
1227
+ class ModernBertForTokenClassification(ModernBertPreTrainedModel):
1228
+ def __init__(self, config: ModernBertConfig):
1229
+ super().__init__(config)
1230
+ self.num_labels = config.num_labels
1231
+
1232
+ self.model = ModernBertModel(config)
1233
+ self.head = ModernBertPredictionHead(config)
1234
+ self.drop = torch.nn.Dropout(config.classifier_dropout)
1235
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1236
+
1237
+ # Initialize weights and apply final processing
1238
+ self.post_init()
1239
+
1240
+ @add_start_docstrings_to_model_forward(MODERNBERT_INPUTS_DOCSTRING)
1241
+ @add_code_sample_docstrings(
1242
+ checkpoint=_CHECKPOINT_FOR_DOC,
1243
+ output_type=TokenClassifierOutput,
1244
+ config_class=_CONFIG_FOR_DOC,
1245
+ )
1246
+ def forward(
1247
+ self,
1248
+ input_ids: Optional[torch.Tensor],
1249
+ attention_mask: Optional[torch.Tensor] = None,
1250
+ sliding_window_mask: Optional[torch.Tensor] = None,
1251
+ position_ids: Optional[torch.Tensor] = None,
1252
+ labels: Optional[torch.Tensor] = None,
1253
+ indices: Optional[torch.Tensor] = None,
1254
+ cu_seqlens: Optional[torch.Tensor] = None,
1255
+ max_seqlen: Optional[int] = None,
1256
+ batch_size: Optional[int] = None,
1257
+ seq_len: Optional[int] = None,
1258
+ output_attentions: Optional[bool] = None,
1259
+ output_hidden_states: Optional[bool] = None,
1260
+ return_dict: Optional[bool] = None,
1261
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1262
+ r"""
1263
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1264
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1265
+ """
1266
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1267
+ self._maybe_set_compile()
1268
+
1269
+ outputs = self.model(
1270
+ input_ids,
1271
+ attention_mask=attention_mask,
1272
+ sliding_window_mask=sliding_window_mask,
1273
+ position_ids=position_ids,
1274
+ indices=indices,
1275
+ cu_seqlens=cu_seqlens,
1276
+ max_seqlen=max_seqlen,
1277
+ batch_size=batch_size,
1278
+ seq_len=seq_len,
1279
+ output_attentions=output_attentions,
1280
+ output_hidden_states=output_hidden_states,
1281
+ return_dict=return_dict,
1282
+ )
1283
+ last_hidden_state = outputs[0]
1284
+
1285
+ last_hidden_state = self.head(last_hidden_state)
1286
+ last_hidden_state = self.drop(last_hidden_state)
1287
+ logits = self.classifier(last_hidden_state)
1288
+
1289
+ loss = None
1290
+ if labels is not None:
1291
+ loss_fct = CrossEntropyLoss()
1292
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1293
+
1294
+ if not return_dict:
1295
+ output = (logits,) + outputs[1:]
1296
+ return ((loss,) + output) if loss is not None else output
1297
+
1298
+ return TokenClassifierOutput(
1299
+ loss=loss,
1300
+ logits=logits,
1301
+ hidden_states=outputs.hidden_states,
1302
+ attentions=outputs.attentions,
1303
+ )
1304
+
1305
+
1306
+ __all__ = [
1307
+ "ModernBertModel",
1308
+ "ModernBertPreTrainedModel",
1309
+ "ModernBertForMaskedLM",
1310
+ "ModernBertForSequenceClassification",
1311
+ "ModernBertForTokenClassification",
1312
+ ]
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:59986e96524b43b5cf379da759af0304a39d83e53a634d78efed2355ea3b6f96
3
+ size 643697266
special_tokens_map.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "cls_token": {
10
+ "content": "[CLS]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "eos_token": {
17
+ "content": "[SEP]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "mask_token": {
24
+ "content": "[MASK]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "pad_token": {
31
+ "content": "[PAD]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ },
37
+ "sep_token": {
38
+ "content": "[SEP]",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false
43
+ },
44
+ "unk_token": {
45
+ "content": "[UNK]",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false
50
+ }
51
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[CLS]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "[PAD]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "[SEP]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "[UNK]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "4": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "bos_token": "[CLS]",
45
+ "clean_up_tokenization_spaces": false,
46
+ "cls_token": "[CLS]",
47
+ "do_lower_case": false,
48
+ "eos_token": "[SEP]",
49
+ "extra_special_tokens": {},
50
+ "keep_accents": true,
51
+ "mask_token": "[MASK]",
52
+ "model_max_length": 1000000000000000019884624838656,
53
+ "pad_token": "[PAD]",
54
+ "sep_token": "[SEP]",
55
+ "split_by_punct": true,
56
+ "tokenizer_class": "DebertaV2TokenizerFast",
57
+ "unk_token": "[UNK]"
58
+ }
ud.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import TokenClassificationPipeline
2
+
3
+ class UniversalDependenciesPipeline(TokenClassificationPipeline):
4
+ def _forward(self,model_inputs):
5
+ import torch
6
+ v=model_inputs["input_ids"][0].tolist()
7
+ with torch.no_grad():
8
+ e=self.model(input_ids=torch.tensor([v[0:i]+[self.tokenizer.mask_token_id]+v[i+1:]+[j] for i,j in enumerate(v[1:-1],1)],device=self.device))
9
+ return {"logits":e.logits[:,1:-2,:],**model_inputs}
10
+ def check_model_type(self,supported_models):
11
+ pass
12
+ def postprocess(self,model_outputs,**kwargs):
13
+ import numpy
14
+ if "logits" not in model_outputs:
15
+ return "".join(self.postprocess(x,**kwargs) for x in model_outputs)
16
+ e=model_outputs["logits"].numpy()
17
+ r=[1 if i==0 else -1 if j.endswith("|root") else 0 for i,j in sorted(self.model.config.id2label.items())]
18
+ e+=numpy.where(numpy.add.outer(numpy.identity(e.shape[0]),r)==0,0,numpy.nan)
19
+ g=self.model.config.label2id["X|_|goeswith"]
20
+ r=numpy.tri(e.shape[0])
21
+ for i in range(e.shape[0]):
22
+ for j in range(i+2,e.shape[1]):
23
+ r[i,j]=r[i,j-1] if numpy.nanargmax(e[i,j-1])==g else 1
24
+ e[:,:,g]+=numpy.where(r==0,0,numpy.nan)
25
+ m,p=numpy.nanmax(e,axis=2),numpy.nanargmax(e,axis=2)
26
+ h=self.chu_liu_edmonds(m)
27
+ z=[i for i,j in enumerate(h) if i==j]
28
+ if len(z)>1:
29
+ k,h=z[numpy.nanargmax(m[z,z])],numpy.nanmin(m)-numpy.nanmax(m)
30
+ m[:,z]+=[[0 if j in z and (i!=j or i==k) else h for i in z] for j in range(m.shape[0])]
31
+ h=self.chu_liu_edmonds(m)
32
+ v=[(s,e) for s,e in model_outputs["offset_mapping"][0].tolist() if s<e]
33
+ q=[self.model.config.id2label[p[j,i]].split("|") for i,j in enumerate(h)]
34
+ if "aggregation_strategy" in kwargs and kwargs["aggregation_strategy"]!="none":
35
+ for i,j in reversed(list(enumerate(q[1:],1))):
36
+ if j[-1]=="goeswith" and set([t[-1] for t in q[h[i]+1:i+1]])=={"goeswith"}:
37
+ h=[b if i>b else b-1 for a,b in enumerate(h) if i!=a]
38
+ v[i-1]=(v[i-1][0],v.pop(i)[1])
39
+ q.pop(i)
40
+ elif v[i-1][1]>v[i][0]:
41
+ h=[b if i>b else b-1 for a,b in enumerate(h) if i!=a]
42
+ v[i-1]=(v[i-1][0],v.pop(i)[1])
43
+ q.pop(i)
44
+ t=model_outputs["sentence"].replace("\n"," ")
45
+ u="# text = "+t+"\n"
46
+ for i,(s,e) in enumerate(v):
47
+ u+="\t".join([str(i+1),t[s:e],"_",q[i][0],"_","|".join(q[i][1:-1]),str(0 if h[i]==i else h[i]+1),q[i][-1],"_","_" if i+1<len(v) and e<v[i+1][0] else "SpaceAfter=No"])+"\n"
48
+ return u+"\n"
49
+ def chu_liu_edmonds(self,matrix):
50
+ import numpy
51
+ h=numpy.nanargmax(matrix,axis=0)
52
+ x=[-1 if i==j else j for i,j in enumerate(h)]
53
+ for b in [lambda x,i,j:-1 if i not in x else x[i],lambda x,i,j:-1 if j<0 else x[j]]:
54
+ y=[]
55
+ while x!=y:
56
+ y=list(x)
57
+ for i,j in enumerate(x):
58
+ x[i]=b(x,i,j)
59
+ if max(x)<0:
60
+ return h
61
+ y,x=[i for i,j in enumerate(x) if j==max(x)],[i for i,j in enumerate(x) if j<max(x)]
62
+ z=matrix-numpy.nanmax(matrix,axis=0)
63
+ m=numpy.block([[z[x,:][:,x],numpy.nanmax(z[x,:][:,y],axis=1).reshape(len(x),1)],[numpy.nanmax(z[y,:][:,x],axis=0),numpy.nanmax(z[y,y])]])
64
+ k=[j if i==len(x) else x[j] if j<len(x) else y[numpy.nanargmax(z[y,x[i]])] for i,j in enumerate(self.chu_liu_edmonds(m))]
65
+ h=[j if i in y else k[x.index(i)] for i,j in enumerate(h)]
66
+ i=y[numpy.nanargmax(z[x[k[-1]],y] if k[-1]<len(x) else z[y,y])]
67
+ h[i]=x[k[-1]] if k[-1]<len(x) else i
68
+ return h