Ahmet Yildirim commited on
Commit
e487faf
·
1 Parent(s): 4750f53

- Include norbert3-related code

Browse files
README.md CHANGED
@@ -125,6 +125,11 @@ humit_tagger.identify_language(["Jeg elsker snø.","Eg elskar snø."])
125
  humit_tagger.identify_language(input_directory = "path/to/input/directory")
126
  ```
127
 
 
 
 
 
 
128
 
129
  ## Cite us
130
 
 
125
  humit_tagger.identify_language(input_directory = "path/to/input/directory")
126
  ```
127
 
128
+ ## About the code in this repository
129
+
130
+ This repository not only publishes the models, but also includes code for the tagging to work.
131
+ Some parts of this code has been included directly from the [norbert3-large HuggingFace repository](https://huggingface.co/ltg/norbert3-large) licensed under Apache 2.0. This is acknowledged in the relevant files.
132
+
133
 
134
  ## Cite us
135
 
configuration_norbert.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The whole code is taken from
2
+ # https://huggingface.co/ltg/norbert3-large/blob/main/configuration_norbert.py
3
+ # which is distributed under Apache 2.0 license.
4
+
5
+ from transformers.configuration_utils import PretrainedConfig
6
+
7
+ class NorbertConfig(PretrainedConfig):
8
+ """Configuration class to store the configuration of a `NorbertModel`.
9
+ """
10
+ def __init__(
11
+ self,
12
+ vocab_size=50000,
13
+ attention_probs_dropout_prob=0.1,
14
+ hidden_dropout_prob=0.1,
15
+ hidden_size=768,
16
+ intermediate_size=2048,
17
+ max_position_embeddings=512,
18
+ position_bucket_size=32,
19
+ num_attention_heads=12,
20
+ num_hidden_layers=12,
21
+ layer_norm_eps=1.0e-7,
22
+ output_all_encoded_layers=True,
23
+ **kwargs,
24
+ ):
25
+ super().__init__(**kwargs)
26
+
27
+ self.vocab_size = vocab_size
28
+ self.hidden_size = hidden_size
29
+ self.num_hidden_layers = num_hidden_layers
30
+ self.num_attention_heads = num_attention_heads
31
+ self.intermediate_size = intermediate_size
32
+ self.hidden_dropout_prob = hidden_dropout_prob
33
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
34
+ self.max_position_embeddings = max_position_embeddings
35
+ self.output_all_encoded_layers = output_all_encoded_layers
36
+ self.position_bucket_size = position_bucket_size
37
+ self.layer_norm_eps = layer_norm_eps
38
+
modeling_humit_tagger.py CHANGED
@@ -43,32 +43,23 @@ class HumitTaggerModel(torch.nn.Module):
43
  spec.loader.exec_module(lemma_rules)
44
 
45
  # Download base_model files into cache
46
- base_config_file = hf_hub_download(repo_id=kwargs["this_model_config"]["base_model"], filename=kwargs["this_model_config"]["base_model_config_file"])
47
- base_model_file = hf_hub_download(repo_id=kwargs["this_model_config"]["base_model"], filename=kwargs["this_model_config"]["base_model_model_file"])
48
  base_model_config_json_file = hf_hub_download(repo_id=kwargs["this_model_config"]["base_model"], filename=kwargs["this_model_config"]["base_model_config_json_file"])
49
  fullformlist_file = hf_hub_download(repo_id=repo_name, filename=kwargs["this_model_config"]["fullformlist_file"])
50
 
51
- # Copy base model's configuration python file into our working directory
52
- config_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)) , os.path.basename(base_config_file))
53
- shutil.copyfile(base_config_file, config_file_path)
54
-
55
- # HACK: Modify base model main file since __init.py__ has already been read and the new file must not contain relative imports
56
- base_model_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)) , os.path.basename(base_model_file))
57
- with open(base_model_file, 'r') as file:
58
- file_content = file.read().replace("from .", "from ")
59
- with open(base_model_file_path, 'w') as file:
60
- file.write(file_content)
61
-
62
  # Register the new files:
63
  # First register the base model config file
64
- sys.path.append(os.path.dirname(config_file_path))
65
- spec = importlib.util.spec_from_file_location("base_config", config_file_path)
 
66
  base_config = importlib.util.module_from_spec(spec)
67
  sys.modules["base_config"] = base_config
68
  spec.loader.exec_module(base_config)
69
  # Then register the base model file
70
- sys.path.append(os.path.dirname(base_model_file_path))
71
- spec = importlib.util.spec_from_file_location("base_model", base_model_file_path)
 
72
  base_model = importlib.util.module_from_spec(spec)
73
  sys.modules["base_model"] = base_model
74
  spec.loader.exec_module(base_model)
 
43
  spec.loader.exec_module(lemma_rules)
44
 
45
  # Download base_model files into cache
46
+ base_config_file = hf_hub_download(repo_id=repo_name, filename=kwargs["this_model_config"]["base_model_config_file"])
47
+ base_model_file = hf_hub_download(repo_id=repo_name, filename=kwargs["this_model_config"]["base_model_model_file"])
48
  base_model_config_json_file = hf_hub_download(repo_id=kwargs["this_model_config"]["base_model"], filename=kwargs["this_model_config"]["base_model_config_json_file"])
49
  fullformlist_file = hf_hub_download(repo_id=repo_name, filename=kwargs["this_model_config"]["fullformlist_file"])
50
 
 
 
 
 
 
 
 
 
 
 
 
51
  # Register the new files:
52
  # First register the base model config file
53
+ sys.path.append(os.path.dirname(base_config_file))
54
+ spec = importlib.util.spec_from_file_location("base_config", base_config_file)
55
+
56
  base_config = importlib.util.module_from_spec(spec)
57
  sys.modules["base_config"] = base_config
58
  spec.loader.exec_module(base_config)
59
  # Then register the base model file
60
+ sys.path.append(os.path.dirname(base_model_file))
61
+ spec = importlib.util.spec_from_file_location("base_model", base_model_file)
62
+
63
  base_model = importlib.util.module_from_spec(spec)
64
  sys.modules["base_model"] = base_model
65
  spec.loader.exec_module(base_model)
modeling_norbert.py ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The whole code is taken from
2
+ # https://huggingface.co/ltg/norbert3-large/blob/a8ed9e21c5bc33c306d814b520c4373c7d29a469/modeling_norbert.py
3
+ # which is distributed under Apache 2.0 license.
4
+
5
+ import math
6
+ from typing import List, Optional, Tuple, Union
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from torch.utils import checkpoint
12
+
13
+ from configuration_norbert import NorbertConfig
14
+ from transformers.modeling_utils import PreTrainedModel
15
+ from transformers.modeling_outputs import (
16
+ MaskedLMOutput,
17
+ MultipleChoiceModelOutput,
18
+ QuestionAnsweringModelOutput,
19
+ SequenceClassifierOutput,
20
+ TokenClassifierOutput,
21
+ BaseModelOutput
22
+ )
23
+
24
+
25
+ class Encoder(nn.Module):
26
+ def __init__(self, config, activation_checkpointing=False):
27
+ super().__init__()
28
+ self.layers = nn.ModuleList([EncoderLayer(config) for _ in range(config.num_hidden_layers)])
29
+
30
+ for i, layer in enumerate(self.layers):
31
+ layer.mlp.mlp[1].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))
32
+ layer.mlp.mlp[-2].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))
33
+
34
+ self.activation_checkpointing = activation_checkpointing
35
+
36
+ def forward(self, hidden_states, attention_mask, relative_embedding):
37
+ hidden_states, attention_probs = [hidden_states], []
38
+
39
+ for layer in self.layers:
40
+ if self.activation_checkpointing:
41
+ hidden_state, attention_p = checkpoint.checkpoint(layer, hidden_states[-1], attention_mask, relative_embedding)
42
+ else:
43
+ hidden_state, attention_p = layer(hidden_states[-1], attention_mask, relative_embedding)
44
+
45
+ hidden_states.append(hidden_state)
46
+ attention_probs.append(attention_p)
47
+
48
+ return hidden_states, attention_probs
49
+
50
+
51
+ class MaskClassifier(nn.Module):
52
+ def __init__(self, config, subword_embedding):
53
+ super().__init__()
54
+ self.nonlinearity = nn.Sequential(
55
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
56
+ nn.Linear(config.hidden_size, config.hidden_size),
57
+ nn.GELU(),
58
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
59
+ nn.Dropout(config.hidden_dropout_prob),
60
+ nn.Linear(subword_embedding.size(1), subword_embedding.size(0))
61
+ )
62
+
63
+ def forward(self, x, masked_lm_labels=None):
64
+ if masked_lm_labels is not None:
65
+ x = torch.index_select(x.flatten(0, 1), 0, torch.nonzero(masked_lm_labels.flatten() != -100).squeeze())
66
+ x = self.nonlinearity(x)
67
+ return x
68
+
69
+
70
+ class EncoderLayer(nn.Module):
71
+ def __init__(self, config):
72
+ super().__init__()
73
+ self.attention = Attention(config)
74
+ self.mlp = FeedForward(config)
75
+
76
+ def forward(self, x, padding_mask, relative_embedding):
77
+ attention_output, attention_probs = self.attention(x, padding_mask, relative_embedding)
78
+ x = x + attention_output
79
+ x = x + self.mlp(x)
80
+ return x, attention_probs
81
+
82
+
83
+ class GeGLU(nn.Module):
84
+ def forward(self, x):
85
+ x, gate = x.chunk(2, dim=-1)
86
+ x = x * F.gelu(gate, approximate="tanh")
87
+ return x
88
+
89
+
90
+ class FeedForward(nn.Module):
91
+ def __init__(self, config):
92
+ super().__init__()
93
+ self.mlp = nn.Sequential(
94
+ nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False),
95
+ nn.Linear(config.hidden_size, 2*config.intermediate_size, bias=False),
96
+ GeGLU(),
97
+ nn.LayerNorm(config.intermediate_size, eps=config.layer_norm_eps, elementwise_affine=False),
98
+ nn.Linear(config.intermediate_size, config.hidden_size, bias=False),
99
+ nn.Dropout(config.hidden_dropout_prob)
100
+ )
101
+
102
+ def forward(self, x):
103
+ return self.mlp(x)
104
+
105
+
106
+ class Attention(nn.Module):
107
+ def __init__(self, config):
108
+ super().__init__()
109
+
110
+ self.config = config
111
+
112
+ if config.hidden_size % config.num_attention_heads != 0:
113
+ raise ValueError(f"The hidden size {config.hidden_size} is not a multiple of the number of attention heads {config.num_attention_heads}")
114
+
115
+ self.hidden_size = config.hidden_size
116
+ self.num_heads = config.num_attention_heads
117
+ self.head_size = config.hidden_size // config.num_attention_heads
118
+
119
+ self.in_proj_qk = nn.Linear(config.hidden_size, 2*config.hidden_size, bias=True)
120
+ self.in_proj_v = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
121
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
122
+
123
+ self.pre_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False)
124
+ self.post_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=True)
125
+
126
+ position_indices = torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(1) \
127
+ - torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(0)
128
+ position_indices = self.make_log_bucket_position(position_indices, config.position_bucket_size, config.max_position_embeddings)
129
+ position_indices = config.position_bucket_size - 1 + position_indices
130
+ self.register_buffer("position_indices", position_indices.contiguous(), persistent=False)
131
+
132
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
133
+ self.scale = 1.0 / math.sqrt(3 * self.head_size)
134
+
135
+ def make_log_bucket_position(self, relative_pos, bucket_size, max_position):
136
+ sign = torch.sign(relative_pos)
137
+ mid = bucket_size // 2
138
+ abs_pos = torch.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, torch.abs(relative_pos).clamp(max=max_position - 1))
139
+ log_pos = torch.ceil(torch.log(abs_pos / mid) / math.log((max_position-1) / mid) * (mid - 1)).int() + mid
140
+ bucket_pos = torch.where(abs_pos <= mid, relative_pos, log_pos * sign).long()
141
+ return bucket_pos
142
+
143
+ def forward(self, hidden_states, attention_mask, relative_embedding):
144
+ batch_size, key_len, _ = hidden_states.size()
145
+ query_len = key_len
146
+
147
+ # Recompute position_indices if sequence length exceeds the precomputed size
148
+ if self.position_indices.size(0) < query_len:
149
+ position_indices = torch.arange(query_len, dtype=torch.long).unsqueeze(1) \
150
+ - torch.arange(query_len, dtype=torch.long).unsqueeze(0)
151
+ position_indices = self.make_log_bucket_position(position_indices, self.config.position_bucket_size, 512)
152
+ position_indices = self.config.position_bucket_size - 1 + position_indices
153
+ self.position_indices = position_indices.to(hidden_states.device)
154
+
155
+ # Pre-LN and project query/key/value.
156
+ hidden_states = self.pre_layer_norm(hidden_states) # shape: [B, T, D]
157
+ query, key = self.in_proj_qk(hidden_states).chunk(2, dim=-1) # shape: [B, T, D]
158
+ value = self.in_proj_v(hidden_states) # shape: [B, T, D]
159
+
160
+ # Reshape to [B, num_heads, T, head_size]
161
+ query = query.view(batch_size, query_len, self.num_heads, self.head_size).transpose(1, 2) # shape: [B, num_heads, T_q, head_size]
162
+ key = key.view(batch_size, key_len, self.num_heads, self.head_size).permute(0, 2, 3, 1) # shape: [B, num_heads, head_size, T_k]
163
+ value = value.view(batch_size, key_len, self.num_heads, self.head_size).transpose(1, 2) # shape: [B, num_heads, T_k, head_size]
164
+
165
+ # Compute relative positional contributions
166
+ pos = self.in_proj_qk(self.dropout(relative_embedding)) # shape: [2*position_bucket_size - 1, 2D]
167
+ query_pos, key_pos = pos.view(-1, self.num_heads, 2*self.head_size).chunk(2, dim=2) # shape: [2*position_bucket_size - 1, num_heads, head_size]
168
+ query_pos = query_pos.transpose(0, 1) # shape: [num_heads, 2*position_bucket_size - 1, head_size]
169
+ key_pos = key_pos.permute(1, 2, 0) # shape: [num_heads, head_size, 2*position_bucket_size - 1]
170
+
171
+ # Scale the keys
172
+ key = key * self.scale
173
+ key_pos = key_pos * self.scale
174
+
175
+ # Compute standard content-to-content attention scores
176
+ attention_c_to_c = torch.matmul(query, key) # shape: [B, num_heads, T_q, T_k]
177
+
178
+ # Compute content-to-position and position-to-content attention scores
179
+ position_indices = self.position_indices[:query_len, :key_len].expand(batch_size, self.num_heads, -1, -1) # shape: [B, num_heads, T_q, T_k]
180
+ attention_c_to_p = torch.matmul(query, key_pos.unsqueeze(0)) # shape: [B, num_heads, T_q, 2*position_bucket_size - 1]
181
+ attention_p_to_c = torch.matmul(query_pos.unsqueeze(0), key) # shape: [B, num_heads, 2*position_bucket_size - 1, T_k]
182
+ attention_c_to_p = attention_c_to_p.gather(3, position_indices) # shape: [B, num_heads, T_q, T_k]
183
+ attention_p_to_c = attention_p_to_c.gather(2, position_indices) # shape: [B, num_heads, T_q, T_k]
184
+
185
+ # Full attention score
186
+ attention_scores = attention_c_to_c + attention_c_to_p + attention_p_to_c # shape: [B, num_heads, T_q, T_k]
187
+
188
+ # Masked softmax
189
+ attention_scores = attention_scores.masked_fill(attention_mask, float('-inf')) # shape: [B, num_heads, T_q, T_k]
190
+ attention_probs = F.softmax(attention_scores, dim=-1) # shape: [B, num_heads, T_q, T_k]
191
+
192
+ # Collect the weighted-averaged values
193
+ attention_probs = self.dropout(attention_probs) # shape: [B, num_heads, T_q, T_k]
194
+ output = torch.matmul(attention_probs, value) # shape: [B, num_heads, T_q, head_size]
195
+ output = output.transpose(1, 2).flatten(2, 3) # shape: [B, T_q, D]
196
+ output = self.out_proj(output)
197
+ output = self.post_layer_norm(output)
198
+ output = self.dropout(output)
199
+
200
+ return output, attention_probs.detach()
201
+
202
+
203
+ class Embedding(nn.Module):
204
+ def __init__(self, config):
205
+ super().__init__()
206
+ self.hidden_size = config.hidden_size
207
+
208
+ self.word_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
209
+ self.word_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False)
210
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
211
+
212
+ self.relative_embedding = nn.Parameter(torch.empty(2 * config.position_bucket_size - 1, config.hidden_size))
213
+ self.relative_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
214
+
215
+ def forward(self, input_ids):
216
+ word_embedding = self.dropout(self.word_layer_norm(self.word_embedding(input_ids)))
217
+ relative_embeddings = self.relative_layer_norm(self.relative_embedding)
218
+ return word_embedding, relative_embeddings
219
+
220
+
221
+ #
222
+ # HuggingFace wrappers
223
+ #
224
+
225
+ class NorbertPreTrainedModel(PreTrainedModel):
226
+ config_class = NorbertConfig
227
+ base_model_prefix = "norbert3"
228
+ supports_gradient_checkpointing = True
229
+
230
+ def _set_gradient_checkpointing(self, module, value=False):
231
+ if isinstance(module, Encoder):
232
+ module.activation_checkpointing = value
233
+
234
+ def _init_weights(self, module):
235
+ std = math.sqrt(2.0 / (5.0 * self.hidden_size))
236
+
237
+ if isinstance(module, nn.Linear):
238
+ nn.init.trunc_normal_(module.weight.data, mean=0.0, std=std, a=-2*std, b=2*std)
239
+ if module.bias is not None:
240
+ module.bias.data.zero_()
241
+ elif isinstance(module, nn.Embedding):
242
+ nn.init.trunc_normal_(module.weight.data, mean=0.0, std=std, a=-2*std, b=2*std)
243
+ elif isinstance(module, nn.LayerNorm):
244
+ module.bias.data.zero_()
245
+ module.weight.data.fill_(1.0)
246
+
247
+
248
+ class NorbertModel(NorbertPreTrainedModel):
249
+ def __init__(self, config, add_mlm_layer=False, gradient_checkpointing=False, **kwargs):
250
+ super().__init__(config, **kwargs)
251
+ self.config = config
252
+ self.hidden_size = config.hidden_size
253
+
254
+ self.embedding = Embedding(config)
255
+ self.transformer = Encoder(config, activation_checkpointing=gradient_checkpointing)
256
+ self.classifier = MaskClassifier(config, self.embedding.word_embedding.weight) if add_mlm_layer else None
257
+
258
+ def get_input_embeddings(self):
259
+ return self.embedding.word_embedding
260
+
261
+ def set_input_embeddings(self, value):
262
+ self.embedding.word_embedding = value
263
+
264
+ def get_contextualized_embeddings(
265
+ self,
266
+ input_ids: Optional[torch.Tensor] = None,
267
+ attention_mask: Optional[torch.Tensor] = None
268
+ ) -> List[torch.Tensor]:
269
+ if input_ids is not None:
270
+ input_shape = input_ids.size()
271
+ else:
272
+ raise ValueError("You have to specify input_ids")
273
+
274
+ batch_size, seq_length = input_shape
275
+ device = input_ids.device
276
+
277
+ if attention_mask is None:
278
+ attention_mask = torch.zeros(batch_size, seq_length, dtype=torch.bool, device=device)
279
+ else:
280
+ attention_mask = ~attention_mask.bool()
281
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
282
+
283
+ static_embeddings, relative_embedding = self.embedding(input_ids)
284
+ contextualized_embeddings, attention_probs = self.transformer(static_embeddings, attention_mask, relative_embedding)
285
+ last_layer = contextualized_embeddings[-1]
286
+ contextualized_embeddings = [contextualized_embeddings[0]] + [
287
+ contextualized_embeddings[i] - contextualized_embeddings[i - 1]
288
+ for i in range(1, len(contextualized_embeddings))
289
+ ]
290
+ return last_layer, contextualized_embeddings, attention_probs
291
+
292
+ def forward(
293
+ self,
294
+ input_ids: Optional[torch.Tensor] = None,
295
+ attention_mask: Optional[torch.Tensor] = None,
296
+ token_type_ids: Optional[torch.Tensor] = None,
297
+ position_ids: Optional[torch.Tensor] = None,
298
+ output_hidden_states: Optional[bool] = None,
299
+ output_attentions: Optional[bool] = None,
300
+ return_dict: Optional[bool] = None,
301
+ **kwargs
302
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutput]:
303
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
304
+
305
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
306
+
307
+ if not return_dict:
308
+ return (
309
+ sequence_output,
310
+ *([contextualized_embeddings] if output_hidden_states else []),
311
+ *([attention_probs] if output_attentions else [])
312
+ )
313
+
314
+ return BaseModelOutput(
315
+ last_hidden_state=sequence_output,
316
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
317
+ attentions=attention_probs if output_attentions else None
318
+ )
319
+
320
+
321
+ class NorbertForMaskedLM(NorbertModel):
322
+ _keys_to_ignore_on_load_unexpected = ["head"]
323
+
324
+ def __init__(self, config, **kwargs):
325
+ super().__init__(config, add_mlm_layer=True, **kwargs)
326
+
327
+ def get_output_embeddings(self):
328
+ return self.classifier.nonlinearity[-1].weight
329
+
330
+ def set_output_embeddings(self, new_embeddings):
331
+ self.classifier.nonlinearity[-1].weight = new_embeddings
332
+
333
+ def forward(
334
+ self,
335
+ input_ids: Optional[torch.Tensor] = None,
336
+ attention_mask: Optional[torch.Tensor] = None,
337
+ token_type_ids: Optional[torch.Tensor] = None,
338
+ position_ids: Optional[torch.Tensor] = None,
339
+ output_hidden_states: Optional[bool] = None,
340
+ output_attentions: Optional[bool] = None,
341
+ return_dict: Optional[bool] = None,
342
+ labels: Optional[torch.LongTensor] = None,
343
+ **kwargs
344
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
345
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
346
+
347
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
348
+ subword_prediction = self.classifier(sequence_output)
349
+ subword_prediction[:, :, :106+1] = float("-inf")
350
+
351
+ masked_lm_loss = None
352
+ if labels is not None:
353
+ masked_lm_loss = F.cross_entropy(subword_prediction.flatten(0, 1), labels.flatten())
354
+
355
+ if not return_dict:
356
+ output = (
357
+ subword_prediction,
358
+ *([contextualized_embeddings] if output_hidden_states else []),
359
+ *([attention_probs] if output_attentions else [])
360
+ )
361
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
362
+
363
+ return MaskedLMOutput(
364
+ loss=masked_lm_loss,
365
+ logits=subword_prediction,
366
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
367
+ attentions=attention_probs if output_attentions else None
368
+ )
369
+
370
+
371
+ class Classifier(nn.Module):
372
+ def __init__(self, config, num_labels: int):
373
+ super().__init__()
374
+
375
+ drop_out = getattr(config, "cls_dropout", None)
376
+ drop_out = config.hidden_dropout_prob if drop_out is None else drop_out
377
+
378
+ self.nonlinearity = nn.Sequential(
379
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
380
+ nn.Linear(config.hidden_size, config.hidden_size),
381
+ nn.GELU(),
382
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
383
+ nn.Dropout(drop_out),
384
+ nn.Linear(config.hidden_size, num_labels)
385
+ )
386
+
387
+ def forward(self, x):
388
+ x = self.nonlinearity(x)
389
+ return x
390
+
391
+
392
+ class NorbertForSequenceClassification(NorbertModel):
393
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
394
+
395
+ def __init__(self, config, **kwargs):
396
+ super().__init__(config, add_mlm_layer=False, **kwargs)
397
+
398
+ self.num_labels = config.num_labels
399
+ self.head = Classifier(config, self.num_labels)
400
+
401
+ def forward(
402
+ self,
403
+ input_ids: Optional[torch.Tensor] = None,
404
+ attention_mask: Optional[torch.Tensor] = None,
405
+ token_type_ids: Optional[torch.Tensor] = None,
406
+ position_ids: Optional[torch.Tensor] = None,
407
+ output_attentions: Optional[bool] = None,
408
+ output_hidden_states: Optional[bool] = None,
409
+ return_dict: Optional[bool] = None,
410
+ labels: Optional[torch.LongTensor] = None,
411
+ **kwargs
412
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
413
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
414
+
415
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
416
+ logits = self.head(sequence_output[:, 0, :])
417
+
418
+ loss = None
419
+ if labels is not None:
420
+ if self.config.problem_type is None:
421
+ if self.num_labels == 1:
422
+ self.config.problem_type = "regression"
423
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
424
+ self.config.problem_type = "single_label_classification"
425
+ else:
426
+ self.config.problem_type = "multi_label_classification"
427
+
428
+ if self.config.problem_type == "regression":
429
+ loss_fct = nn.MSELoss()
430
+ if self.num_labels == 1:
431
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
432
+ else:
433
+ loss = loss_fct(logits, labels)
434
+ elif self.config.problem_type == "single_label_classification":
435
+ loss_fct = nn.CrossEntropyLoss()
436
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
437
+ elif self.config.problem_type == "multi_label_classification":
438
+ loss_fct = nn.BCEWithLogitsLoss()
439
+ loss = loss_fct(logits, labels)
440
+
441
+ if not return_dict:
442
+ output = (
443
+ logits,
444
+ *([contextualized_embeddings] if output_hidden_states else []),
445
+ *([attention_probs] if output_attentions else [])
446
+ )
447
+ return ((loss,) + output) if loss is not None else output
448
+
449
+ return SequenceClassifierOutput(
450
+ loss=loss,
451
+ logits=logits,
452
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
453
+ attentions=attention_probs if output_attentions else None
454
+ )
455
+
456
+
457
+ class NorbertForTokenClassification(NorbertModel):
458
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
459
+
460
+ def __init__(self, config, **kwargs):
461
+ super().__init__(config, add_mlm_layer=False, **kwargs)
462
+
463
+ self.num_labels = config.num_labels
464
+ self.head = Classifier(config, self.num_labels)
465
+
466
+ def forward(
467
+ self,
468
+ input_ids: Optional[torch.Tensor] = None,
469
+ attention_mask: Optional[torch.Tensor] = None,
470
+ token_type_ids: Optional[torch.Tensor] = None,
471
+ position_ids: Optional[torch.Tensor] = None,
472
+ output_attentions: Optional[bool] = None,
473
+ output_hidden_states: Optional[bool] = None,
474
+ return_dict: Optional[bool] = None,
475
+ labels: Optional[torch.LongTensor] = None,
476
+ **kwargs
477
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
478
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
479
+
480
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
481
+ logits = self.head(sequence_output)
482
+
483
+ loss = None
484
+ if labels is not None:
485
+ loss_fct = nn.CrossEntropyLoss()
486
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
487
+
488
+ if not return_dict:
489
+ output = (
490
+ logits,
491
+ *([contextualized_embeddings] if output_hidden_states else []),
492
+ *([attention_probs] if output_attentions else [])
493
+ )
494
+ return ((loss,) + output) if loss is not None else output
495
+
496
+ return TokenClassifierOutput(
497
+ loss=loss,
498
+ logits=logits,
499
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
500
+ attentions=attention_probs if output_attentions else None
501
+ )
502
+
503
+
504
+ class NorbertForQuestionAnswering(NorbertModel):
505
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
506
+
507
+ def __init__(self, config, **kwargs):
508
+ super().__init__(config, add_mlm_layer=False, **kwargs)
509
+
510
+ self.num_labels = config.num_labels
511
+ self.head = Classifier(config, self.num_labels)
512
+
513
+ def forward(
514
+ self,
515
+ input_ids: Optional[torch.Tensor] = None,
516
+ attention_mask: Optional[torch.Tensor] = None,
517
+ token_type_ids: Optional[torch.Tensor] = None,
518
+ position_ids: Optional[torch.Tensor] = None,
519
+ output_attentions: Optional[bool] = None,
520
+ output_hidden_states: Optional[bool] = None,
521
+ return_dict: Optional[bool] = None,
522
+ start_positions: Optional[torch.Tensor] = None,
523
+ end_positions: Optional[torch.Tensor] = None,
524
+ **kwargs
525
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
526
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
527
+
528
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
529
+ logits = self.head(sequence_output)
530
+
531
+ start_logits, end_logits = logits.split(1, dim=-1)
532
+ start_logits = start_logits.squeeze(-1).contiguous()
533
+ end_logits = end_logits.squeeze(-1).contiguous()
534
+
535
+ total_loss = None
536
+ if start_positions is not None and end_positions is not None:
537
+ # If we are on multi-GPU, split add a dimension
538
+ if len(start_positions.size()) > 1:
539
+ start_positions = start_positions.squeeze(-1)
540
+ if len(end_positions.size()) > 1:
541
+ end_positions = end_positions.squeeze(-1)
542
+
543
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
544
+ ignored_index = start_logits.size(1)
545
+ start_positions = start_positions.clamp(0, ignored_index)
546
+ end_positions = end_positions.clamp(0, ignored_index)
547
+
548
+ loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
549
+ start_loss = loss_fct(start_logits, start_positions)
550
+ end_loss = loss_fct(end_logits, end_positions)
551
+ total_loss = (start_loss + end_loss) / 2
552
+
553
+ if not return_dict:
554
+ output = (
555
+ start_logits,
556
+ end_logits,
557
+ *([contextualized_embeddings] if output_hidden_states else []),
558
+ *([attention_probs] if output_attentions else [])
559
+ )
560
+ return ((total_loss,) + output) if total_loss is not None else output
561
+
562
+ return QuestionAnsweringModelOutput(
563
+ loss=total_loss,
564
+ start_logits=start_logits,
565
+ end_logits=end_logits,
566
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
567
+ attentions=attention_probs if output_attentions else None
568
+ )
569
+
570
+
571
+ class NorbertForMultipleChoice(NorbertModel):
572
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
573
+
574
+ def __init__(self, config, **kwargs):
575
+ super().__init__(config, add_mlm_layer=False, **kwargs)
576
+
577
+ self.num_labels = getattr(config, "num_labels", 2)
578
+ self.head = Classifier(config, self.num_labels)
579
+
580
+ def forward(
581
+ self,
582
+ input_ids: Optional[torch.Tensor] = None,
583
+ attention_mask: Optional[torch.Tensor] = None,
584
+ token_type_ids: Optional[torch.Tensor] = None,
585
+ position_ids: Optional[torch.Tensor] = None,
586
+ labels: Optional[torch.Tensor] = None,
587
+ output_attentions: Optional[bool] = None,
588
+ output_hidden_states: Optional[bool] = None,
589
+ return_dict: Optional[bool] = None,
590
+ **kwargs
591
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
592
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
593
+ num_choices = input_ids.shape[1]
594
+
595
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1))
596
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
597
+
598
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(flat_input_ids, flat_attention_mask)
599
+ logits = self.head(sequence_output)
600
+ reshaped_logits = logits.view(-1, num_choices)
601
+
602
+ loss = None
603
+ if labels is not None:
604
+ loss_fct = nn.CrossEntropyLoss()
605
+ loss = loss_fct(reshaped_logits, labels)
606
+
607
+ if not return_dict:
608
+ output = (
609
+ reshaped_logits,
610
+ *([contextualized_embeddings] if output_hidden_states else []),
611
+ *([attention_probs] if output_attentions else [])
612
+ )
613
+ return ((loss,) + output) if loss is not None else output
614
+
615
+ return MultipleChoiceModelOutput(
616
+ loss=loss,
617
+ logits=reshaped_logits,
618
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
619
+ attentions=attention_probs if output_attentions else None
620
+ )