KoichiYasuoka commited on
Commit
86b8c35
·
1 Parent(s): 43e3574

initial release

Browse files
README.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - "en"
4
+ tags:
5
+ - "english"
6
+ - "token-classification"
7
+ - "pos"
8
+ - "dependency-parsing"
9
+ base_model: answerdotai/ModernBERT-base
10
+ datasets:
11
+ - "universal_dependencies"
12
+ license: "apache-2.0"
13
+ pipeline_tag: "token-classification"
14
+ ---
15
+
16
+ # modernbert-base-english-ud-triangular
17
+
18
+ ## Model Description
19
+
20
+ This is a ModernBERT model for POS-tagging and dependency-parsing (using `goeswith` for subwords), derived from [ModernBERT-base](https://huggingface.co/answerdotai/ModernBERT-base).
21
+
22
+ ## How to Use
23
+
24
+ ```py
25
+ from transformers import pipeline
26
+ nlp=pipeline("universal-dependencies","KoichiYasuoka/modernbert-base-english-ud-triangular",trust_remote_code=True,aggregation_strategy="simple")
27
+ print(nlp("I saw a horse yesterday which had no name"))
28
+ ```
29
+
config.json ADDED
The diff for this file is too large to render. See raw diff
 
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,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/python3
2
+ import os,json
3
+ tgt="KoichiYasuoka/modernbert-base-english-ud-triangular"
4
+ url="https://github.com/UniversalDependencies/UD_English-"
5
+ for e in ["EWT","GUM","Atis","ParTUT","LinES"]:
6
+ u=url+e
7
+ d=os.path.basename(u)
8
+ os.system("test -d "+d+" || git clone --depth=1 "+u)
9
+ s='BEGIN{FS="\\t";OFS="\\t"};{if(NF==10){if($1~/^[1-9][0-9]*-/){split($1,a,"-");if($10~/SpaceAfter=No/)a[2]++}else if($1-a[1]>=0&&$1-a[2]<0)$10=($10=="_")?"SpaceAfter=No":$10"|SpaceAfter=No"}print}'
10
+ os.system("for F in train dev test ; do nawk '"+s+"' UD_English-*/*-$F.conllu > $F.conllu ; done")
11
+ os.system("""
12
+ if test -d transformers
13
+ then :
14
+ else git clone --depth=1 https://github.com/huggingface/transformers transformers-all
15
+ ln -s transformers-all/src/transformers transformers
16
+ fi
17
+ test -d ModernBERT-base || git clone --depth=1 https://huggingface.co/answerdotai/ModernBERT-base
18
+ test -f ModernBERT-base/configuration_modernbert.py || sed 's/^from \\.\\.\\./from transformers./' transformers/models/modernbert/configuration_modernbert.py > ModernBERT-base/configuration_modernbert.py
19
+ test -f ModernBERT-base/modeling_modernbert.py || sed -e 's/^from \\.\\.\\./from transformers./' -e 's/^from .* import is_triton_available/import importlib\\nis_triton_available = lambda: importlib.util.find_spec("triton") is not None/' transformers/models/modernbert/modeling_modernbert.py > ModernBERT-base/modeling_modernbert.py
20
+ """)
21
+ with open("ModernBERT-base/config.json","r",encoding="utf-8") as r:
22
+ d=json.load(r)
23
+ if not "auto_map" in d:
24
+ d["auto_map"]={
25
+ "AutoConfig":"configuration_modernbert.ModernBertConfig",
26
+ "AutoModel":"modeling_modernbert.ModernBertModel",
27
+ "AutoModelForMaskedLM":"modeling_modernbert.ModernBertForMaskedLM",
28
+ "AutoModelForSequenceClassification":"modeling_modernbert.ModernBertForSequenceClassification",
29
+ "AutoModelForTokenClassification":"modeling_modernbert.ModernBertForTokenClassification"
30
+ }
31
+ with open("ModernBERT-base/config.json","w",encoding="utf-8") as w:
32
+ json.dump(d,w,indent=2)
33
+ class UDTriangularDataset(object):
34
+ def __init__(self,conllu,tokenizer):
35
+ self.conllu=open(conllu,"r",encoding="utf-8")
36
+ self.tokenizer=tokenizer
37
+ self.seeks=[0]
38
+ label=set(["SYM|x","X|x"])
39
+ dep=set(["X|x|r-goeswith"])
40
+ s=self.conllu.readline()
41
+ while s!="":
42
+ if s=="\n":
43
+ self.seeks.append(self.conllu.tell())
44
+ else:
45
+ w=s.split("\t")
46
+ if len(w)==10:
47
+ if w[0].isdecimal():
48
+ p=w[3]
49
+ q="" if w[5]=="_" else "|"+w[5]
50
+ d=("|" if w[6]=="0" else "|l-" if int(w[0])<int(w[6]) else "|r-")+w[7]
51
+ label.add(p+"|o"+q)
52
+ label.add(p+"|x"+q)
53
+ dep.add(p+"|o"+q+d)
54
+ dep.add(p+"|x"+q+d)
55
+ s=self.conllu.readline()
56
+ lid={l:i for i,l in enumerate(sorted(label))}
57
+ for i,d in enumerate(sorted(dep),len(lid)):
58
+ lid[d]=i
59
+ self.label2id=lid
60
+ def __call__(*args):
61
+ lid={l:i for i,l in enumerate(sorted(set(sum([list(t.label2id) for t in args],[]))))}
62
+ for t in args:
63
+ t.label2id=lid
64
+ return lid
65
+ def __del__(self):
66
+ self.conllu.close()
67
+ __len__=lambda self:len(self.seeks)-1
68
+ def __getitem__(self,i):
69
+ self.conllu.seek(self.seeks[i])
70
+ c,t,s=[],[""],False
71
+ while t[0]!="\n":
72
+ t=self.conllu.readline().split("\t")
73
+ if len(t)==10 and t[0].isdecimal():
74
+ if s:
75
+ t[1]=" "+t[1]
76
+ c.append(t)
77
+ s=t[9].find("SpaceAfter=No")<0
78
+ v=self.tokenizer([t[1] for t in c],add_special_tokens=False)["input_ids"]
79
+ for i in range(len(v)-1,-1,-1):
80
+ for j in range(1,len(v[i])):
81
+ c.insert(i+1,[c[i][0],"_","_","X","_","_",c[i][0],"goeswith","_","_"])
82
+ y=["0"]+[t[0] for t in c]
83
+ h=[i if t[6]=="0" else y.index(t[6]) for i,t in enumerate(c,1)]
84
+ x=["o" if k>i or sum([1 if j==i+1 else 0 for j in h[i+1:]])>0 else "x" for i,k in enumerate(h)]
85
+ p=[t[3]+"|"+x[i] if t[5]=="_" else t[3]+"|"+x[i]+"|"+t[5] for i,t in enumerate(c)]
86
+ d=[t[7] if t[6]=="0" else "l-"+t[7] if int(t[0])<int(t[6]) else "r-"+t[7] for t in c]
87
+ v=sum(v,[])
88
+ ids=[self.tokenizer.cls_token_id]
89
+ upos=["SYM|x"]
90
+ for i,k in enumerate(v):
91
+ if len(v)<128 or x[i]=="o":
92
+ ids.append(k)
93
+ upos.append(p[i]+"|"+d[i] if h[i]==i+1 else p[i])
94
+ for j in range(i+1,len(v)):
95
+ ids.append(v[j])
96
+ upos.append(p[j]+"|"+d[j] if h[j]==i+1 else p[i]+"|"+d[i] if h[i]==j+1 else p[j])
97
+ ids.append(self.tokenizer.sep_token_id)
98
+ upos.append("SYM|x")
99
+ return {"input_ids":ids[:8192],"labels":[self.label2id[p] for p in upos[:8192]]}
100
+ from transformers import AutoTokenizer,AutoConfig,AutoModelForTokenClassification,DataCollatorForTokenClassification,TrainingArguments,Trainer
101
+ from tokenizers.pre_tokenizers import Sequence,Split
102
+ from tokenizers import Regex
103
+ tkz=AutoTokenizer.from_pretrained("ModernBERT-base")
104
+ tkz.backend_tokenizer.pre_tokenizer=Sequence([Split(Regex("[nN]['`’][tT]"),"isolated"),tkz.backend_tokenizer.pre_tokenizer])
105
+ trainDS=UDTriangularDataset("train.conllu",tkz)
106
+ devDS=UDTriangularDataset("dev.conllu",tkz)
107
+ testDS=UDTriangularDataset("test.conllu",tkz)
108
+ lid=trainDS(devDS,testDS)
109
+ cfg=AutoConfig.from_pretrained("ModernBERT-base",num_labels=len(lid),label2id=lid,id2label={i:l for l,i in lid.items()},ignore_mismatched_sizes=True,trust_remote_code=True)
110
+ mdl=AutoModelForTokenClassification.from_pretrained("ModernBERT-base",config=cfg,ignore_mismatched_sizes=True,trust_remote_code=True)
111
+ arg=TrainingArguments(num_train_epochs=3,per_device_train_batch_size=1,dataloader_pin_memory=False,output_dir=tgt,overwrite_output_dir=True,save_total_limit=2,learning_rate=5e-05,warmup_ratio=0.1,save_safetensors=False)
112
+ trn=Trainer(args=arg,data_collator=DataCollatorForTokenClassification(tkz),model=mdl,train_dataset=trainDS)
113
+ trn.train()
114
+ trn.save_model(tgt)
115
+ tkz.save_pretrained(tgt)
116
+ os.system("cp -p ModernBERT-base/*.py "+tgt)
modeling_modernbert.py ADDED
@@ -0,0 +1,1351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
210
+ self, input_ids: torch.LongTensor = None, inputs_embeds: Optional[torch.Tensor] = None
211
+ ) -> torch.Tensor:
212
+ if inputs_embeds is not None:
213
+ hidden_states = self.drop(self.norm(inputs_embeds))
214
+ else:
215
+ hidden_states = (
216
+ self.compiled_embeddings(input_ids)
217
+ if self.config.reference_compile
218
+ else self.drop(self.norm(self.tok_embeddings(input_ids)))
219
+ )
220
+ return hidden_states
221
+
222
+
223
+ class ModernBertMLP(nn.Module):
224
+ """Applies the GLU at the end of each ModernBERT layer.
225
+
226
+ Compared to the default BERT architecture, this block replaces :class:`~transformers.model.bert.modeling_bert.BertIntermediate`
227
+ and :class:`~transformers.model.bert.modeling_bert.SelfOutput` with a single module that has similar functionality.
228
+ """
229
+
230
+ def __init__(self, config: ModernBertConfig):
231
+ super().__init__()
232
+ self.config = config
233
+ self.Wi = nn.Linear(config.hidden_size, int(config.intermediate_size) * 2, bias=config.mlp_bias)
234
+ self.act = ACT2FN[config.hidden_activation]
235
+ self.drop = nn.Dropout(config.mlp_dropout)
236
+ self.Wo = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.mlp_bias)
237
+
238
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
239
+ input, gate = self.Wi(hidden_states).chunk(2, dim=-1)
240
+ return self.Wo(self.drop(self.act(input) * gate))
241
+
242
+
243
+ class ModernBertRotaryEmbedding(nn.Module):
244
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
245
+ super().__init__()
246
+
247
+ self.dim = dim
248
+ self.max_position_embeddings = max_position_embeddings
249
+ self.base = base
250
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim))
251
+ self.register_buffer("inv_freq", tensor=inv_freq, persistent=False)
252
+
253
+ @torch.no_grad()
254
+ def forward(self, x, position_ids, seq_len=None):
255
+ # x: [bs, num_attention_heads, seq_len, head_size]
256
+ self.inv_freq.to(x.device)
257
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
258
+ position_ids_expanded = position_ids[:, None, :].float()
259
+ # Force float32 since bfloat16 loses precision on long contexts
260
+ # See https://github.com/huggingface/transformers/pull/29285
261
+ device_type = x.device.type
262
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
263
+ with torch.autocast(device_type=device_type, enabled=False):
264
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
265
+ emb = torch.cat((freqs, freqs), dim=-1)
266
+ cos = emb.cos()
267
+ sin = emb.sin()
268
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
269
+
270
+
271
+ def rotate_half(x):
272
+ """Rotates half the hidden dims of the input."""
273
+ x1 = x[..., : x.shape[-1] // 2]
274
+ x2 = x[..., x.shape[-1] // 2 :]
275
+ return torch.cat((-x2, x1), dim=-1)
276
+
277
+
278
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
279
+ """Applies Rotary Position Embedding to the query and key tensors.
280
+
281
+ Args:
282
+ q (`torch.Tensor`): The query tensor.
283
+ k (`torch.Tensor`): The key tensor.
284
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
285
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
286
+ position_ids (`torch.Tensor`, *optional*):
287
+ Deprecated and unused.
288
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
289
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
290
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
291
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
292
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
293
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
294
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
295
+ Returns:
296
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
297
+ """
298
+ cos = cos.unsqueeze(unsqueeze_dim)
299
+ sin = sin.unsqueeze(unsqueeze_dim)
300
+ q_embed = (q * cos) + (rotate_half(q) * sin)
301
+ k_embed = (k * cos) + (rotate_half(k) * sin)
302
+ return q_embed, k_embed
303
+
304
+
305
+ def eager_attention_forward(
306
+ module: "ModernBertAttention",
307
+ qkv: torch.Tensor,
308
+ attention_mask: torch.Tensor,
309
+ sliding_window_mask: torch.Tensor,
310
+ position_ids: Optional[torch.LongTensor],
311
+ local_attention: Tuple[int, int],
312
+ bs: int,
313
+ dim: int,
314
+ output_attentions: Optional[bool] = False,
315
+ **_kwargs,
316
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
317
+ # qkv: [batch_size, seqlen, 3, nheads, headdim]
318
+ cos, sin = module.rotary_emb(qkv, position_ids=position_ids)
319
+ query, key, value = qkv.transpose(3, 1).unbind(dim=2)
320
+ # query, key, value: [batch_size, heads, seq_len, head_dim]
321
+ query, key = apply_rotary_pos_emb(query, key, cos, sin)
322
+
323
+ scale = module.head_dim**-0.5
324
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scale
325
+
326
+ if local_attention != (-1, -1):
327
+ attention_mask = sliding_window_mask
328
+
329
+ attn_weights = attn_weights + attention_mask
330
+
331
+ # upcast attention to fp32
332
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
333
+ attn_weights = nn.functional.dropout(attn_weights, p=module.attention_dropout, training=module.training)
334
+ attn_output = torch.matmul(attn_weights, value)
335
+ attn_output = attn_output.transpose(1, 2).contiguous()
336
+ attn_output = attn_output.view(bs, -1, dim)
337
+ if output_attentions:
338
+ return (attn_output, attn_weights)
339
+ return (attn_output,)
340
+
341
+
342
+ def flash_attention_forward(
343
+ module: "ModernBertAttention",
344
+ qkv: torch.Tensor,
345
+ rotary_emb: ModernBertUnpaddedRotaryEmbedding,
346
+ cu_seqlens: torch.Tensor,
347
+ max_seqlen: int,
348
+ local_attention: Tuple[int, int],
349
+ bs: int,
350
+ dim: int,
351
+ target_dtype: torch.dtype = torch.bfloat16,
352
+ **_kwargs,
353
+ ) -> Tuple[torch.Tensor]:
354
+ # (total_seqlen, 3, nheads, headdim)
355
+ qkv = rotary_emb(qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen)
356
+
357
+ convert_dtype = qkv.dtype not in (torch.float16, torch.bfloat16)
358
+ if convert_dtype:
359
+ # FA2 implementation only supports fp16 and bf16. If FA2 is supported,
360
+ # bfloat16 must be supported as of FA2 2.5.7. (Turing GPUs not supported)
361
+ orig_dtype = qkv.dtype
362
+ qkv = qkv.to(target_dtype)
363
+
364
+ attn = flash_attn_varlen_qkvpacked_func(
365
+ qkv,
366
+ cu_seqlens=cu_seqlens,
367
+ max_seqlen=max_seqlen,
368
+ dropout_p=module.attention_dropout if module.training else 0.0,
369
+ deterministic=module.deterministic_flash_attn,
370
+ window_size=local_attention,
371
+ )
372
+ attn = attn.to(orig_dtype) # type: ignore
373
+ else:
374
+ attn = flash_attn_varlen_qkvpacked_func(
375
+ qkv,
376
+ cu_seqlens=cu_seqlens,
377
+ max_seqlen=max_seqlen,
378
+ dropout_p=module.attention_dropout if module.training else 0.0,
379
+ deterministic=module.deterministic_flash_attn,
380
+ window_size=local_attention,
381
+ )
382
+ return (attn.view(bs, dim),)
383
+
384
+
385
+ def sdpa_attention_forward(
386
+ module: "ModernBertAttention",
387
+ qkv: torch.Tensor,
388
+ attention_mask: torch.Tensor,
389
+ sliding_window_mask: torch.Tensor,
390
+ position_ids: Optional[torch.LongTensor],
391
+ local_attention: Tuple[int, int],
392
+ bs: int,
393
+ dim: int,
394
+ **_kwargs,
395
+ ) -> Tuple[torch.Tensor]:
396
+ # qkv: [batch_size, seqlen, 3, nheads, headdim]
397
+ cos, sin = module.rotary_emb(qkv, position_ids=position_ids)
398
+ query, key, value = qkv.transpose(3, 1).unbind(dim=2)
399
+ # query, key, value: [batch_size, heads, seq_len, head_dim]
400
+ query, key = apply_rotary_pos_emb(query, key, cos, sin)
401
+
402
+ if local_attention != (-1, -1):
403
+ attention_mask = sliding_window_mask
404
+
405
+ attn_output = (
406
+ F.scaled_dot_product_attention(
407
+ query,
408
+ key,
409
+ value,
410
+ dropout_p=module.attention_dropout if module.training else 0.0,
411
+ attn_mask=attention_mask,
412
+ )
413
+ .transpose(1, 2)
414
+ .contiguous()
415
+ )
416
+ attn_output = attn_output.view(bs, -1, dim)
417
+ return (attn_output,)
418
+
419
+
420
+ MODERNBERT_ATTENTION_FUNCTION = {
421
+ "flash_attention_2": flash_attention_forward,
422
+ "eager": eager_attention_forward,
423
+ "sdpa": sdpa_attention_forward,
424
+ }
425
+
426
+
427
+ class ModernBertAttention(nn.Module):
428
+ """Performs multi-headed self attention on a batch of unpadded sequences.
429
+
430
+ If Flash Attention 2 is installed, this module uses Flash Attention to improve throughput.
431
+ If Flash Attention 2 is not installed, the implementation will use PyTorch's SDPA kernel,
432
+ which requires padding and unpadding inputs, adding some overhead.
433
+
434
+ See `forward` method for additional details.
435
+ """
436
+
437
+ def __init__(self, config: ModernBertConfig, layer_id: Optional[int] = None):
438
+ super().__init__()
439
+ self.config = config
440
+ self.layer_id = layer_id
441
+
442
+ if config.hidden_size % config.num_attention_heads != 0:
443
+ raise ValueError(
444
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention heads ({config.num_attention_heads})"
445
+ )
446
+
447
+ self.attention_dropout = config.attention_dropout
448
+ self.deterministic_flash_attn = config.deterministic_flash_attn
449
+ self.num_heads = config.num_attention_heads
450
+ self.head_dim = config.hidden_size // config.num_attention_heads
451
+ self.all_head_size = self.head_dim * self.num_heads
452
+ self.Wqkv = nn.Linear(config.hidden_size, 3 * self.all_head_size, bias=config.attention_bias)
453
+
454
+ if layer_id % config.global_attn_every_n_layers != 0:
455
+ self.local_attention = (config.local_attention // 2, config.local_attention // 2)
456
+ else:
457
+ self.local_attention = (-1, -1)
458
+
459
+ rope_theta = config.global_rope_theta
460
+ max_position_embeddings = config.max_position_embeddings
461
+ if self.local_attention != (-1, -1):
462
+ if config.local_rope_theta is not None:
463
+ rope_theta = config.local_rope_theta
464
+ max_position_embeddings = config.local_attention
465
+
466
+ if config._attn_implementation == "flash_attention_2":
467
+ self.rotary_emb = ModernBertUnpaddedRotaryEmbedding(
468
+ dim=self.head_dim, max_seqlen=max_position_embeddings, base=rope_theta
469
+ )
470
+ else:
471
+ self.rotary_emb = ModernBertRotaryEmbedding(
472
+ dim=self.head_dim, max_position_embeddings=max_position_embeddings, base=rope_theta
473
+ )
474
+
475
+ self.Wo = nn.Linear(config.hidden_size, config.hidden_size, bias=config.attention_bias)
476
+ self.out_drop = nn.Dropout(config.attention_dropout) if config.attention_dropout > 0.0 else nn.Identity()
477
+ self.pruned_heads = set()
478
+
479
+ def forward(
480
+ self,
481
+ hidden_states: torch.Tensor,
482
+ output_attentions: Optional[bool] = False,
483
+ **kwargs,
484
+ ) -> torch.Tensor:
485
+ qkv = self.Wqkv(hidden_states)
486
+
487
+ bs = hidden_states.shape[0]
488
+ if self.config._attn_implementation == "flash_attention_2":
489
+ qkv = qkv.view(-1, 3, self.num_heads, self.head_dim)
490
+ else:
491
+ qkv = qkv.view(bs, -1, 3, self.num_heads, self.head_dim)
492
+
493
+ attn_outputs = MODERNBERT_ATTENTION_FUNCTION[self.config._attn_implementation](
494
+ self,
495
+ qkv=qkv,
496
+ rotary_emb=self.rotary_emb,
497
+ local_attention=self.local_attention,
498
+ bs=bs,
499
+ dim=self.all_head_size,
500
+ output_attentions=output_attentions,
501
+ **kwargs,
502
+ )
503
+ hidden_states = attn_outputs[0]
504
+ hidden_states = self.out_drop(self.Wo(hidden_states))
505
+
506
+ return (hidden_states,) + attn_outputs[1:] # add attentions if outputted
507
+
508
+
509
+ class ModernBertEncoderLayer(nn.Module):
510
+ def __init__(self, config: ModernBertConfig, layer_id: Optional[int] = None):
511
+ super().__init__()
512
+ self.config = config
513
+ if layer_id == 0:
514
+ self.attn_norm = nn.Identity()
515
+ else:
516
+ self.attn_norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias)
517
+ self.attn = ModernBertAttention(config=config, layer_id=layer_id)
518
+ self.mlp_norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias)
519
+ self.mlp = ModernBertMLP(config)
520
+
521
+ @torch.compile(dynamic=True)
522
+ def compiled_mlp(self, hidden_states: torch.Tensor) -> torch.Tensor:
523
+ return self.mlp(self.mlp_norm(hidden_states))
524
+
525
+ def forward(
526
+ self,
527
+ hidden_states: torch.Tensor,
528
+ attention_mask: Optional[torch.Tensor] = None,
529
+ sliding_window_mask: Optional[torch.Tensor] = None,
530
+ position_ids: Optional[torch.LongTensor] = None,
531
+ cu_seqlens: Optional[torch.Tensor] = None,
532
+ max_seqlen: Optional[int] = None,
533
+ output_attentions: Optional[bool] = False,
534
+ ) -> torch.Tensor:
535
+ attn_outputs = self.attn(
536
+ self.attn_norm(hidden_states),
537
+ attention_mask=attention_mask,
538
+ sliding_window_mask=sliding_window_mask,
539
+ position_ids=position_ids,
540
+ cu_seqlens=cu_seqlens,
541
+ max_seqlen=max_seqlen,
542
+ output_attentions=output_attentions,
543
+ )
544
+ hidden_states = hidden_states + attn_outputs[0]
545
+ mlp_output = (
546
+ self.compiled_mlp(hidden_states)
547
+ if self.config.reference_compile
548
+ else self.mlp(self.mlp_norm(hidden_states))
549
+ )
550
+ hidden_states = hidden_states + mlp_output
551
+
552
+ return (hidden_states,) + attn_outputs[1:] # add attentions if outputted
553
+
554
+
555
+ MODERNBERT_START_DOCSTRING = r"""
556
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
557
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
558
+ etc.)
559
+
560
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
561
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
562
+ and behavior.
563
+
564
+ Parameters:
565
+ config ([`ModernBertConfig`]):
566
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
567
+ load the weights associated with the model, only the configuration. Check out the
568
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
569
+ """
570
+
571
+
572
+ @add_start_docstrings(
573
+ "The bare ModernBert Model outputting raw hidden-states without any specific head on top.",
574
+ MODERNBERT_START_DOCSTRING,
575
+ )
576
+ class ModernBertPreTrainedModel(PreTrainedModel):
577
+ config_class = ModernBertConfig
578
+ base_model_prefix = "model"
579
+ supports_gradient_checkpointing = True
580
+ _no_split_modules = ["ModernBertEmbeddings", "ModernBertEncoderLayer"]
581
+ _supports_flash_attn_2 = True
582
+ _supports_sdpa = True
583
+ _supports_flex_attn = False
584
+
585
+ def _init_weights(self, module: nn.Module):
586
+ cutoff_factor = self.config.initializer_cutoff_factor
587
+ if cutoff_factor is None:
588
+ cutoff_factor = 3
589
+
590
+ def init_weight(module: nn.Module, std: float):
591
+ nn.init.trunc_normal_(
592
+ module.weight,
593
+ mean=0.0,
594
+ std=std,
595
+ a=-cutoff_factor * std,
596
+ b=cutoff_factor * std,
597
+ )
598
+
599
+ if isinstance(module, nn.Linear):
600
+ if module.bias is not None:
601
+ nn.init.zeros_(module.bias)
602
+
603
+ stds = {
604
+ "in": self.config.initializer_range,
605
+ "out": self.config.initializer_range / math.sqrt(2.0 * self.config.num_hidden_layers),
606
+ "embedding": self.config.initializer_range,
607
+ "final_out": self.config.hidden_size**-0.5,
608
+ }
609
+
610
+ if isinstance(module, ModernBertEmbeddings):
611
+ init_weight(module.tok_embeddings, stds["embedding"])
612
+ elif isinstance(module, ModernBertMLP):
613
+ init_weight(module.Wi, stds["in"])
614
+ init_weight(module.Wo, stds["out"])
615
+ elif isinstance(module, ModernBertAttention):
616
+ init_weight(module.Wqkv, stds["in"])
617
+ init_weight(module.Wo, stds["out"])
618
+ elif isinstance(module, ModernBertPredictionHead):
619
+ init_weight(module.dense, stds["out"])
620
+ elif isinstance(module, ModernBertForMaskedLM):
621
+ init_weight(module.decoder, stds["out"])
622
+ elif isinstance(module, (ModernBertForSequenceClassification, ModernBertForTokenClassification)):
623
+ init_weight(module.classifier, stds["final_out"])
624
+
625
+ @classmethod
626
+ def _autoset_attn_implementation(
627
+ cls,
628
+ config,
629
+ use_flash_attention_2: bool = False,
630
+ torch_dtype: Optional[torch.dtype] = None,
631
+ device_map: Optional[Union[str, Dict[str, int]]] = None,
632
+ check_device_map: bool = True,
633
+ ):
634
+ # If the user didn't specify anything, try to use flash_attention_2 if available.
635
+ # Otherwise we fall back to the default SDPA -> Eager from the super() method.
636
+ if config._attn_implementation_internal is None:
637
+ config._attn_implementation_internal = "flash_attention_2"
638
+ try:
639
+ return cls._check_and_enable_flash_attn_2(
640
+ config,
641
+ torch_dtype=torch_dtype,
642
+ device_map=device_map,
643
+ hard_check_only=False,
644
+ check_device_map=check_device_map,
645
+ )
646
+ except (ValueError, ImportError):
647
+ config._attn_implementation_internal = None
648
+ return super()._autoset_attn_implementation(
649
+ config,
650
+ use_flash_attention_2=use_flash_attention_2,
651
+ torch_dtype=torch_dtype,
652
+ device_map=device_map,
653
+ check_device_map=check_device_map,
654
+ )
655
+
656
+ def _maybe_set_compile(self):
657
+ if self.config.reference_compile is False:
658
+ return
659
+
660
+ if hasattr(self, "hf_device_map") and len(self.hf_device_map) > 1:
661
+ if self.config.reference_compile:
662
+ logger.warning_once(
663
+ "If `accelerate` split the model across devices, `torch.compile` will not work. "
664
+ "Falling back to non-compiled mode."
665
+ )
666
+ self.config.reference_compile = False
667
+
668
+ if self.device.type == "mps":
669
+ if self.config.reference_compile:
670
+ logger.warning_once(
671
+ "Compiling the model with `torch.compile` and using a `torch.mps` device is not supported. "
672
+ "Falling back to non-compiled mode."
673
+ )
674
+ self.config.reference_compile = False
675
+
676
+ if self.config.reference_compile is None:
677
+ self.config.reference_compile = is_triton_available()
678
+
679
+ def resize_token_embeddings(self, *args, **kwargs):
680
+ model_embeds = super().resize_token_embeddings(*args, **kwargs)
681
+
682
+ if self.config.reference_compile in {True, None}:
683
+ if self.config.reference_compile:
684
+ logger.warning_once(
685
+ "Resizing token embeddings with `torch.compile` is not supported. Falling back to non-compiled mode."
686
+ )
687
+ self.config.reference_compile = False
688
+
689
+ return model_embeds
690
+
691
+
692
+ def _unpad_modernbert_input(
693
+ inputs: torch.Tensor,
694
+ attention_mask: torch.Tensor,
695
+ position_ids: Optional[torch.Tensor] = None,
696
+ labels: Optional[torch.Tensor] = None,
697
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int, Optional[torch.Tensor], Optional[torch.Tensor]]:
698
+ """
699
+ Remove padding from input sequences.
700
+
701
+ Args:
702
+ inputs: (batch, seqlen, ...) or (batch, seqlen)
703
+ attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
704
+ position_ids: (batch, seqlen), int, position ids
705
+ labels: (batch, seqlen), int, labels
706
+
707
+ Returns:
708
+ unpadded_inputs: (total_nnz, ...), where total_nnz = number of tokens selected in attention_mask.
709
+ indices: (total_nnz)
710
+ cu_seqlens: (batch + 1), the cumulative sequence lengths
711
+ max_seqlen_in_batch: int
712
+ unpadded_position_ids: (total_nnz) or None
713
+ unpadded_labels: (total_nnz) or None
714
+ """
715
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
716
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
717
+ max_seqlen_in_batch = int(seqlens_in_batch.max().item())
718
+ cu_seqlens = torch.nn.functional.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
719
+
720
+ if inputs.dim() == 2:
721
+ unpadded_inputs = inputs.flatten()[indices]
722
+ else:
723
+ batch, seqlen, *rest = inputs.shape
724
+ shape = batch * seqlen
725
+ unpadded_inputs = inputs.view(shape, *rest)[indices]
726
+
727
+ unpadded_position_ids = position_ids.flatten()[indices] if position_ids is not None else None
728
+ unpadded_labels = labels.flatten()[indices] if labels is not None else None
729
+
730
+ return unpadded_inputs, indices, cu_seqlens, max_seqlen_in_batch, unpadded_position_ids, unpadded_labels
731
+
732
+
733
+ def _pad_modernbert_output(
734
+ inputs: torch.Tensor,
735
+ indices: torch.Tensor,
736
+ batch: int,
737
+ seqlen: int,
738
+ ) -> torch.Tensor:
739
+ """
740
+ Add padding to sequences.
741
+
742
+ Args:
743
+ inputs: (total_nnz, ...) or (total_nnz,), where total_nnz = number of tokens selected in attention_mask.
744
+ indices: (total_nnz)
745
+ batch: int, batch size
746
+ seqlen: int, max sequence length
747
+
748
+ Returns:
749
+ padded_inputs: (batch, seqlen, ...) or (batch, seqlen)
750
+ """
751
+ if inputs.dim() == 1:
752
+ output = torch.zeros(batch * seqlen, dtype=inputs.dtype, device=inputs.device)
753
+ output[indices] = inputs
754
+ padded_inputs = output.view(batch, seqlen)
755
+ else:
756
+ _, *rest = inputs.shape
757
+ output = torch.zeros(batch * seqlen, *rest, dtype=inputs.dtype, device=inputs.device)
758
+ output[indices] = inputs
759
+ padded_inputs = output.view(batch, seqlen, *rest)
760
+
761
+ return padded_inputs
762
+
763
+
764
+ MODERNBERT_INPUTS_DOCSTRING = r"""
765
+ Args:
766
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
767
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
768
+ it.
769
+
770
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
771
+ [`PreTrainedTokenizer.__call__`] for details.
772
+
773
+ [What are input IDs?](../glossary#input-ids)
774
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
775
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
776
+
777
+ - 1 for tokens that are **not masked**,
778
+ - 0 for tokens that are **masked**.
779
+
780
+ [What are attention masks?](../glossary#attention-mask)
781
+
782
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
783
+ [`PreTrainedTokenizer.__call__`] for details.
784
+
785
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
786
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
787
+ information on the default strategy.
788
+
789
+ - 1 indicates the head is **not masked**,
790
+ - 0 indicates the head is **masked**.
791
+ sliding_window_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
792
+ Mask to avoid performing attention on padding or far-away tokens. In ModernBert, only every few layers
793
+ perform global attention, while the rest perform local attention. This mask is used to avoid attending to
794
+ far-away tokens in the local attention layers.
795
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
796
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
797
+ config.n_positions - 1]`.
798
+
799
+ [What are position IDs?](../glossary#position-ids)
800
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
801
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
802
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
803
+ model's internal embedding lookup matrix.
804
+ indices (`torch.Tensor` of shape `(total_unpadded_tokens,)`, *optional*):
805
+ Indices of the non-padding tokens in the input sequence. Used for unpadding the output.
806
+ cu_seqlens (`torch.Tensor` of shape `(batch + 1,)`, *optional*):
807
+ Cumulative sequence lengths of the input sequences. Used to index the unpadded tensors.
808
+ max_seqlen (`int`, *optional*):
809
+ Maximum sequence length in the batch. Used to pad the output tensors.
810
+ batch_size (`int`, *optional*):
811
+ Batch size of the input sequences. Used to pad the output tensors.
812
+ seq_len (`int`, *optional*):
813
+ Sequence length of the input sequences. Used to pad the output tensors.
814
+ output_attentions (`bool`, *optional*):
815
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
816
+ tensors for more detail.
817
+ output_hidden_states (`bool`, *optional*):
818
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
819
+ more detail.
820
+ return_dict (`bool`, *optional*):
821
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
822
+ """
823
+
824
+
825
+ @add_start_docstrings(
826
+ "The bare ModernBert Model outputting raw hidden-states without any specific head on top.",
827
+ MODERNBERT_START_DOCSTRING,
828
+ )
829
+ class ModernBertModel(ModernBertPreTrainedModel):
830
+ def __init__(self, config: ModernBertConfig):
831
+ super().__init__(config)
832
+ self.config = config
833
+ self.embeddings = ModernBertEmbeddings(config)
834
+ self.layers = nn.ModuleList(
835
+ [ModernBertEncoderLayer(config, layer_id) for layer_id in range(config.num_hidden_layers)]
836
+ )
837
+ self.final_norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias)
838
+ self.gradient_checkpointing = False
839
+ self.post_init()
840
+
841
+ def get_input_embeddings(self):
842
+ return self.embeddings.tok_embeddings
843
+
844
+ def set_input_embeddings(self, value):
845
+ self.embeddings.tok_embeddings = value
846
+
847
+ @add_start_docstrings_to_model_forward(MODERNBERT_INPUTS_DOCSTRING)
848
+ @add_code_sample_docstrings(
849
+ checkpoint=_CHECKPOINT_FOR_DOC,
850
+ output_type=BaseModelOutput,
851
+ config_class=_CONFIG_FOR_DOC,
852
+ )
853
+ def forward(
854
+ self,
855
+ input_ids: Optional[torch.LongTensor] = None,
856
+ attention_mask: Optional[torch.Tensor] = None,
857
+ sliding_window_mask: Optional[torch.Tensor] = None,
858
+ position_ids: Optional[torch.LongTensor] = None,
859
+ inputs_embeds: Optional[torch.Tensor] = None,
860
+ indices: Optional[torch.Tensor] = None,
861
+ cu_seqlens: Optional[torch.Tensor] = None,
862
+ max_seqlen: Optional[int] = None,
863
+ batch_size: Optional[int] = None,
864
+ seq_len: Optional[int] = None,
865
+ output_attentions: Optional[bool] = None,
866
+ output_hidden_states: Optional[bool] = None,
867
+ return_dict: Optional[bool] = None,
868
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutput]:
869
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
870
+ output_hidden_states = (
871
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
872
+ )
873
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
874
+
875
+ if (input_ids is None) ^ (inputs_embeds is not None):
876
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
877
+
878
+ all_hidden_states = () if output_hidden_states else None
879
+ all_self_attentions = () if output_attentions else None
880
+
881
+ self._maybe_set_compile()
882
+
883
+ if input_ids is not None:
884
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
885
+
886
+ if batch_size is None and seq_len is None:
887
+ if inputs_embeds is not None:
888
+ batch_size, seq_len = inputs_embeds.shape[:2]
889
+ else:
890
+ batch_size, seq_len = input_ids.shape[:2]
891
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
892
+
893
+ if attention_mask is None:
894
+ attention_mask = torch.ones((batch_size, seq_len), device=device, dtype=torch.bool)
895
+
896
+ repad = False
897
+ if self.config._attn_implementation == "flash_attention_2":
898
+ if indices is None and cu_seqlens is None and max_seqlen is None:
899
+ repad = True
900
+ if inputs_embeds is None:
901
+ with torch.no_grad():
902
+ input_ids, indices, cu_seqlens, max_seqlen, *_ = _unpad_modernbert_input(
903
+ inputs=input_ids, attention_mask=attention_mask
904
+ )
905
+ else:
906
+ inputs_embeds, indices, cu_seqlens, max_seqlen, *_ = _unpad_modernbert_input(
907
+ inputs=inputs_embeds, attention_mask=attention_mask
908
+ )
909
+ else:
910
+ if position_ids is None:
911
+ position_ids = torch.arange(seq_len, device=device).unsqueeze(0)
912
+
913
+ attention_mask, sliding_window_mask = self._update_attention_mask(
914
+ attention_mask, output_attentions=output_attentions
915
+ )
916
+
917
+ hidden_states = self.embeddings(input_ids=input_ids, inputs_embeds=inputs_embeds)
918
+
919
+ for encoder_layer in self.layers:
920
+ if output_hidden_states:
921
+ all_hidden_states = all_hidden_states + (hidden_states,)
922
+
923
+ if self.gradient_checkpointing and self.training:
924
+ layer_outputs = self._gradient_checkpointing_func(
925
+ encoder_layer.__call__,
926
+ hidden_states,
927
+ attention_mask,
928
+ sliding_window_mask,
929
+ position_ids,
930
+ cu_seqlens,
931
+ max_seqlen,
932
+ output_attentions,
933
+ )
934
+ else:
935
+ layer_outputs = encoder_layer(
936
+ hidden_states,
937
+ attention_mask=attention_mask,
938
+ sliding_window_mask=sliding_window_mask,
939
+ position_ids=position_ids,
940
+ cu_seqlens=cu_seqlens,
941
+ max_seqlen=max_seqlen,
942
+ output_attentions=output_attentions,
943
+ )
944
+ hidden_states = layer_outputs[0]
945
+ if output_attentions and len(layer_outputs) > 1:
946
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
947
+
948
+ if output_hidden_states:
949
+ all_hidden_states = all_hidden_states + (hidden_states,)
950
+
951
+ hidden_states = self.final_norm(hidden_states)
952
+
953
+ if repad:
954
+ hidden_states = _pad_modernbert_output(
955
+ inputs=hidden_states, indices=indices, batch=batch_size, seqlen=seq_len
956
+ )
957
+ if all_hidden_states is not None:
958
+ all_hidden_states = tuple(
959
+ _pad_modernbert_output(inputs=hs, indices=indices, batch=batch_size, seqlen=seq_len)
960
+ for hs in all_hidden_states
961
+ )
962
+
963
+ if not return_dict:
964
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
965
+ return BaseModelOutput(
966
+ last_hidden_state=hidden_states,
967
+ hidden_states=all_hidden_states,
968
+ attentions=all_self_attentions,
969
+ )
970
+
971
+ def _update_attention_mask(self, attention_mask: torch.Tensor, output_attentions: bool) -> torch.Tensor:
972
+ if output_attentions:
973
+ if self.config._attn_implementation == "sdpa":
974
+ logger.warning_once(
975
+ "Outputting attentions is only supported with the 'eager' attention implementation, "
976
+ 'not with "sdpa". Falling back to `attn_implementation="eager"`.'
977
+ )
978
+ self.config._attn_implementation = "eager"
979
+ elif self.config._attn_implementation != "eager":
980
+ logger.warning_once(
981
+ "Outputting attentions is only supported with the eager attention implementation, "
982
+ f'not with {self.config._attn_implementation}. Consider setting `attn_implementation="eager"`.'
983
+ " Setting `output_attentions=False`."
984
+ )
985
+
986
+ global_attention_mask = _prepare_4d_attention_mask(attention_mask, self.dtype)
987
+
988
+ # Create position indices
989
+ rows = torch.arange(global_attention_mask.shape[2]).unsqueeze(0)
990
+ # Calculate distance between positions
991
+ distance = torch.abs(rows - rows.T)
992
+
993
+ # Create sliding window mask (1 for positions within window, 0 outside)
994
+ window_mask = (
995
+ (distance <= self.config.local_attention // 2).unsqueeze(0).unsqueeze(0).to(attention_mask.device)
996
+ )
997
+ # Combine with existing mask
998
+ sliding_window_mask = global_attention_mask.masked_fill(window_mask.logical_not(), torch.finfo(self.dtype).min)
999
+
1000
+ return global_attention_mask, sliding_window_mask
1001
+
1002
+
1003
+ class ModernBertPredictionHead(nn.Module):
1004
+ def __init__(self, config: ModernBertConfig):
1005
+ super().__init__()
1006
+ self.config = config
1007
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size, config.classifier_bias)
1008
+ self.act = ACT2FN[config.classifier_activation]
1009
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias)
1010
+
1011
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
1012
+ return self.norm(self.act(self.dense(hidden_states)))
1013
+
1014
+
1015
+ @add_start_docstrings(
1016
+ "The ModernBert Model with a decoder head on top that is used for masked language modeling.",
1017
+ MODERNBERT_START_DOCSTRING,
1018
+ )
1019
+ class ModernBertForMaskedLM(ModernBertPreTrainedModel):
1020
+ _tied_weights_keys = ["decoder.weight"]
1021
+
1022
+ def __init__(self, config: ModernBertConfig):
1023
+ super().__init__(config)
1024
+ self.config = config
1025
+ self.model = ModernBertModel(config)
1026
+ self.head = ModernBertPredictionHead(config)
1027
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=config.decoder_bias)
1028
+
1029
+ self.sparse_prediction = self.config.sparse_prediction
1030
+ self.sparse_pred_ignore_index = self.config.sparse_pred_ignore_index
1031
+
1032
+ # Initialize weights and apply final processing
1033
+ self.post_init()
1034
+
1035
+ def get_output_embeddings(self):
1036
+ return self.decoder
1037
+
1038
+ def set_output_embeddings(self, new_embeddings: nn.Linear):
1039
+ self.decoder = new_embeddings
1040
+
1041
+ @torch.compile(dynamic=True)
1042
+ def compiled_head(self, output: torch.Tensor) -> torch.Tensor:
1043
+ return self.decoder(self.head(output))
1044
+
1045
+ @add_start_docstrings_to_model_forward(MODERNBERT_INPUTS_DOCSTRING)
1046
+ @add_code_sample_docstrings(
1047
+ checkpoint=_CHECKPOINT_FOR_DOC,
1048
+ output_type=MaskedLMOutput,
1049
+ config_class=_CONFIG_FOR_DOC,
1050
+ )
1051
+ def forward(
1052
+ self,
1053
+ input_ids: Optional[torch.LongTensor] = None,
1054
+ attention_mask: Optional[torch.Tensor] = None,
1055
+ sliding_window_mask: Optional[torch.Tensor] = None,
1056
+ position_ids: Optional[torch.Tensor] = None,
1057
+ inputs_embeds: Optional[torch.Tensor] = None,
1058
+ labels: Optional[torch.Tensor] = None,
1059
+ indices: Optional[torch.Tensor] = None,
1060
+ cu_seqlens: Optional[torch.Tensor] = None,
1061
+ max_seqlen: Optional[int] = None,
1062
+ batch_size: Optional[int] = None,
1063
+ seq_len: Optional[int] = None,
1064
+ output_attentions: Optional[bool] = None,
1065
+ output_hidden_states: Optional[bool] = None,
1066
+ return_dict: Optional[bool] = None,
1067
+ **kwargs,
1068
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
1069
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1070
+ self._maybe_set_compile()
1071
+
1072
+ if self.config._attn_implementation == "flash_attention_2":
1073
+ if indices is None and cu_seqlens is None and max_seqlen is None:
1074
+ if batch_size is None and seq_len is None:
1075
+ if inputs_embeds is not None:
1076
+ batch_size, seq_len = inputs_embeds.shape[:2]
1077
+ else:
1078
+ batch_size, seq_len = input_ids.shape[:2]
1079
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1080
+
1081
+ if attention_mask is None:
1082
+ attention_mask = torch.ones((batch_size, seq_len), device=device, dtype=torch.bool)
1083
+
1084
+ if inputs_embeds is None:
1085
+ with torch.no_grad():
1086
+ input_ids, indices, cu_seqlens, max_seqlen, position_ids, labels = _unpad_modernbert_input(
1087
+ inputs=input_ids, attention_mask=attention_mask, position_ids=position_ids, labels=labels
1088
+ )
1089
+ else:
1090
+ inputs_embeds, indices, cu_seqlens, max_seqlen, position_ids, labels = _unpad_modernbert_input(
1091
+ inputs=inputs_embeds, attention_mask=attention_mask, position_ids=position_ids, labels=labels
1092
+ )
1093
+
1094
+ outputs = self.model(
1095
+ input_ids=input_ids,
1096
+ attention_mask=attention_mask,
1097
+ sliding_window_mask=sliding_window_mask,
1098
+ position_ids=position_ids,
1099
+ inputs_embeds=inputs_embeds,
1100
+ indices=indices,
1101
+ cu_seqlens=cu_seqlens,
1102
+ max_seqlen=max_seqlen,
1103
+ batch_size=batch_size,
1104
+ seq_len=seq_len,
1105
+ output_attentions=output_attentions,
1106
+ output_hidden_states=output_hidden_states,
1107
+ return_dict=return_dict,
1108
+ )
1109
+ last_hidden_state = outputs[0]
1110
+
1111
+ if self.sparse_prediction and labels is not None:
1112
+ # flatten labels and output first
1113
+ labels = labels.view(-1)
1114
+ last_hidden_state = last_hidden_state.view(labels.shape[0], -1)
1115
+
1116
+ # then filter out the non-masked tokens
1117
+ mask_tokens = labels != self.sparse_pred_ignore_index
1118
+ last_hidden_state = last_hidden_state[mask_tokens]
1119
+ labels = labels[mask_tokens]
1120
+
1121
+ logits = (
1122
+ self.compiled_head(last_hidden_state)
1123
+ if self.config.reference_compile
1124
+ else self.decoder(self.head(last_hidden_state))
1125
+ )
1126
+
1127
+ loss = None
1128
+ if labels is not None:
1129
+ loss = self.loss_function(logits, labels, vocab_size=self.config.vocab_size)
1130
+
1131
+ if self.config._attn_implementation == "flash_attention_2":
1132
+ with torch.no_grad():
1133
+ logits = _pad_modernbert_output(inputs=logits, indices=indices, batch=batch_size, seqlen=seq_len)
1134
+ if not return_dict:
1135
+ output = (logits,)
1136
+ return ((loss,) + output) if loss is not None else output
1137
+
1138
+ return MaskedLMOutput(
1139
+ loss=loss,
1140
+ logits=logits,
1141
+ hidden_states=outputs.hidden_states,
1142
+ attentions=outputs.attentions,
1143
+ )
1144
+
1145
+
1146
+ @add_start_docstrings(
1147
+ "The ModernBert Model with a sequence classification head on top that performs pooling.",
1148
+ MODERNBERT_START_DOCSTRING,
1149
+ )
1150
+ class ModernBertForSequenceClassification(ModernBertPreTrainedModel):
1151
+ def __init__(self, config: ModernBertConfig):
1152
+ super().__init__(config)
1153
+ self.num_labels = config.num_labels
1154
+ self.config = config
1155
+
1156
+ self.model = ModernBertModel(config)
1157
+ self.head = ModernBertPredictionHead(config)
1158
+ self.drop = torch.nn.Dropout(config.classifier_dropout)
1159
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1160
+
1161
+ # Initialize weights and apply final processing
1162
+ self.post_init()
1163
+
1164
+ @add_start_docstrings_to_model_forward(MODERNBERT_INPUTS_DOCSTRING)
1165
+ @add_code_sample_docstrings(
1166
+ checkpoint=_CHECKPOINT_FOR_DOC,
1167
+ output_type=SequenceClassifierOutput,
1168
+ config_class=_CONFIG_FOR_DOC,
1169
+ )
1170
+ def forward(
1171
+ self,
1172
+ input_ids: Optional[torch.LongTensor] = None,
1173
+ attention_mask: Optional[torch.Tensor] = None,
1174
+ sliding_window_mask: Optional[torch.Tensor] = None,
1175
+ position_ids: Optional[torch.Tensor] = None,
1176
+ inputs_embeds: Optional[torch.Tensor] = None,
1177
+ labels: Optional[torch.Tensor] = None,
1178
+ indices: Optional[torch.Tensor] = None,
1179
+ cu_seqlens: Optional[torch.Tensor] = None,
1180
+ max_seqlen: Optional[int] = None,
1181
+ batch_size: Optional[int] = None,
1182
+ seq_len: Optional[int] = None,
1183
+ output_attentions: Optional[bool] = None,
1184
+ output_hidden_states: Optional[bool] = None,
1185
+ return_dict: Optional[bool] = None,
1186
+ **kwargs,
1187
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1188
+ r"""
1189
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1190
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1191
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1192
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1193
+ """
1194
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1195
+ self._maybe_set_compile()
1196
+
1197
+ outputs = self.model(
1198
+ input_ids=input_ids,
1199
+ attention_mask=attention_mask,
1200
+ sliding_window_mask=sliding_window_mask,
1201
+ position_ids=position_ids,
1202
+ inputs_embeds=inputs_embeds,
1203
+ indices=indices,
1204
+ cu_seqlens=cu_seqlens,
1205
+ max_seqlen=max_seqlen,
1206
+ batch_size=batch_size,
1207
+ seq_len=seq_len,
1208
+ output_attentions=output_attentions,
1209
+ output_hidden_states=output_hidden_states,
1210
+ return_dict=return_dict,
1211
+ )
1212
+ last_hidden_state = outputs[0]
1213
+
1214
+ if self.config.classifier_pooling == "cls":
1215
+ last_hidden_state = last_hidden_state[:, 0]
1216
+ elif self.config.classifier_pooling == "mean":
1217
+ last_hidden_state = (last_hidden_state * attention_mask.unsqueeze(-1)).sum(dim=1) / attention_mask.sum(
1218
+ dim=1, keepdim=True
1219
+ )
1220
+
1221
+ pooled_output = self.head(last_hidden_state)
1222
+ pooled_output = self.drop(pooled_output)
1223
+ logits = self.classifier(pooled_output)
1224
+
1225
+ loss = None
1226
+ if labels is not None:
1227
+ if self.config.problem_type is None:
1228
+ if self.num_labels == 1:
1229
+ self.config.problem_type = "regression"
1230
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1231
+ self.config.problem_type = "single_label_classification"
1232
+ else:
1233
+ self.config.problem_type = "multi_label_classification"
1234
+
1235
+ if self.config.problem_type == "regression":
1236
+ loss_fct = MSELoss()
1237
+ if self.num_labels == 1:
1238
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1239
+ else:
1240
+ loss = loss_fct(logits, labels)
1241
+ elif self.config.problem_type == "single_label_classification":
1242
+ loss_fct = CrossEntropyLoss()
1243
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1244
+ elif self.config.problem_type == "multi_label_classification":
1245
+ loss_fct = BCEWithLogitsLoss()
1246
+ loss = loss_fct(logits, labels)
1247
+
1248
+ if not return_dict:
1249
+ output = (logits,)
1250
+ return ((loss,) + output) if loss is not None else output
1251
+
1252
+ return SequenceClassifierOutput(
1253
+ loss=loss,
1254
+ logits=logits,
1255
+ hidden_states=outputs.hidden_states,
1256
+ attentions=outputs.attentions,
1257
+ )
1258
+
1259
+
1260
+ @add_start_docstrings(
1261
+ "The ModernBert Model with a token classification head on top, e.g. for Named Entity Recognition (NER) tasks.",
1262
+ MODERNBERT_START_DOCSTRING,
1263
+ )
1264
+ class ModernBertForTokenClassification(ModernBertPreTrainedModel):
1265
+ def __init__(self, config: ModernBertConfig):
1266
+ super().__init__(config)
1267
+ self.num_labels = config.num_labels
1268
+
1269
+ self.model = ModernBertModel(config)
1270
+ self.head = ModernBertPredictionHead(config)
1271
+ self.drop = torch.nn.Dropout(config.classifier_dropout)
1272
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1273
+
1274
+ # Initialize weights and apply final processing
1275
+ self.post_init()
1276
+
1277
+ @add_start_docstrings_to_model_forward(MODERNBERT_INPUTS_DOCSTRING)
1278
+ @add_code_sample_docstrings(
1279
+ checkpoint=_CHECKPOINT_FOR_DOC,
1280
+ output_type=TokenClassifierOutput,
1281
+ config_class=_CONFIG_FOR_DOC,
1282
+ )
1283
+ def forward(
1284
+ self,
1285
+ input_ids: Optional[torch.LongTensor] = None,
1286
+ attention_mask: Optional[torch.Tensor] = None,
1287
+ sliding_window_mask: Optional[torch.Tensor] = None,
1288
+ position_ids: Optional[torch.Tensor] = None,
1289
+ inputs_embeds: Optional[torch.Tensor] = None,
1290
+ labels: Optional[torch.Tensor] = None,
1291
+ indices: Optional[torch.Tensor] = None,
1292
+ cu_seqlens: Optional[torch.Tensor] = None,
1293
+ max_seqlen: Optional[int] = None,
1294
+ batch_size: Optional[int] = None,
1295
+ seq_len: Optional[int] = None,
1296
+ output_attentions: Optional[bool] = None,
1297
+ output_hidden_states: Optional[bool] = None,
1298
+ return_dict: Optional[bool] = None,
1299
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1300
+ r"""
1301
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1302
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1303
+ """
1304
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1305
+ self._maybe_set_compile()
1306
+
1307
+ outputs = self.model(
1308
+ input_ids=input_ids,
1309
+ attention_mask=attention_mask,
1310
+ sliding_window_mask=sliding_window_mask,
1311
+ position_ids=position_ids,
1312
+ inputs_embeds=inputs_embeds,
1313
+ indices=indices,
1314
+ cu_seqlens=cu_seqlens,
1315
+ max_seqlen=max_seqlen,
1316
+ batch_size=batch_size,
1317
+ seq_len=seq_len,
1318
+ output_attentions=output_attentions,
1319
+ output_hidden_states=output_hidden_states,
1320
+ return_dict=return_dict,
1321
+ )
1322
+ last_hidden_state = outputs[0]
1323
+
1324
+ last_hidden_state = self.head(last_hidden_state)
1325
+ last_hidden_state = self.drop(last_hidden_state)
1326
+ logits = self.classifier(last_hidden_state)
1327
+
1328
+ loss = None
1329
+ if labels is not None:
1330
+ loss_fct = CrossEntropyLoss()
1331
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1332
+
1333
+ if not return_dict:
1334
+ output = (logits,) + outputs[1:]
1335
+ return ((loss,) + output) if loss is not None else output
1336
+
1337
+ return TokenClassifierOutput(
1338
+ loss=loss,
1339
+ logits=logits,
1340
+ hidden_states=outputs.hidden_states,
1341
+ attentions=outputs.attentions,
1342
+ )
1343
+
1344
+
1345
+ __all__ = [
1346
+ "ModernBertModel",
1347
+ "ModernBertPreTrainedModel",
1348
+ "ModernBertForMaskedLM",
1349
+ "ModernBertForSequenceClassification",
1350
+ "ModernBertForTokenClassification",
1351
+ ]
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5555664b43930eddfa78ccb8e036151dfaf38aa1f4d47ac9fdb50402721daf10
3
+ size 622968178
special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "mask_token": {
10
+ "content": "[MASK]",
11
+ "lstrip": true,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "sep_token": {
24
+ "content": "[SEP]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,945 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "|||IP_ADDRESS|||",
5
+ "lstrip": false,
6
+ "normalized": true,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": false
10
+ },
11
+ "1": {
12
+ "content": "<|padding|>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "50254": {
20
+ "content": " ",
21
+ "lstrip": false,
22
+ "normalized": true,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": false
26
+ },
27
+ "50255": {
28
+ "content": " ",
29
+ "lstrip": false,
30
+ "normalized": true,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": false
34
+ },
35
+ "50256": {
36
+ "content": " ",
37
+ "lstrip": false,
38
+ "normalized": true,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": false
42
+ },
43
+ "50257": {
44
+ "content": " ",
45
+ "lstrip": false,
46
+ "normalized": true,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": false
50
+ },
51
+ "50258": {
52
+ "content": " ",
53
+ "lstrip": false,
54
+ "normalized": true,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": false
58
+ },
59
+ "50259": {
60
+ "content": " ",
61
+ "lstrip": false,
62
+ "normalized": true,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": false
66
+ },
67
+ "50260": {
68
+ "content": " ",
69
+ "lstrip": false,
70
+ "normalized": true,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": false
74
+ },
75
+ "50261": {
76
+ "content": " ",
77
+ "lstrip": false,
78
+ "normalized": true,
79
+ "rstrip": false,
80
+ "single_word": false,
81
+ "special": false
82
+ },
83
+ "50262": {
84
+ "content": " ",
85
+ "lstrip": false,
86
+ "normalized": true,
87
+ "rstrip": false,
88
+ "single_word": false,
89
+ "special": false
90
+ },
91
+ "50263": {
92
+ "content": " ",
93
+ "lstrip": false,
94
+ "normalized": true,
95
+ "rstrip": false,
96
+ "single_word": false,
97
+ "special": false
98
+ },
99
+ "50264": {
100
+ "content": " ",
101
+ "lstrip": false,
102
+ "normalized": true,
103
+ "rstrip": false,
104
+ "single_word": false,
105
+ "special": false
106
+ },
107
+ "50265": {
108
+ "content": " ",
109
+ "lstrip": false,
110
+ "normalized": true,
111
+ "rstrip": false,
112
+ "single_word": false,
113
+ "special": false
114
+ },
115
+ "50266": {
116
+ "content": " ",
117
+ "lstrip": false,
118
+ "normalized": true,
119
+ "rstrip": false,
120
+ "single_word": false,
121
+ "special": false
122
+ },
123
+ "50267": {
124
+ "content": " ",
125
+ "lstrip": false,
126
+ "normalized": true,
127
+ "rstrip": false,
128
+ "single_word": false,
129
+ "special": false
130
+ },
131
+ "50268": {
132
+ "content": " ",
133
+ "lstrip": false,
134
+ "normalized": true,
135
+ "rstrip": false,
136
+ "single_word": false,
137
+ "special": false
138
+ },
139
+ "50269": {
140
+ "content": " ",
141
+ "lstrip": false,
142
+ "normalized": true,
143
+ "rstrip": false,
144
+ "single_word": false,
145
+ "special": false
146
+ },
147
+ "50270": {
148
+ "content": " ",
149
+ "lstrip": false,
150
+ "normalized": true,
151
+ "rstrip": false,
152
+ "single_word": false,
153
+ "special": false
154
+ },
155
+ "50271": {
156
+ "content": " ",
157
+ "lstrip": false,
158
+ "normalized": true,
159
+ "rstrip": false,
160
+ "single_word": false,
161
+ "special": false
162
+ },
163
+ "50272": {
164
+ "content": " ",
165
+ "lstrip": false,
166
+ "normalized": true,
167
+ "rstrip": false,
168
+ "single_word": false,
169
+ "special": false
170
+ },
171
+ "50273": {
172
+ "content": " ",
173
+ "lstrip": false,
174
+ "normalized": true,
175
+ "rstrip": false,
176
+ "single_word": false,
177
+ "special": false
178
+ },
179
+ "50274": {
180
+ "content": " ",
181
+ "lstrip": false,
182
+ "normalized": true,
183
+ "rstrip": false,
184
+ "single_word": false,
185
+ "special": false
186
+ },
187
+ "50275": {
188
+ "content": " ",
189
+ "lstrip": false,
190
+ "normalized": true,
191
+ "rstrip": false,
192
+ "single_word": false,
193
+ "special": false
194
+ },
195
+ "50276": {
196
+ "content": " ",
197
+ "lstrip": false,
198
+ "normalized": true,
199
+ "rstrip": false,
200
+ "single_word": false,
201
+ "special": false
202
+ },
203
+ "50277": {
204
+ "content": "|||EMAIL_ADDRESS|||",
205
+ "lstrip": false,
206
+ "normalized": true,
207
+ "rstrip": false,
208
+ "single_word": false,
209
+ "special": false
210
+ },
211
+ "50278": {
212
+ "content": "|||PHONE_NUMBER|||",
213
+ "lstrip": false,
214
+ "normalized": true,
215
+ "rstrip": false,
216
+ "single_word": false,
217
+ "special": false
218
+ },
219
+ "50279": {
220
+ "content": "<|endoftext|>",
221
+ "lstrip": false,
222
+ "normalized": false,
223
+ "rstrip": false,
224
+ "single_word": false,
225
+ "special": true
226
+ },
227
+ "50280": {
228
+ "content": "[UNK]",
229
+ "lstrip": false,
230
+ "normalized": false,
231
+ "rstrip": false,
232
+ "single_word": false,
233
+ "special": true
234
+ },
235
+ "50281": {
236
+ "content": "[CLS]",
237
+ "lstrip": false,
238
+ "normalized": false,
239
+ "rstrip": false,
240
+ "single_word": false,
241
+ "special": true
242
+ },
243
+ "50282": {
244
+ "content": "[SEP]",
245
+ "lstrip": false,
246
+ "normalized": false,
247
+ "rstrip": false,
248
+ "single_word": false,
249
+ "special": true
250
+ },
251
+ "50283": {
252
+ "content": "[PAD]",
253
+ "lstrip": false,
254
+ "normalized": false,
255
+ "rstrip": false,
256
+ "single_word": false,
257
+ "special": true
258
+ },
259
+ "50284": {
260
+ "content": "[MASK]",
261
+ "lstrip": true,
262
+ "normalized": false,
263
+ "rstrip": false,
264
+ "single_word": false,
265
+ "special": true
266
+ },
267
+ "50285": {
268
+ "content": "[unused0]",
269
+ "lstrip": false,
270
+ "normalized": true,
271
+ "rstrip": false,
272
+ "single_word": false,
273
+ "special": false
274
+ },
275
+ "50286": {
276
+ "content": "[unused1]",
277
+ "lstrip": false,
278
+ "normalized": true,
279
+ "rstrip": false,
280
+ "single_word": false,
281
+ "special": false
282
+ },
283
+ "50287": {
284
+ "content": "[unused2]",
285
+ "lstrip": false,
286
+ "normalized": true,
287
+ "rstrip": false,
288
+ "single_word": false,
289
+ "special": false
290
+ },
291
+ "50288": {
292
+ "content": "[unused3]",
293
+ "lstrip": false,
294
+ "normalized": true,
295
+ "rstrip": false,
296
+ "single_word": false,
297
+ "special": false
298
+ },
299
+ "50289": {
300
+ "content": "[unused4]",
301
+ "lstrip": false,
302
+ "normalized": true,
303
+ "rstrip": false,
304
+ "single_word": false,
305
+ "special": false
306
+ },
307
+ "50290": {
308
+ "content": "[unused5]",
309
+ "lstrip": false,
310
+ "normalized": true,
311
+ "rstrip": false,
312
+ "single_word": false,
313
+ "special": false
314
+ },
315
+ "50291": {
316
+ "content": "[unused6]",
317
+ "lstrip": false,
318
+ "normalized": true,
319
+ "rstrip": false,
320
+ "single_word": false,
321
+ "special": false
322
+ },
323
+ "50292": {
324
+ "content": "[unused7]",
325
+ "lstrip": false,
326
+ "normalized": true,
327
+ "rstrip": false,
328
+ "single_word": false,
329
+ "special": false
330
+ },
331
+ "50293": {
332
+ "content": "[unused8]",
333
+ "lstrip": false,
334
+ "normalized": true,
335
+ "rstrip": false,
336
+ "single_word": false,
337
+ "special": false
338
+ },
339
+ "50294": {
340
+ "content": "[unused9]",
341
+ "lstrip": false,
342
+ "normalized": true,
343
+ "rstrip": false,
344
+ "single_word": false,
345
+ "special": false
346
+ },
347
+ "50295": {
348
+ "content": "[unused10]",
349
+ "lstrip": false,
350
+ "normalized": true,
351
+ "rstrip": false,
352
+ "single_word": false,
353
+ "special": false
354
+ },
355
+ "50296": {
356
+ "content": "[unused11]",
357
+ "lstrip": false,
358
+ "normalized": true,
359
+ "rstrip": false,
360
+ "single_word": false,
361
+ "special": false
362
+ },
363
+ "50297": {
364
+ "content": "[unused12]",
365
+ "lstrip": false,
366
+ "normalized": true,
367
+ "rstrip": false,
368
+ "single_word": false,
369
+ "special": false
370
+ },
371
+ "50298": {
372
+ "content": "[unused13]",
373
+ "lstrip": false,
374
+ "normalized": true,
375
+ "rstrip": false,
376
+ "single_word": false,
377
+ "special": false
378
+ },
379
+ "50299": {
380
+ "content": "[unused14]",
381
+ "lstrip": false,
382
+ "normalized": true,
383
+ "rstrip": false,
384
+ "single_word": false,
385
+ "special": false
386
+ },
387
+ "50300": {
388
+ "content": "[unused15]",
389
+ "lstrip": false,
390
+ "normalized": true,
391
+ "rstrip": false,
392
+ "single_word": false,
393
+ "special": false
394
+ },
395
+ "50301": {
396
+ "content": "[unused16]",
397
+ "lstrip": false,
398
+ "normalized": true,
399
+ "rstrip": false,
400
+ "single_word": false,
401
+ "special": false
402
+ },
403
+ "50302": {
404
+ "content": "[unused17]",
405
+ "lstrip": false,
406
+ "normalized": true,
407
+ "rstrip": false,
408
+ "single_word": false,
409
+ "special": false
410
+ },
411
+ "50303": {
412
+ "content": "[unused18]",
413
+ "lstrip": false,
414
+ "normalized": true,
415
+ "rstrip": false,
416
+ "single_word": false,
417
+ "special": false
418
+ },
419
+ "50304": {
420
+ "content": "[unused19]",
421
+ "lstrip": false,
422
+ "normalized": true,
423
+ "rstrip": false,
424
+ "single_word": false,
425
+ "special": false
426
+ },
427
+ "50305": {
428
+ "content": "[unused20]",
429
+ "lstrip": false,
430
+ "normalized": true,
431
+ "rstrip": false,
432
+ "single_word": false,
433
+ "special": false
434
+ },
435
+ "50306": {
436
+ "content": "[unused21]",
437
+ "lstrip": false,
438
+ "normalized": true,
439
+ "rstrip": false,
440
+ "single_word": false,
441
+ "special": false
442
+ },
443
+ "50307": {
444
+ "content": "[unused22]",
445
+ "lstrip": false,
446
+ "normalized": true,
447
+ "rstrip": false,
448
+ "single_word": false,
449
+ "special": false
450
+ },
451
+ "50308": {
452
+ "content": "[unused23]",
453
+ "lstrip": false,
454
+ "normalized": true,
455
+ "rstrip": false,
456
+ "single_word": false,
457
+ "special": false
458
+ },
459
+ "50309": {
460
+ "content": "[unused24]",
461
+ "lstrip": false,
462
+ "normalized": true,
463
+ "rstrip": false,
464
+ "single_word": false,
465
+ "special": false
466
+ },
467
+ "50310": {
468
+ "content": "[unused25]",
469
+ "lstrip": false,
470
+ "normalized": true,
471
+ "rstrip": false,
472
+ "single_word": false,
473
+ "special": false
474
+ },
475
+ "50311": {
476
+ "content": "[unused26]",
477
+ "lstrip": false,
478
+ "normalized": true,
479
+ "rstrip": false,
480
+ "single_word": false,
481
+ "special": false
482
+ },
483
+ "50312": {
484
+ "content": "[unused27]",
485
+ "lstrip": false,
486
+ "normalized": true,
487
+ "rstrip": false,
488
+ "single_word": false,
489
+ "special": false
490
+ },
491
+ "50313": {
492
+ "content": "[unused28]",
493
+ "lstrip": false,
494
+ "normalized": true,
495
+ "rstrip": false,
496
+ "single_word": false,
497
+ "special": false
498
+ },
499
+ "50314": {
500
+ "content": "[unused29]",
501
+ "lstrip": false,
502
+ "normalized": true,
503
+ "rstrip": false,
504
+ "single_word": false,
505
+ "special": false
506
+ },
507
+ "50315": {
508
+ "content": "[unused30]",
509
+ "lstrip": false,
510
+ "normalized": true,
511
+ "rstrip": false,
512
+ "single_word": false,
513
+ "special": false
514
+ },
515
+ "50316": {
516
+ "content": "[unused31]",
517
+ "lstrip": false,
518
+ "normalized": true,
519
+ "rstrip": false,
520
+ "single_word": false,
521
+ "special": false
522
+ },
523
+ "50317": {
524
+ "content": "[unused32]",
525
+ "lstrip": false,
526
+ "normalized": true,
527
+ "rstrip": false,
528
+ "single_word": false,
529
+ "special": false
530
+ },
531
+ "50318": {
532
+ "content": "[unused33]",
533
+ "lstrip": false,
534
+ "normalized": true,
535
+ "rstrip": false,
536
+ "single_word": false,
537
+ "special": false
538
+ },
539
+ "50319": {
540
+ "content": "[unused34]",
541
+ "lstrip": false,
542
+ "normalized": true,
543
+ "rstrip": false,
544
+ "single_word": false,
545
+ "special": false
546
+ },
547
+ "50320": {
548
+ "content": "[unused35]",
549
+ "lstrip": false,
550
+ "normalized": true,
551
+ "rstrip": false,
552
+ "single_word": false,
553
+ "special": false
554
+ },
555
+ "50321": {
556
+ "content": "[unused36]",
557
+ "lstrip": false,
558
+ "normalized": true,
559
+ "rstrip": false,
560
+ "single_word": false,
561
+ "special": false
562
+ },
563
+ "50322": {
564
+ "content": "[unused37]",
565
+ "lstrip": false,
566
+ "normalized": true,
567
+ "rstrip": false,
568
+ "single_word": false,
569
+ "special": false
570
+ },
571
+ "50323": {
572
+ "content": "[unused38]",
573
+ "lstrip": false,
574
+ "normalized": true,
575
+ "rstrip": false,
576
+ "single_word": false,
577
+ "special": false
578
+ },
579
+ "50324": {
580
+ "content": "[unused39]",
581
+ "lstrip": false,
582
+ "normalized": true,
583
+ "rstrip": false,
584
+ "single_word": false,
585
+ "special": false
586
+ },
587
+ "50325": {
588
+ "content": "[unused40]",
589
+ "lstrip": false,
590
+ "normalized": true,
591
+ "rstrip": false,
592
+ "single_word": false,
593
+ "special": false
594
+ },
595
+ "50326": {
596
+ "content": "[unused41]",
597
+ "lstrip": false,
598
+ "normalized": true,
599
+ "rstrip": false,
600
+ "single_word": false,
601
+ "special": false
602
+ },
603
+ "50327": {
604
+ "content": "[unused42]",
605
+ "lstrip": false,
606
+ "normalized": true,
607
+ "rstrip": false,
608
+ "single_word": false,
609
+ "special": false
610
+ },
611
+ "50328": {
612
+ "content": "[unused43]",
613
+ "lstrip": false,
614
+ "normalized": true,
615
+ "rstrip": false,
616
+ "single_word": false,
617
+ "special": false
618
+ },
619
+ "50329": {
620
+ "content": "[unused44]",
621
+ "lstrip": false,
622
+ "normalized": true,
623
+ "rstrip": false,
624
+ "single_word": false,
625
+ "special": false
626
+ },
627
+ "50330": {
628
+ "content": "[unused45]",
629
+ "lstrip": false,
630
+ "normalized": true,
631
+ "rstrip": false,
632
+ "single_word": false,
633
+ "special": false
634
+ },
635
+ "50331": {
636
+ "content": "[unused46]",
637
+ "lstrip": false,
638
+ "normalized": true,
639
+ "rstrip": false,
640
+ "single_word": false,
641
+ "special": false
642
+ },
643
+ "50332": {
644
+ "content": "[unused47]",
645
+ "lstrip": false,
646
+ "normalized": true,
647
+ "rstrip": false,
648
+ "single_word": false,
649
+ "special": false
650
+ },
651
+ "50333": {
652
+ "content": "[unused48]",
653
+ "lstrip": false,
654
+ "normalized": true,
655
+ "rstrip": false,
656
+ "single_word": false,
657
+ "special": false
658
+ },
659
+ "50334": {
660
+ "content": "[unused49]",
661
+ "lstrip": false,
662
+ "normalized": true,
663
+ "rstrip": false,
664
+ "single_word": false,
665
+ "special": false
666
+ },
667
+ "50335": {
668
+ "content": "[unused50]",
669
+ "lstrip": false,
670
+ "normalized": true,
671
+ "rstrip": false,
672
+ "single_word": false,
673
+ "special": false
674
+ },
675
+ "50336": {
676
+ "content": "[unused51]",
677
+ "lstrip": false,
678
+ "normalized": true,
679
+ "rstrip": false,
680
+ "single_word": false,
681
+ "special": false
682
+ },
683
+ "50337": {
684
+ "content": "[unused52]",
685
+ "lstrip": false,
686
+ "normalized": true,
687
+ "rstrip": false,
688
+ "single_word": false,
689
+ "special": false
690
+ },
691
+ "50338": {
692
+ "content": "[unused53]",
693
+ "lstrip": false,
694
+ "normalized": true,
695
+ "rstrip": false,
696
+ "single_word": false,
697
+ "special": false
698
+ },
699
+ "50339": {
700
+ "content": "[unused54]",
701
+ "lstrip": false,
702
+ "normalized": true,
703
+ "rstrip": false,
704
+ "single_word": false,
705
+ "special": false
706
+ },
707
+ "50340": {
708
+ "content": "[unused55]",
709
+ "lstrip": false,
710
+ "normalized": true,
711
+ "rstrip": false,
712
+ "single_word": false,
713
+ "special": false
714
+ },
715
+ "50341": {
716
+ "content": "[unused56]",
717
+ "lstrip": false,
718
+ "normalized": true,
719
+ "rstrip": false,
720
+ "single_word": false,
721
+ "special": false
722
+ },
723
+ "50342": {
724
+ "content": "[unused57]",
725
+ "lstrip": false,
726
+ "normalized": true,
727
+ "rstrip": false,
728
+ "single_word": false,
729
+ "special": false
730
+ },
731
+ "50343": {
732
+ "content": "[unused58]",
733
+ "lstrip": false,
734
+ "normalized": true,
735
+ "rstrip": false,
736
+ "single_word": false,
737
+ "special": false
738
+ },
739
+ "50344": {
740
+ "content": "[unused59]",
741
+ "lstrip": false,
742
+ "normalized": true,
743
+ "rstrip": false,
744
+ "single_word": false,
745
+ "special": false
746
+ },
747
+ "50345": {
748
+ "content": "[unused60]",
749
+ "lstrip": false,
750
+ "normalized": true,
751
+ "rstrip": false,
752
+ "single_word": false,
753
+ "special": false
754
+ },
755
+ "50346": {
756
+ "content": "[unused61]",
757
+ "lstrip": false,
758
+ "normalized": true,
759
+ "rstrip": false,
760
+ "single_word": false,
761
+ "special": false
762
+ },
763
+ "50347": {
764
+ "content": "[unused62]",
765
+ "lstrip": false,
766
+ "normalized": true,
767
+ "rstrip": false,
768
+ "single_word": false,
769
+ "special": false
770
+ },
771
+ "50348": {
772
+ "content": "[unused63]",
773
+ "lstrip": false,
774
+ "normalized": true,
775
+ "rstrip": false,
776
+ "single_word": false,
777
+ "special": false
778
+ },
779
+ "50349": {
780
+ "content": "[unused64]",
781
+ "lstrip": false,
782
+ "normalized": true,
783
+ "rstrip": false,
784
+ "single_word": false,
785
+ "special": false
786
+ },
787
+ "50350": {
788
+ "content": "[unused65]",
789
+ "lstrip": false,
790
+ "normalized": true,
791
+ "rstrip": false,
792
+ "single_word": false,
793
+ "special": false
794
+ },
795
+ "50351": {
796
+ "content": "[unused66]",
797
+ "lstrip": false,
798
+ "normalized": true,
799
+ "rstrip": false,
800
+ "single_word": false,
801
+ "special": false
802
+ },
803
+ "50352": {
804
+ "content": "[unused67]",
805
+ "lstrip": false,
806
+ "normalized": true,
807
+ "rstrip": false,
808
+ "single_word": false,
809
+ "special": false
810
+ },
811
+ "50353": {
812
+ "content": "[unused68]",
813
+ "lstrip": false,
814
+ "normalized": true,
815
+ "rstrip": false,
816
+ "single_word": false,
817
+ "special": false
818
+ },
819
+ "50354": {
820
+ "content": "[unused69]",
821
+ "lstrip": false,
822
+ "normalized": true,
823
+ "rstrip": false,
824
+ "single_word": false,
825
+ "special": false
826
+ },
827
+ "50355": {
828
+ "content": "[unused70]",
829
+ "lstrip": false,
830
+ "normalized": true,
831
+ "rstrip": false,
832
+ "single_word": false,
833
+ "special": false
834
+ },
835
+ "50356": {
836
+ "content": "[unused71]",
837
+ "lstrip": false,
838
+ "normalized": true,
839
+ "rstrip": false,
840
+ "single_word": false,
841
+ "special": false
842
+ },
843
+ "50357": {
844
+ "content": "[unused72]",
845
+ "lstrip": false,
846
+ "normalized": true,
847
+ "rstrip": false,
848
+ "single_word": false,
849
+ "special": false
850
+ },
851
+ "50358": {
852
+ "content": "[unused73]",
853
+ "lstrip": false,
854
+ "normalized": true,
855
+ "rstrip": false,
856
+ "single_word": false,
857
+ "special": false
858
+ },
859
+ "50359": {
860
+ "content": "[unused74]",
861
+ "lstrip": false,
862
+ "normalized": true,
863
+ "rstrip": false,
864
+ "single_word": false,
865
+ "special": false
866
+ },
867
+ "50360": {
868
+ "content": "[unused75]",
869
+ "lstrip": false,
870
+ "normalized": true,
871
+ "rstrip": false,
872
+ "single_word": false,
873
+ "special": false
874
+ },
875
+ "50361": {
876
+ "content": "[unused76]",
877
+ "lstrip": false,
878
+ "normalized": true,
879
+ "rstrip": false,
880
+ "single_word": false,
881
+ "special": false
882
+ },
883
+ "50362": {
884
+ "content": "[unused77]",
885
+ "lstrip": false,
886
+ "normalized": true,
887
+ "rstrip": false,
888
+ "single_word": false,
889
+ "special": false
890
+ },
891
+ "50363": {
892
+ "content": "[unused78]",
893
+ "lstrip": false,
894
+ "normalized": true,
895
+ "rstrip": false,
896
+ "single_word": false,
897
+ "special": false
898
+ },
899
+ "50364": {
900
+ "content": "[unused79]",
901
+ "lstrip": false,
902
+ "normalized": true,
903
+ "rstrip": false,
904
+ "single_word": false,
905
+ "special": false
906
+ },
907
+ "50365": {
908
+ "content": "[unused80]",
909
+ "lstrip": false,
910
+ "normalized": true,
911
+ "rstrip": false,
912
+ "single_word": false,
913
+ "special": false
914
+ },
915
+ "50366": {
916
+ "content": "[unused81]",
917
+ "lstrip": false,
918
+ "normalized": true,
919
+ "rstrip": false,
920
+ "single_word": false,
921
+ "special": false
922
+ },
923
+ "50367": {
924
+ "content": "[unused82]",
925
+ "lstrip": false,
926
+ "normalized": true,
927
+ "rstrip": false,
928
+ "single_word": false,
929
+ "special": false
930
+ }
931
+ },
932
+ "clean_up_tokenization_spaces": true,
933
+ "cls_token": "[CLS]",
934
+ "extra_special_tokens": {},
935
+ "mask_token": "[MASK]",
936
+ "model_input_names": [
937
+ "input_ids",
938
+ "attention_mask"
939
+ ],
940
+ "model_max_length": 1000000000000000019884624838656,
941
+ "pad_token": "[PAD]",
942
+ "sep_token": "[SEP]",
943
+ "tokenizer_class": "PreTrainedTokenizerFast",
944
+ "unk_token": "[UNK]"
945
+ }
ud.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy
2
+ from transformers import TokenClassificationPipeline
3
+
4
+ class UniversalDependenciesPipeline(TokenClassificationPipeline):
5
+ def __init__(self,**kwargs):
6
+ super().__init__(**kwargs)
7
+ x=self.model.config.label2id
8
+ self.root=numpy.full((len(x)),numpy.nan)
9
+ self.left_arc=numpy.full((len(x)),numpy.nan)
10
+ self.right_arc=numpy.full((len(x)),numpy.nan)
11
+ for k,v in x.items():
12
+ if k.endswith("|root"):
13
+ self.root[v]=0
14
+ elif k.find("|l-")>0:
15
+ self.left_arc[v]=0
16
+ elif k.find("|r-")>0:
17
+ self.right_arc[v]=0
18
+ def check_model_type(self,supported_models):
19
+ pass
20
+ def postprocess(self,model_outputs,**kwargs):
21
+ import torch
22
+ if "logits" not in model_outputs:
23
+ return "".join(self.postprocess(x,**kwargs) for x in model_outputs)
24
+ m=model_outputs["logits"][0].cpu().numpy()
25
+ k=numpy.argmax(m,axis=1).tolist()
26
+ x=[self.model.config.id2label[i].split("|")[1]=="o" for i in k[1:-1]]
27
+ if len(x)<127:
28
+ x=[True]*len(x)
29
+ off=model_outputs["offset_mapping"][0].tolist()
30
+ v=model_outputs["input_ids"][0].tolist()
31
+ for i,(s,e) in reversed(list(enumerate(off))):
32
+ if s<e:
33
+ d=model_outputs["sentence"][s:e]
34
+ j=len(d)-len(d.lstrip())
35
+ if j>0:
36
+ d=d.lstrip()
37
+ off[i][0]+=j
38
+ j=len(d)-len(d.rstrip())
39
+ if j>0:
40
+ d=d.rstrip()
41
+ off[i][1]-=j
42
+ if d.strip()=="":
43
+ off.pop(i)
44
+ v.pop(i)
45
+ w=[self.tokenizer.cls_token_id]
46
+ for i,j in enumerate(x):
47
+ if j:
48
+ w+=v[i+1:]
49
+ with torch.no_grad():
50
+ e=self.model(input_ids=torch.tensor([w]).to(self.device))
51
+ m=e.logits[0].cpu().numpy()
52
+ w=len(v)-2
53
+ e=numpy.full((w,w,m.shape[-1]),m.min())
54
+ k=1
55
+ for i in range(w):
56
+ if x[i]:
57
+ e[i,i]=m[k]+self.root
58
+ k+=1
59
+ for j in range(1,w-i):
60
+ e[i+j,i]=m[k]+self.left_arc
61
+ e[i,i+j]=m[k]+self.right_arc
62
+ k+=1
63
+ k+=1
64
+ g=self.model.config.label2id["X|x|r-goeswith"]
65
+ r=numpy.tri(e.shape[0])
66
+ for i in range(e.shape[0]):
67
+ for j in range(i+2,e.shape[1]):
68
+ r[i,j]=r[i,j-1] if numpy.nanargmax(e[i,j-1])==g else 1
69
+ e[:,:,g]+=numpy.where(r==0,0,numpy.nan)
70
+ m,p=numpy.nanmax(e,axis=2),numpy.nanargmax(e,axis=2)
71
+ h=self.chu_liu_edmonds(m)
72
+ z=[i for i,j in enumerate(h) if i==j]
73
+ if len(z)>1:
74
+ k,h=z[numpy.nanargmax(m[z,z])],numpy.nanmin(m)-numpy.nanmax(m)
75
+ 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])]
76
+ h=self.chu_liu_edmonds(m)
77
+ v=[(s,e) for s,e in off if s<e]
78
+ q=[self.model.config.id2label[p[j,i]].split("|") for i,j in enumerate(h)]
79
+ if "aggregation_strategy" in kwargs and kwargs["aggregation_strategy"]!="none":
80
+ for i,j in reversed(list(enumerate(q[1:],1))):
81
+ if j[-1]=="r-goeswith" and set([t[-1] for t in q[h[i]+1:i+1]])=={"r-goeswith"}:
82
+ h=[b if i>b else b-1 for a,b in enumerate(h) if i!=a]
83
+ v[i-1]=(v[i-1][0],v.pop(i)[1])
84
+ q.pop(i)
85
+ elif v[i-1][1]>v[i][0]:
86
+ h=[b if i>b else b-1 for a,b in enumerate(h) if i!=a]
87
+ v[i-1]=(v[i-1][0],v.pop(i)[1])
88
+ q.pop(i)
89
+ t=model_outputs["sentence"].replace("\n"," ")
90
+ u="# text = "+t+"\n"
91
+ for i,(s,e) in enumerate(v):
92
+ u+="\t".join([str(i+1),t[s:e],"_",q[i][0],"_","_" if len(q[i])<4 else "|".join(q[i][2:-1]),str(0 if h[i]==i else h[i]+1),"root" if q[i][-1]=="root" else q[i][-1][2:],"_","_" if i+1<len(v) and e<v[i+1][0] else "SpaceAfter=No"])+"\n"
93
+ return u+"\n"
94
+ def chu_liu_edmonds(self,matrix):
95
+ import numpy
96
+ h=numpy.nanargmax(matrix,axis=0)
97
+ x=[-1 if i==j else j for i,j in enumerate(h)]
98
+ 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]]:
99
+ y=[]
100
+ while x!=y:
101
+ y=list(x)
102
+ for i,j in enumerate(x):
103
+ x[i]=b(x,i,j)
104
+ if max(x)<0:
105
+ return h
106
+ y,x=[i for i,j in enumerate(x) if j==max(x)],[i for i,j in enumerate(x) if j<max(x)]
107
+ z=matrix-numpy.nanmax(matrix,axis=0)
108
+ 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])]])
109
+ 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))]
110
+ h=[j if i in y else k[x.index(i)] for i,j in enumerate(h)]
111
+ i=y[numpy.nanargmax(z[x[k[-1]],y] if k[-1]<len(x) else z[y,y])]
112
+ h[i]=x[k[-1]] if k[-1]<len(x) else i
113
+ return h