babylm commited on
Commit
866bf5b
1 Parent(s): 9c1846e

Upload 7 files

Browse files
config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "ltg/ltg-bert-babylm",
3
+ "architectures": [
4
+ "LtgBertForMaskedLM"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_ltgbert.LtgBertConfig",
9
+ "AutoModelForMaskedLM": "modeling_ltgbert.LtgBertForMaskedLM",
10
+ "AutoModelForSequenceClassification": "modeling_ltgbert.LtgBertForSequenceClassification"
11
+ },
12
+ "classifier_dropout": 0.2,
13
+ "hidden_dropout_prob": 0.1,
14
+ "hidden_size": 768,
15
+ "intermediate_size": 2048,
16
+ "layer_norm_eps": 1e-07,
17
+ "max_position_embeddings": 512,
18
+ "model_type": "ltgbert",
19
+ "num_attention_heads": 12,
20
+ "num_hidden_layers": 12,
21
+ "output_all_encoded_layers": true,
22
+ "pad_token_id": 4,
23
+ "position_bucket_size": 32,
24
+ "torch_dtype": "float32",
25
+ "transformers_version": "4.40.2",
26
+ "vocab_size": 16384
27
+ }
configuration_ltgbert.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Language Technology Group from University of Oslo and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ LTG-BERT configutation """
17
+
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+
21
+
22
+ class LtgBertConfig(PretrainedConfig):
23
+ r"""
24
+ This is the configuration class to store the configuration of a [`LtgBertModel`]. It is used to
25
+ instantiate an LTG-BERT model according to the specified arguments, defining the model architecture.
26
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
27
+ documentation from [`PretrainedConfig`] for more information.
28
+ Args:
29
+ vocab_size (`int`, *optional*, defaults to 16384):
30
+ Vocabulary size of the LTG-BERT model. Defines the number of different tokens that can be represented by the
31
+ `inputs_ids` passed when calling [`LtgBertModel`].
32
+ hidden_size (`int`, *optional*, defaults to 768):
33
+ Dimensionality of the encoder layers and the pooler layer.
34
+ num_hidden_layers (`int`, *optional*, defaults to 12):
35
+ Number of hidden layers in the Transformer encoder.
36
+ num_attention_heads (`int`, *optional*, defaults to 12):
37
+ Number of attention heads for each attention layer in the Transformer encoder.
38
+ intermediate_size (`int`, *optional*, defaults to 2048):
39
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
40
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
41
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
42
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
43
+ The dropout ratio for the attention probabilities.
44
+ max_position_embeddings (`int`, *optional*, defaults to 512):
45
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
46
+ just in case (e.g., 512 or 1024 or 2048).
47
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
48
+ The epsilon used by the layer normalization layers.
49
+ classifier_dropout (`float`, *optional*):
50
+ The dropout ratio for the classification head.
51
+ """
52
+ model_type = "bert"
53
+ def __init__(
54
+ self,
55
+ vocab_size=16384,
56
+ attention_probs_dropout_prob=0.1,
57
+ hidden_dropout_prob=0.1,
58
+ hidden_size=768,
59
+ intermediate_size=2048,
60
+ max_position_embeddings=512,
61
+ position_bucket_size=32,
62
+ num_attention_heads=12,
63
+ num_hidden_layers=12,
64
+ layer_norm_eps=1.0e-7,
65
+ pad_token_id=4,
66
+ output_all_encoded_layers=True,
67
+ classifier_dropout=None,
68
+ **kwargs,
69
+ ):
70
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
71
+
72
+ self.vocab_size = vocab_size
73
+ self.hidden_size = hidden_size
74
+ self.num_hidden_layers = num_hidden_layers
75
+ self.num_attention_heads = num_attention_heads
76
+ self.intermediate_size = intermediate_size
77
+ self.hidden_dropout_prob = hidden_dropout_prob
78
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
79
+ self.max_position_embeddings = max_position_embeddings
80
+ self.output_all_encoded_layers = output_all_encoded_layers
81
+ self.position_bucket_size = position_bucket_size
82
+ self.layer_norm_eps = layer_norm_eps
83
+ self.classifier_dropout = classifier_dropout
modeling_ltgbert.py ADDED
@@ -0,0 +1,787 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Language Technology Group from University of Oslo and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ PyTorch LTG-BERT model."""
17
+
18
+
19
+ import math
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+ import torch.nn.functional as F
25
+ from torch.utils import checkpoint
26
+
27
+ from .configuration_ltgbert import LtgBertConfig
28
+ from transformers.modeling_utils import PreTrainedModel
29
+ from transformers.activations import gelu_new
30
+ from transformers.modeling_outputs import (
31
+ MaskedLMOutput,
32
+ MultipleChoiceModelOutput,
33
+ QuestionAnsweringModelOutput,
34
+ SequenceClassifierOutput,
35
+ TokenClassifierOutput,
36
+ BaseModelOutput
37
+ )
38
+ from transformers.pytorch_utils import softmax_backward_data
39
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward
40
+
41
+
42
+ _CHECKPOINT_FOR_DOC = "ltg/ltg-bert-bnc"
43
+ _CONFIG_FOR_DOC = "LtgBertConfig"
44
+
45
+
46
+ class Encoder(nn.Module):
47
+ def __init__(self, config, activation_checkpointing=False):
48
+ super().__init__()
49
+ self.layers = nn.ModuleList([EncoderLayer(config) for _ in range(config.num_hidden_layers)])
50
+
51
+ for i, layer in enumerate(self.layers):
52
+ layer.mlp.mlp[1].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))
53
+ layer.mlp.mlp[-2].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))
54
+
55
+ self.activation_checkpointing = activation_checkpointing
56
+
57
+ def forward(self, hidden_states, attention_mask, relative_embedding):
58
+ hidden_states, attention_probs = [hidden_states], []
59
+
60
+ for layer in self.layers:
61
+ if self.activation_checkpointing:
62
+ hidden_state, attention_p = checkpoint.checkpoint(layer, hidden_states[-1], attention_mask, relative_embedding)
63
+ else:
64
+ hidden_state, attention_p = layer(hidden_states[-1], attention_mask, relative_embedding)
65
+
66
+ hidden_states.append(hidden_state)
67
+ attention_probs.append(attention_p)
68
+
69
+ return hidden_states, attention_probs
70
+
71
+
72
+ class MaskClassifier(nn.Module):
73
+ def __init__(self, config, subword_embedding):
74
+ super().__init__()
75
+ self.nonlinearity = nn.Sequential(
76
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
77
+ nn.Linear(config.hidden_size, config.hidden_size),
78
+ nn.GELU(),
79
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
80
+ nn.Dropout(config.hidden_dropout_prob),
81
+ nn.Linear(subword_embedding.size(1), subword_embedding.size(0))
82
+ )
83
+ self.initialize(config.hidden_size, subword_embedding)
84
+
85
+ def initialize(self, hidden_size, embedding):
86
+ std = math.sqrt(2.0 / (5.0 * hidden_size))
87
+ nn.init.trunc_normal_(self.nonlinearity[1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
88
+ self.nonlinearity[-1].weight = embedding
89
+ self.nonlinearity[1].bias.data.zero_()
90
+ self.nonlinearity[-1].bias.data.zero_()
91
+
92
+ def forward(self, x, masked_lm_labels=None):
93
+ if masked_lm_labels is not None:
94
+ x = torch.index_select(x.flatten(0, 1), 0, torch.nonzero(masked_lm_labels.flatten() != -100).squeeze())
95
+ x = self.nonlinearity(x)
96
+ return x
97
+
98
+
99
+ class EncoderLayer(nn.Module):
100
+ def __init__(self, config):
101
+ super().__init__()
102
+ self.attention = Attention(config)
103
+ self.mlp = FeedForward(config)
104
+
105
+ def forward(self, x, padding_mask, relative_embedding):
106
+ attention_output, attention_probs = self.attention(x, padding_mask, relative_embedding)
107
+ x = x + attention_output
108
+ x = x + self.mlp(x)
109
+ return x, attention_probs
110
+
111
+
112
+ class GeGLU(nn.Module):
113
+ def forward(self, x):
114
+ x, gate = x.chunk(2, dim=-1)
115
+ x = x * gelu_new(gate)
116
+ return x
117
+
118
+
119
+ class FeedForward(nn.Module):
120
+ def __init__(self, config):
121
+ super().__init__()
122
+ self.mlp = nn.Sequential(
123
+ nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False),
124
+ nn.Linear(config.hidden_size, 2*config.intermediate_size, bias=False),
125
+ GeGLU(),
126
+ nn.LayerNorm(config.intermediate_size, eps=config.layer_norm_eps, elementwise_affine=False),
127
+ nn.Linear(config.intermediate_size, config.hidden_size, bias=False),
128
+ nn.Dropout(config.hidden_dropout_prob)
129
+ )
130
+ self.initialize(config.hidden_size)
131
+
132
+ def initialize(self, hidden_size):
133
+ std = math.sqrt(2.0 / (5.0 * hidden_size))
134
+ nn.init.trunc_normal_(self.mlp[1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
135
+ nn.init.trunc_normal_(self.mlp[-2].weight, mean=0.0, std=std, a=-2*std, b=2*std)
136
+
137
+ def forward(self, x):
138
+ return self.mlp(x)
139
+
140
+
141
+ class MaskedSoftmax(torch.autograd.Function):
142
+ @staticmethod
143
+ def forward(self, x, mask, dim):
144
+ self.dim = dim
145
+ x.masked_fill_(mask, float('-inf'))
146
+ x = torch.softmax(x, self.dim)
147
+ x.masked_fill_(mask, 0.0)
148
+ self.save_for_backward(x)
149
+ return x
150
+
151
+ @staticmethod
152
+ def backward(self, grad_output):
153
+ output, = self.saved_tensors
154
+ input_grad = softmax_backward_data(self, grad_output, output, self.dim, output)
155
+ return input_grad, None, None
156
+
157
+
158
+ class Attention(nn.Module):
159
+ def __init__(self, config):
160
+ super().__init__()
161
+
162
+ self.config = config
163
+
164
+ if config.hidden_size % config.num_attention_heads != 0:
165
+ raise ValueError(f"The hidden size {config.hidden_size} is not a multiple of the number of attention heads {config.num_attention_heads}")
166
+
167
+ self.hidden_size = config.hidden_size
168
+ self.num_heads = config.num_attention_heads
169
+ self.head_size = config.hidden_size // config.num_attention_heads
170
+
171
+ self.in_proj_qk = nn.Linear(config.hidden_size, 2*config.hidden_size, bias=True)
172
+ self.in_proj_v = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
173
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
174
+
175
+ self.pre_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False)
176
+ self.post_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=True)
177
+
178
+ position_indices = torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(1) \
179
+ - torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(0)
180
+ position_indices = self.make_log_bucket_position(position_indices, config.position_bucket_size, config.max_position_embeddings)
181
+ position_indices = config.position_bucket_size - 1 + position_indices
182
+ self.register_buffer("position_indices", position_indices, persistent=True)
183
+
184
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
185
+ self.scale = 1.0 / math.sqrt(3 * self.head_size)
186
+ self.initialize()
187
+
188
+ def make_log_bucket_position(self, relative_pos, bucket_size, max_position):
189
+ sign = torch.sign(relative_pos)
190
+ mid = bucket_size // 2
191
+ abs_pos = torch.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, torch.abs(relative_pos).clamp(max=max_position - 1))
192
+ log_pos = torch.ceil(torch.log(abs_pos / mid) / math.log((max_position-1) / mid) * (mid - 1)).int() + mid
193
+ bucket_pos = torch.where(abs_pos <= mid, relative_pos, log_pos * sign).long()
194
+ return bucket_pos
195
+
196
+ def initialize(self):
197
+ std = math.sqrt(2.0 / (5.0 * self.hidden_size))
198
+ nn.init.trunc_normal_(self.in_proj_qk.weight, mean=0.0, std=std, a=-2*std, b=2*std)
199
+ nn.init.trunc_normal_(self.in_proj_v.weight, mean=0.0, std=std, a=-2*std, b=2*std)
200
+ nn.init.trunc_normal_(self.out_proj.weight, mean=0.0, std=std, a=-2*std, b=2*std)
201
+ self.in_proj_qk.bias.data.zero_()
202
+ self.in_proj_v.bias.data.zero_()
203
+ self.out_proj.bias.data.zero_()
204
+
205
+ def compute_attention_scores(self, hidden_states, relative_embedding):
206
+ key_len, batch_size, _ = hidden_states.size()
207
+ query_len = key_len
208
+
209
+ if self.position_indices.size(0) < query_len:
210
+ position_indices = torch.arange(query_len, dtype=torch.long).unsqueeze(1) \
211
+ - torch.arange(query_len, dtype=torch.long).unsqueeze(0)
212
+ position_indices = self.make_log_bucket_position(position_indices, self.position_bucket_size, 512)
213
+ position_indices = self.position_bucket_size - 1 + position_indices
214
+ self.position_indices = position_indices.to(hidden_states.device)
215
+
216
+ hidden_states = self.pre_layer_norm(hidden_states)
217
+
218
+ query, key = self.in_proj_qk(hidden_states).chunk(2, dim=2) # shape: [T, B, D]
219
+ value = self.in_proj_v(hidden_states) # shape: [T, B, D]
220
+
221
+ query = query.reshape(query_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
222
+ key = key.reshape(key_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
223
+ value = value.view(key_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
224
+
225
+ attention_scores = torch.bmm(query, key.transpose(1, 2) * self.scale)
226
+
227
+ pos = self.in_proj_qk(self.dropout(relative_embedding)) # shape: [2T-1, 2D]
228
+ query_pos, key_pos = pos.view(-1, self.num_heads, 2*self.head_size).chunk(2, dim=2)
229
+ query = query.view(batch_size, self.num_heads, query_len, self.head_size)
230
+ key = key.view(batch_size, self.num_heads, query_len, self.head_size)
231
+
232
+ attention_c_p = torch.einsum("bhqd,khd->bhqk", query, key_pos.squeeze(1) * self.scale)
233
+ attention_p_c = torch.einsum("bhkd,qhd->bhqk", key * self.scale, query_pos.squeeze(1))
234
+
235
+ position_indices = self.position_indices[:query_len, :key_len].expand(batch_size, self.num_heads, -1, -1)
236
+ attention_c_p = attention_c_p.gather(3, position_indices)
237
+ attention_p_c = attention_p_c.gather(2, position_indices)
238
+
239
+ attention_scores = attention_scores.view(batch_size, self.num_heads, query_len, key_len)
240
+ attention_scores.add_(attention_c_p)
241
+ attention_scores.add_(attention_p_c)
242
+
243
+ return attention_scores, value
244
+
245
+ def compute_output(self, attention_probs, value):
246
+ attention_probs = self.dropout(attention_probs)
247
+ context = torch.bmm(attention_probs.flatten(0, 1), value) # shape: [B*H, Q, D]
248
+ context = context.transpose(0, 1).reshape(context.size(1), -1, self.hidden_size) # shape: [Q, B, H*D]
249
+ context = self.out_proj(context)
250
+ context = self.post_layer_norm(context)
251
+ context = self.dropout(context)
252
+ return context
253
+
254
+ def forward(self, hidden_states, attention_mask, relative_embedding):
255
+ attention_scores, value = self.compute_attention_scores(hidden_states, relative_embedding)
256
+ attention_probs = MaskedSoftmax.apply(attention_scores, attention_mask, -1)
257
+ return self.compute_output(attention_probs, value), attention_probs.detach()
258
+
259
+
260
+ class Embedding(nn.Module):
261
+ def __init__(self, config):
262
+ super().__init__()
263
+ self.hidden_size = config.hidden_size
264
+
265
+ self.word_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
266
+ self.word_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False)
267
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
268
+
269
+ self.relative_embedding = nn.Parameter(torch.empty(2 * config.position_bucket_size - 1, config.hidden_size))
270
+ self.relative_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
271
+
272
+ self.initialize()
273
+
274
+ def initialize(self):
275
+ std = math.sqrt(2.0 / (5.0 * self.hidden_size))
276
+ nn.init.trunc_normal_(self.relative_embedding, mean=0.0, std=std, a=-2*std, b=2*std)
277
+ nn.init.trunc_normal_(self.word_embedding.weight, mean=0.0, std=std, a=-2*std, b=2*std)
278
+
279
+ def forward(self, input_ids):
280
+ word_embedding = self.dropout(self.word_layer_norm(self.word_embedding(input_ids)))
281
+ relative_embeddings = self.relative_layer_norm(self.relative_embedding)
282
+ return word_embedding, relative_embeddings
283
+
284
+
285
+ #
286
+ # HuggingFace wrappers
287
+ #
288
+
289
+ class LtgBertPreTrainedModel(PreTrainedModel):
290
+ """
291
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
292
+ models.
293
+ """
294
+
295
+ config_class = LtgBertConfig
296
+ base_model_prefix = "bnc-bert"
297
+ supports_gradient_checkpointing = True
298
+
299
+ def _set_gradient_checkpointing(self, module, value=False):
300
+ if isinstance(module, Encoder):
301
+ module.activation_checkpointing = value
302
+
303
+ def _init_weights(self, _):
304
+ pass # everything is already initialized
305
+
306
+
307
+ LTG_BERT_START_DOCSTRING = r"""
308
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
309
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
310
+ etc.)
311
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
312
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
313
+ and behavior.
314
+ Parameters:
315
+ config ([`LtgBertConfig`]): Model configuration class with all the parameters of the model.
316
+ Initializing with a config file does not load the weights associated with the model, only the
317
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
318
+ """
319
+
320
+ LTG_BERT_INPUTS_DOCSTRING = r"""
321
+ Args:
322
+ input_ids (`torch.LongTensor` of shape `({0})`):
323
+ Indices of input sequence tokens in the vocabulary.
324
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
325
+ [`PreTrainedTokenizer.__call__`] for details.
326
+ [What are input IDs?](../glossary#input-ids)
327
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
328
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
329
+ - 1 for tokens that are **not masked**,
330
+ - 0 for tokens that are **masked**.
331
+ [What are attention masks?](../glossary#attention-mask)
332
+ output_hidden_states (`bool`, *optional*):
333
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
334
+ more detail.
335
+ output_attentions (`bool`, *optional*):
336
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
337
+ tensors for more detail.
338
+ return_dict (`bool`, *optional*):
339
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
340
+ """
341
+
342
+
343
+ @add_start_docstrings(
344
+ "The bare LTG-BERT transformer outputting raw hidden-states without any specific head on top.",
345
+ LTG_BERT_START_DOCSTRING,
346
+ )
347
+ class LtgBertModel(LtgBertPreTrainedModel):
348
+ def __init__(self, config, add_mlm_layer=False):
349
+ super().__init__(config)
350
+ self.config = config
351
+
352
+ self.embedding = Embedding(config)
353
+ self.transformer = Encoder(config, activation_checkpointing=False)
354
+ self.classifier = MaskClassifier(config, self.embedding.word_embedding.weight) if add_mlm_layer else None
355
+
356
+ def get_input_embeddings(self):
357
+ return self.embedding.word_embedding
358
+
359
+ def set_input_embeddings(self, value):
360
+ self.embedding.word_embedding = value
361
+
362
+ def get_contextualized_embeddings(
363
+ self,
364
+ input_ids: Optional[torch.Tensor] = None,
365
+ inputs_embeds: Optional[torch.Tensor] = None,
366
+ attention_mask: Optional[torch.Tensor] = None
367
+ ) -> List[torch.Tensor]:
368
+ if input_ids is not None:
369
+ input_shape = input_ids.size()
370
+ # elif inputs_embeds is not None:
371
+ # input_shape = inputs_embeds.size()[:-1]
372
+ else:
373
+ raise ValueError("You have to specify input_ids")
374
+
375
+ batch_size, seq_length = input_shape
376
+ device = input_ids.device
377
+
378
+ if attention_mask is None:
379
+ attention_mask = torch.zeros(batch_size, seq_length, dtype=torch.bool, device=device)
380
+ else:
381
+ attention_mask = ~attention_mask.bool()
382
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
383
+
384
+ # if inputs_embeds is None:
385
+ # static_embeddings, relative_embedding = self.embedding(input_ids.t())
386
+ static_embeddings, relative_embedding = self.embedding(input_ids.t())
387
+ contextualized_embeddings, attention_probs = self.transformer(static_embeddings, attention_mask, relative_embedding)
388
+ contextualized_embeddings = [e.transpose(0, 1) for e in contextualized_embeddings]
389
+ last_layer = contextualized_embeddings[-1]
390
+ contextualized_embeddings = [contextualized_embeddings[0]] + [
391
+ contextualized_embeddings[i] - contextualized_embeddings[i - 1]
392
+ for i in range(1, len(contextualized_embeddings))
393
+ ]
394
+ return last_layer, contextualized_embeddings, attention_probs
395
+
396
+ @add_start_docstrings_to_model_forward(LTG_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
397
+ def forward(
398
+ self,
399
+ input_ids: Optional[torch.Tensor] = None,
400
+ attention_mask: Optional[torch.Tensor] = None,
401
+ output_hidden_states: Optional[bool] = None,
402
+ output_attentions: Optional[bool] = None,
403
+ return_dict: Optional[bool] = None,
404
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutput]:
405
+
406
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
407
+ output_hidden_states = (
408
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
409
+ )
410
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
411
+
412
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
413
+
414
+ if not return_dict:
415
+ return (
416
+ sequence_output,
417
+ *([contextualized_embeddings] if output_hidden_states else []),
418
+ *([attention_probs] if output_attentions else [])
419
+ )
420
+
421
+ return BaseModelOutput(
422
+ last_hidden_state=sequence_output,
423
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
424
+ attentions=attention_probs if output_attentions else None
425
+ )
426
+
427
+
428
+ @add_start_docstrings("""LTG-BERT model with a `language modeling` head on top.""", LTG_BERT_START_DOCSTRING)
429
+ class LtgBertForMaskedLM(LtgBertModel):
430
+ _keys_to_ignore_on_load_unexpected = ["head"]
431
+
432
+ def __init__(self, config):
433
+ super().__init__(config, add_mlm_layer=True)
434
+
435
+ def get_output_embeddings(self):
436
+ return self.classifier.nonlinearity[-1].weight
437
+
438
+ def set_output_embeddings(self, new_embeddings):
439
+ self.classifier.nonlinearity[-1].weight = new_embeddings
440
+
441
+ @add_start_docstrings_to_model_forward(LTG_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
442
+ def forward(
443
+ self,
444
+ input_ids: Optional[torch.Tensor] = None,
445
+ attention_mask: Optional[torch.Tensor] = None,
446
+ output_hidden_states: Optional[bool] = None,
447
+ output_attentions: Optional[bool] = None,
448
+ return_dict: Optional[bool] = None,
449
+ labels: Optional[torch.LongTensor] = None,
450
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
451
+ r"""
452
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
453
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
454
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
455
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
456
+ """
457
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
458
+
459
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
460
+ subword_prediction = self.classifier(sequence_output)
461
+
462
+ masked_lm_loss = None
463
+ if labels is not None:
464
+ masked_lm_loss = F.cross_entropy(subword_prediction.flatten(0, 1), labels.flatten())
465
+
466
+ if not return_dict:
467
+ output = (
468
+ subword_prediction,
469
+ *([contextualized_embeddings] if output_hidden_states else []),
470
+ *([attention_probs] if output_attentions else [])
471
+ )
472
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
473
+
474
+ return MaskedLMOutput(
475
+ loss=masked_lm_loss,
476
+ logits=subword_prediction,
477
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
478
+ attentions=attention_probs if output_attentions else None
479
+ )
480
+
481
+
482
+ class Classifier(nn.Module):
483
+ def __init__(self, config, num_labels: int):
484
+ super().__init__()
485
+
486
+ drop_out = getattr(config, "classifier_dropout", config.hidden_dropout_prob)
487
+
488
+ self.nonlinearity = nn.Sequential(
489
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
490
+ nn.Linear(config.hidden_size, config.hidden_size),
491
+ nn.GELU(),
492
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
493
+ nn.Dropout(drop_out),
494
+ nn.Linear(config.hidden_size, num_labels)
495
+ )
496
+ self.initialize(config.hidden_size)
497
+
498
+ def initialize(self, hidden_size):
499
+ std = math.sqrt(2.0 / (5.0 * hidden_size))
500
+ nn.init.trunc_normal_(self.nonlinearity[1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
501
+ nn.init.trunc_normal_(self.nonlinearity[-1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
502
+ self.nonlinearity[1].bias.data.zero_()
503
+ self.nonlinearity[-1].bias.data.zero_()
504
+
505
+ def forward(self, x):
506
+ x = self.nonlinearity(x)
507
+ return x
508
+
509
+
510
+ @add_start_docstrings(
511
+ """
512
+ LTG-BERT model with a sequence classification/regression head on top (a linear layer on top of the pooled
513
+ output) e.g. for GLUE tasks.
514
+ """,
515
+ LTG_BERT_START_DOCSTRING,
516
+ )
517
+ class LtgBertForSequenceClassification(LtgBertModel):
518
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
519
+ _keys_to_ignore_on_load_missing = ["head"]
520
+
521
+ def __init__(self, config):
522
+ super().__init__(config, add_mlm_layer=False)
523
+
524
+ self.num_labels = config.num_labels
525
+ # self.head = Classifier(config, self.num_labels)
526
+
527
+ self.config = config
528
+
529
+ classifier_dropout = (
530
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
531
+ )
532
+ self.dropout = nn.Dropout(classifier_dropout)
533
+ self.head = nn.Linear(config.hidden_size, config.num_labels)
534
+
535
+ # Initialize weights and apply final processing
536
+ self.post_init()
537
+
538
+ @add_start_docstrings_to_model_forward(LTG_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
539
+ def forward(
540
+ self,
541
+ input_ids: Optional[torch.Tensor] = None,
542
+ attention_mask: Optional[torch.Tensor] = None,
543
+ output_attentions: Optional[bool] = None,
544
+ output_hidden_states: Optional[bool] = None,
545
+ inputs_embeds: Optional[torch.Tensor] = None,
546
+ return_dict: Optional[bool] = None,
547
+ labels: Optional[torch.LongTensor] = None,
548
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
549
+ r"""
550
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
551
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
552
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
553
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
554
+ """
555
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
556
+
557
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, inputs_embeds,
558
+ ~attention_mask)
559
+ logits = self.head(sequence_output[:, 0, :])
560
+
561
+ loss = None
562
+ if labels is not None:
563
+ if self.config.problem_type is None:
564
+ if self.num_labels == 1:
565
+ self.config.problem_type = "regression"
566
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
567
+ self.config.problem_type = "single_label_classification"
568
+ else:
569
+ self.config.problem_type = "multi_label_classification"
570
+
571
+ if self.config.problem_type == "regression":
572
+ loss_fct = nn.MSELoss()
573
+ if self.num_labels == 1:
574
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
575
+ else:
576
+ loss = loss_fct(logits, labels)
577
+ elif self.config.problem_type == "single_label_classification":
578
+ loss_fct = nn.CrossEntropyLoss()
579
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
580
+ elif self.config.problem_type == "multi_label_classification":
581
+ loss_fct = nn.BCEWithLogitsLoss()
582
+ loss = loss_fct(logits, labels)
583
+
584
+ if not return_dict:
585
+ output = (
586
+ logits,
587
+ *([contextualized_embeddings] if output_hidden_states else []),
588
+ *([attention_probs] if output_attentions else [])
589
+ )
590
+ return ((loss,) + output) if loss is not None else output
591
+
592
+ return SequenceClassifierOutput(
593
+ loss=loss,
594
+ logits=logits,
595
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
596
+ attentions=attention_probs if output_attentions else None
597
+ )
598
+
599
+
600
+ @add_start_docstrings(
601
+ """
602
+ LTG-BERT model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
603
+ Named-Entity-Recognition (NER) tasks.
604
+ """,
605
+ LTG_BERT_START_DOCSTRING,
606
+ )
607
+ class LtgBertForTokenClassification(LtgBertModel):
608
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
609
+ _keys_to_ignore_on_load_missing = ["head"]
610
+
611
+ def __init__(self, config):
612
+ super().__init__(config, add_mlm_layer=False)
613
+
614
+ self.num_labels = config.num_labels
615
+ self.head = Classifier(config, self.num_labels)
616
+
617
+ @add_start_docstrings_to_model_forward(LTG_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
618
+ def forward(
619
+ self,
620
+ input_ids: Optional[torch.Tensor] = None,
621
+ attention_mask: Optional[torch.Tensor] = None,
622
+ token_type_ids: Optional[torch.Tensor] = None,
623
+ position_ids: Optional[torch.Tensor] = None,
624
+ output_attentions: Optional[bool] = None,
625
+ output_hidden_states: Optional[bool] = None,
626
+ return_dict: Optional[bool] = None,
627
+ labels: Optional[torch.LongTensor] = None,
628
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
629
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
630
+
631
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
632
+ logits = self.head(sequence_output)
633
+
634
+ loss = None
635
+ if labels is not None:
636
+ loss_fct = nn.CrossEntropyLoss()
637
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
638
+
639
+ if not return_dict:
640
+ output = (
641
+ logits,
642
+ *([contextualized_embeddings] if output_hidden_states else []),
643
+ *([attention_probs] if output_attentions else [])
644
+ )
645
+ return ((loss,) + output) if loss is not None else output
646
+
647
+ return TokenClassifierOutput(
648
+ loss=loss,
649
+ logits=logits,
650
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
651
+ attentions=attention_probs if output_attentions else None
652
+ )
653
+
654
+
655
+ @add_start_docstrings(
656
+ """
657
+ LTG-BERT model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
658
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
659
+ """,
660
+ LTG_BERT_START_DOCSTRING,
661
+ )
662
+ class LtgBertForQuestionAnswering(LtgBertModel):
663
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
664
+ _keys_to_ignore_on_load_missing = ["head"]
665
+
666
+ def __init__(self, config):
667
+ super().__init__(config, add_mlm_layer=False)
668
+
669
+ self.num_labels = config.num_labels
670
+ self.head = Classifier(config, self.num_labels)
671
+
672
+ @add_start_docstrings_to_model_forward(LTG_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
673
+ def forward(
674
+ self,
675
+ input_ids: Optional[torch.Tensor] = None,
676
+ attention_mask: Optional[torch.Tensor] = None,
677
+ token_type_ids: Optional[torch.Tensor] = None,
678
+ position_ids: Optional[torch.Tensor] = None,
679
+ output_attentions: Optional[bool] = None,
680
+ output_hidden_states: Optional[bool] = None,
681
+ return_dict: Optional[bool] = None,
682
+ start_positions: Optional[torch.Tensor] = None,
683
+ end_positions: Optional[torch.Tensor] = None
684
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
685
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
686
+
687
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
688
+ logits = self.head(sequence_output)
689
+
690
+ start_logits, end_logits = logits.split(1, dim=-1)
691
+ start_logits = start_logits.squeeze(-1).contiguous()
692
+ end_logits = end_logits.squeeze(-1).contiguous()
693
+
694
+ total_loss = None
695
+ if start_positions is not None and end_positions is not None:
696
+ # If we are on multi-GPU, split add a dimension
697
+ if len(start_positions.size()) > 1:
698
+ start_positions = start_positions.squeeze(-1)
699
+ if len(end_positions.size()) > 1:
700
+ end_positions = end_positions.squeeze(-1)
701
+
702
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
703
+ ignored_index = start_logits.size(1)
704
+ start_positions = start_positions.clamp(0, ignored_index)
705
+ end_positions = end_positions.clamp(0, ignored_index)
706
+
707
+ loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
708
+ start_loss = loss_fct(start_logits, start_positions)
709
+ end_loss = loss_fct(end_logits, end_positions)
710
+ total_loss = (start_loss + end_loss) / 2
711
+
712
+ if not return_dict:
713
+ output = (
714
+ start_logits,
715
+ end_logits,
716
+ *([contextualized_embeddings] if output_hidden_states else []),
717
+ *([attention_probs] if output_attentions else [])
718
+ )
719
+ return ((total_loss,) + output) if total_loss is not None else output
720
+
721
+ return QuestionAnsweringModelOutput(
722
+ loss=total_loss,
723
+ start_logits=start_logits,
724
+ end_logits=end_logits,
725
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
726
+ attentions=attention_probs if output_attentions else None
727
+ )
728
+
729
+
730
+ @add_start_docstrings(
731
+ """
732
+ LTG-BERT model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
733
+ softmax) e.g. for RocStories/SWAG tasks.
734
+ """,
735
+ LTG_BERT_START_DOCSTRING,
736
+ )
737
+ class LtgBertForMultipleChoice(LtgBertModel):
738
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
739
+ _keys_to_ignore_on_load_missing = ["head"]
740
+
741
+ def __init__(self, config):
742
+ super().__init__(config, add_mlm_layer=False)
743
+
744
+ self.num_labels = getattr(config, "num_labels", 2)
745
+ self.head = Classifier(config, self.num_labels)
746
+
747
+ @add_start_docstrings_to_model_forward(LTG_BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
748
+ def forward(
749
+ self,
750
+ input_ids: Optional[torch.Tensor] = None,
751
+ attention_mask: Optional[torch.Tensor] = None,
752
+ token_type_ids: Optional[torch.Tensor] = None,
753
+ position_ids: Optional[torch.Tensor] = None,
754
+ labels: Optional[torch.Tensor] = None,
755
+ output_attentions: Optional[bool] = None,
756
+ output_hidden_states: Optional[bool] = None,
757
+ return_dict: Optional[bool] = None
758
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
759
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
760
+ num_choices = input_ids.shape[1]
761
+
762
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1))
763
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
764
+
765
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(flat_input_ids, flat_attention_mask)
766
+ logits = self.head(sequence_output)
767
+ reshaped_logits = logits.view(-1, num_choices)
768
+
769
+ loss = None
770
+ if labels is not None:
771
+ loss_fct = nn.CrossEntropyLoss()
772
+ loss = loss_fct(reshaped_logits, labels)
773
+
774
+ if not return_dict:
775
+ output = (
776
+ reshaped_logits,
777
+ *([contextualized_embeddings] if output_hidden_states else []),
778
+ *([attention_probs] if output_attentions else [])
779
+ )
780
+ return ((loss,) + output) if loss is not None else output
781
+
782
+ return MultipleChoiceModelOutput(
783
+ loss=loss,
784
+ logits=reshaped_logits,
785
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
786
+ attentions=attention_probs if output_attentions else None
787
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd61048218ff33e720a3fcb3f9efc6ed11685aaec7e318e8b444474e2474c40f
3
+ size 418132726
special_tokens_map.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "cls_token": {
10
+ "content": "<cls>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "eos_token": {
17
+ "content": "</s>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "mask_token": {
24
+ "content": "<mask>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "pad_token": {
31
+ "content": "<pad>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ },
37
+ "sep_token": {
38
+ "content": "<sep>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false
43
+ },
44
+ "unk_token": {
45
+ "content": "<unk>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false
50
+ }
51
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<s>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<pad>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "</s>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "4": {
36
+ "content": "<mask>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "5": {
44
+ "content": "<cls>",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "6": {
52
+ "content": "<sep>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ }
59
+ },
60
+ "bos_token": "<s>",
61
+ "clean_up_tokenization_spaces": true,
62
+ "cls_token": "<cls>",
63
+ "eos_token": "</s>",
64
+ "mask_token": "<mask>",
65
+ "model_max_length": 128,
66
+ "pad_token": "<pad>",
67
+ "sep_token": "<sep>",
68
+ "special_tokens": [
69
+ "<s>",
70
+ "<pad>",
71
+ "</s>",
72
+ "<unk>",
73
+ "<mask>",
74
+ "<cls>",
75
+ "<sep>"
76
+ ],
77
+ "tokenizer_class": "PreTrainedTokenizerFast",
78
+ "unk_token": "<unk>"
79
+ }