Upload 8 files
Browse files- base.json +13 -0
- config.json +19 -0
- configuration_ltgbert.py +34 -0
- modeling_ltgbert.py +639 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +1 -0
- tokenizer.json +0 -0
- tokenizer_config.json +4 -0
base.json
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"attention_probs_dropout_prob": 0.1,
|
3 |
+
"hidden_dropout_prob": 0.1,
|
4 |
+
"hidden_size": 768,
|
5 |
+
"initializer_range": 0.02,
|
6 |
+
"intermediate_size": 2048,
|
7 |
+
"max_position_embeddings": 512,
|
8 |
+
"position_bucket_size": 32,
|
9 |
+
"num_attention_heads": 12,
|
10 |
+
"num_hidden_layers": 12,
|
11 |
+
"vocab_size": 16384,
|
12 |
+
"layer_norm_eps": 1.0e-7
|
13 |
+
}
|
config.json
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"LTGBertForMaskedLM"
|
4 |
+
],
|
5 |
+
"attention_probs_dropout_prob": 0.1,
|
6 |
+
"hidden_dropout_prob": 0.1,
|
7 |
+
"hidden_size": 768,
|
8 |
+
"initializer_range": 0.02,
|
9 |
+
"intermediate_size": 2048,
|
10 |
+
"layer_norm_eps": 1e-07,
|
11 |
+
"max_position_embeddings": 512,
|
12 |
+
"num_attention_heads": 12,
|
13 |
+
"num_hidden_layers": 12,
|
14 |
+
"output_all_encoded_layers": true,
|
15 |
+
"position_bucket_size": 32,
|
16 |
+
"torch_dtype": "float32",
|
17 |
+
"transformers_version": "4.26.0",
|
18 |
+
"vocab_size": 16384
|
19 |
+
}
|
configuration_ltgbert.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers.configuration_utils import PretrainedConfig
|
2 |
+
|
3 |
+
|
4 |
+
class LTGBertConfig(PretrainedConfig):
|
5 |
+
"""Configuration class to store the configuration of a `LTGBertModel`.
|
6 |
+
"""
|
7 |
+
def __init__(
|
8 |
+
self,
|
9 |
+
vocab_size=50000,
|
10 |
+
attention_probs_dropout_prob=0.1,
|
11 |
+
hidden_dropout_prob=0.1,
|
12 |
+
hidden_size=768,
|
13 |
+
intermediate_size=2048,
|
14 |
+
max_position_embeddings=512,
|
15 |
+
position_bucket_size=32,
|
16 |
+
num_attention_heads=12,
|
17 |
+
num_hidden_layers=12,
|
18 |
+
layer_norm_eps=1.0e-7,
|
19 |
+
output_all_encoded_layers=True,
|
20 |
+
**kwargs,
|
21 |
+
):
|
22 |
+
super().__init__(**kwargs)
|
23 |
+
|
24 |
+
self.vocab_size = vocab_size
|
25 |
+
self.hidden_size = hidden_size
|
26 |
+
self.num_hidden_layers = num_hidden_layers
|
27 |
+
self.num_attention_heads = num_attention_heads
|
28 |
+
self.intermediate_size = intermediate_size
|
29 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
30 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
31 |
+
self.max_position_embeddings = max_position_embeddings
|
32 |
+
self.output_all_encoded_layers = output_all_encoded_layers
|
33 |
+
self.position_bucket_size = position_bucket_size
|
34 |
+
self.layer_norm_eps = layer_norm_eps
|
modeling_ltgbert.py
ADDED
@@ -0,0 +1,639 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import absolute_import, division, print_function, unicode_literals
|
2 |
+
|
3 |
+
import math
|
4 |
+
from typing import List, Optional, Tuple, Union
|
5 |
+
|
6 |
+
import torch
|
7 |
+
import torch.nn as nn
|
8 |
+
import torch.nn.functional as F
|
9 |
+
from torch import _softmax_backward_data as _softmax_backward_data
|
10 |
+
from torch.utils import checkpoint
|
11 |
+
|
12 |
+
from configuration_ltgbert import LTGBertConfig
|
13 |
+
from transformers.modeling_utils import PreTrainedModel
|
14 |
+
from transformers.activations import gelu_new
|
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 |
+
self.initialize(config.hidden_size, subword_embedding)
|
63 |
+
|
64 |
+
def initialize(self, hidden_size, embedding):
|
65 |
+
std = math.sqrt(2.0 / (5.0 * hidden_size))
|
66 |
+
nn.init.trunc_normal_(self.nonlinearity[1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
67 |
+
self.nonlinearity[-1].weight = embedding
|
68 |
+
self.nonlinearity[1].bias.data.zero_()
|
69 |
+
self.nonlinearity[-1].bias.data.zero_()
|
70 |
+
|
71 |
+
def forward(self, x, masked_lm_labels=None):
|
72 |
+
if masked_lm_labels is not None:
|
73 |
+
x = torch.index_select(x.flatten(0, 1), 0, torch.nonzero(masked_lm_labels.flatten() != -100).squeeze())
|
74 |
+
x = self.nonlinearity(x)
|
75 |
+
return x
|
76 |
+
|
77 |
+
|
78 |
+
class EncoderLayer(nn.Module):
|
79 |
+
def __init__(self, config):
|
80 |
+
super().__init__()
|
81 |
+
self.attention = Attention(config)
|
82 |
+
self.mlp = FeedForward(config)
|
83 |
+
|
84 |
+
def forward(self, x, padding_mask, relative_embedding):
|
85 |
+
attention_output, attention_probs = self.attention(x, padding_mask, relative_embedding)
|
86 |
+
x = x + attention_output
|
87 |
+
x = x + self.mlp(x)
|
88 |
+
return x, attention_probs
|
89 |
+
|
90 |
+
|
91 |
+
class GeGLU(nn.Module):
|
92 |
+
def forward(self, x):
|
93 |
+
x, gate = x.chunk(2, dim=-1)
|
94 |
+
x = x * gelu_new(gate)
|
95 |
+
return x
|
96 |
+
|
97 |
+
|
98 |
+
class FeedForward(nn.Module):
|
99 |
+
def __init__(self, config):
|
100 |
+
super().__init__()
|
101 |
+
self.mlp = nn.Sequential(
|
102 |
+
nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False),
|
103 |
+
nn.Linear(config.hidden_size, 2*config.intermediate_size, bias=False),
|
104 |
+
GeGLU(),
|
105 |
+
nn.LayerNorm(config.intermediate_size, eps=config.layer_norm_eps, elementwise_affine=False),
|
106 |
+
nn.Linear(config.intermediate_size, config.hidden_size, bias=False),
|
107 |
+
nn.Dropout(config.hidden_dropout_prob)
|
108 |
+
)
|
109 |
+
self.initialize(config.hidden_size)
|
110 |
+
|
111 |
+
def initialize(self, hidden_size):
|
112 |
+
std = math.sqrt(2.0 / (5.0 * hidden_size))
|
113 |
+
nn.init.trunc_normal_(self.mlp[1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
114 |
+
nn.init.trunc_normal_(self.mlp[-2].weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
115 |
+
|
116 |
+
def forward(self, x):
|
117 |
+
return self.mlp(x)
|
118 |
+
|
119 |
+
|
120 |
+
class MaskedSoftmax(torch.autograd.Function):
|
121 |
+
@staticmethod
|
122 |
+
def forward(self, x, mask, dim):
|
123 |
+
self.dim = dim
|
124 |
+
x.masked_fill_(mask, float('-inf'))
|
125 |
+
x = torch.softmax(x, self.dim)
|
126 |
+
x.masked_fill_(mask, 0.0)
|
127 |
+
self.save_for_backward(x)
|
128 |
+
return x
|
129 |
+
|
130 |
+
@staticmethod
|
131 |
+
def backward(self, grad_output):
|
132 |
+
output, = self.saved_tensors
|
133 |
+
inputGrad = _softmax_backward_data(grad_output, output, self.dim, output.dtype)
|
134 |
+
return inputGrad, None, None
|
135 |
+
|
136 |
+
|
137 |
+
class Attention(nn.Module):
|
138 |
+
def __init__(self, config):
|
139 |
+
super().__init__()
|
140 |
+
|
141 |
+
self.config = config
|
142 |
+
|
143 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
144 |
+
raise ValueError(f"The hidden size {config.hidden_size} is not a multiple of the number of attention heads {config.num_attention_heads}")
|
145 |
+
|
146 |
+
self.hidden_size = config.hidden_size
|
147 |
+
self.num_heads = config.num_attention_heads
|
148 |
+
self.head_size = config.hidden_size // config.num_attention_heads
|
149 |
+
|
150 |
+
self.in_proj_qk = nn.Linear(config.hidden_size, 2*config.hidden_size, bias=True)
|
151 |
+
self.in_proj_v = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
|
152 |
+
self.out_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
|
153 |
+
|
154 |
+
self.pre_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False)
|
155 |
+
self.post_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=True)
|
156 |
+
|
157 |
+
position_indices = torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(1) \
|
158 |
+
- torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(0)
|
159 |
+
position_indices = self.make_log_bucket_position(position_indices, config.position_bucket_size, config.max_position_embeddings)
|
160 |
+
position_indices = config.position_bucket_size - 1 + position_indices
|
161 |
+
self.register_buffer("position_indices", position_indices, persistent=True)
|
162 |
+
|
163 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
164 |
+
self.scale = 1.0 / math.sqrt(3 * self.head_size)
|
165 |
+
self.initialize()
|
166 |
+
|
167 |
+
def make_log_bucket_position(self, relative_pos, bucket_size, max_position):
|
168 |
+
sign = torch.sign(relative_pos)
|
169 |
+
mid = bucket_size // 2
|
170 |
+
abs_pos = torch.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, torch.abs(relative_pos).clamp(max=max_position - 1))
|
171 |
+
log_pos = torch.ceil(torch.log(abs_pos / mid) / math.log((max_position-1) / mid) * (mid - 1)).int() + mid
|
172 |
+
bucket_pos = torch.where(abs_pos <= mid, relative_pos, log_pos * sign).long()
|
173 |
+
return bucket_pos
|
174 |
+
|
175 |
+
def initialize(self):
|
176 |
+
std = math.sqrt(2.0 / (5.0 * self.hidden_size))
|
177 |
+
nn.init.trunc_normal_(self.in_proj_qk.weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
178 |
+
nn.init.trunc_normal_(self.in_proj_v.weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
179 |
+
nn.init.trunc_normal_(self.out_proj.weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
180 |
+
self.in_proj_qk.bias.data.zero_()
|
181 |
+
self.in_proj_v.bias.data.zero_()
|
182 |
+
self.out_proj.bias.data.zero_()
|
183 |
+
|
184 |
+
def compute_attention_scores(self, hidden_states, relative_embedding):
|
185 |
+
key_len, batch_size, _ = hidden_states.size()
|
186 |
+
query_len = key_len
|
187 |
+
|
188 |
+
if self.position_indices.size(0) < query_len:
|
189 |
+
position_indices = torch.arange(query_len, dtype=torch.long).unsqueeze(1) \
|
190 |
+
- torch.arange(query_len, dtype=torch.long).unsqueeze(0)
|
191 |
+
position_indices = self.make_log_bucket_position(position_indices, self.position_bucket_size, 512)
|
192 |
+
position_indices = self.position_bucket_size - 1 + position_indices
|
193 |
+
self.position_indices = position_indices.to(hidden_states.device)
|
194 |
+
|
195 |
+
hidden_states = self.pre_layer_norm(hidden_states)
|
196 |
+
|
197 |
+
query, key = self.in_proj_qk(hidden_states).chunk(2, dim=2) # shape: [T, B, D]
|
198 |
+
key = key * self.scale
|
199 |
+
value = self.in_proj_v(hidden_states) # shape: [T, B, D]
|
200 |
+
|
201 |
+
query = query.reshape(query_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
|
202 |
+
key = key.reshape(key_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
|
203 |
+
value = value.view(key_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
|
204 |
+
|
205 |
+
attention_scores = torch.bmm(query, key.transpose(1, 2))
|
206 |
+
|
207 |
+
pos = self.in_proj_qk(self.dropout(relative_embedding)) # shape: [2T-1, 2D]
|
208 |
+
pos = pos.view(-1, self.num_heads, 2*self.head_size)
|
209 |
+
query_pos, key_pos = pos.chunk(2, dim=2)
|
210 |
+
key_pos = key_pos * self.scale
|
211 |
+
|
212 |
+
query = query.view(batch_size, self.num_heads, query_len, self.head_size)
|
213 |
+
key = key.view(batch_size, self.num_heads, key_len, self.head_size)
|
214 |
+
|
215 |
+
attention_c_p = torch.einsum("bhqd,khd->bhqk", query, key_pos)
|
216 |
+
attention_p_c = torch.einsum("bhkd,qhd->bhqk", key, query_pos)
|
217 |
+
|
218 |
+
position_indices = self.position_indices[:query_len, :key_len].expand(batch_size, self.num_heads, -1, -1)
|
219 |
+
attention_c_p = attention_c_p.gather(3, position_indices)
|
220 |
+
attention_p_c = attention_p_c.gather(2, position_indices)
|
221 |
+
|
222 |
+
attention_scores = attention_scores.view(batch_size, self.num_heads, query_len, key_len)
|
223 |
+
attention_scores.add_(attention_c_p)
|
224 |
+
attention_scores.add_(attention_p_c)
|
225 |
+
|
226 |
+
return attention_scores, attention_c_p, attention_p_c, value
|
227 |
+
|
228 |
+
def compute_output(self, attention_probs, value):
|
229 |
+
attention_probs = self.dropout(attention_probs)
|
230 |
+
context = torch.bmm(attention_probs.flatten(0, 1), value) # shape: [B*H, Q, D]
|
231 |
+
context = context.transpose(0, 1).reshape(context.size(1), -1, self.hidden_size) # shape: [Q, B, H*D]
|
232 |
+
context = self.out_proj(context)
|
233 |
+
context = self.post_layer_norm(context)
|
234 |
+
context = self.dropout(context)
|
235 |
+
return context
|
236 |
+
|
237 |
+
def forward(self, hidden_states, attention_mask, relative_embedding):
|
238 |
+
attention_scores, value = self.compute_attention_scores(hidden_states, relative_embedding)
|
239 |
+
attention_probs = MaskedSoftmax.apply(attention_scores, attention_mask, -1)
|
240 |
+
return self.compute_output(attention_probs, value), attention_probs.detach()
|
241 |
+
|
242 |
+
|
243 |
+
class Embedding(nn.Module):
|
244 |
+
def __init__(self, config):
|
245 |
+
super().__init__()
|
246 |
+
self.hidden_size = config.hidden_size
|
247 |
+
|
248 |
+
self.word_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
|
249 |
+
self.word_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False)
|
250 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
251 |
+
|
252 |
+
self.relative_embedding = nn.Parameter(torch.empty(2 * config.position_bucket_size - 1, config.hidden_size))
|
253 |
+
self.relative_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
254 |
+
|
255 |
+
self.initialize()
|
256 |
+
|
257 |
+
def initialize(self):
|
258 |
+
std = math.sqrt(2.0 / (5.0 * self.hidden_size))
|
259 |
+
nn.init.trunc_normal_(self.relative_embedding, mean=0.0, std=std, a=-2*std, b=2*std)
|
260 |
+
nn.init.trunc_normal_(self.word_embedding.weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
261 |
+
|
262 |
+
def forward(self, input_ids):
|
263 |
+
word_embedding = self.dropout(self.word_layer_norm(self.word_embedding(input_ids)))
|
264 |
+
relative_embeddings = self.relative_layer_norm(self.relative_embedding)
|
265 |
+
return word_embedding, relative_embeddings
|
266 |
+
|
267 |
+
|
268 |
+
#
|
269 |
+
# HuggingFace wrappers
|
270 |
+
#
|
271 |
+
|
272 |
+
class LTGBertPreTrainedModel(PreTrainedModel):
|
273 |
+
config_class = LTGBertConfig
|
274 |
+
base_model_prefix = "LTG-BERT"
|
275 |
+
supports_gradient_checkpointing = True
|
276 |
+
|
277 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
278 |
+
if isinstance(module, Encoder):
|
279 |
+
module.activation_checkpointing = value
|
280 |
+
|
281 |
+
def _init_weights(self, module):
|
282 |
+
pass # everything is already initialized
|
283 |
+
|
284 |
+
|
285 |
+
class LTGBertModel(LTGBertPreTrainedModel):
|
286 |
+
def __init__(self, config, add_mlm_layer=False):
|
287 |
+
super().__init__(config)
|
288 |
+
self.config = config
|
289 |
+
|
290 |
+
self.embedding = Embedding(config)
|
291 |
+
self.transformer = Encoder(config, activation_checkpointing=False)
|
292 |
+
self.classifier = MaskClassifier(config, self.embedding.word_embedding.weight) if add_mlm_layer else None
|
293 |
+
|
294 |
+
def get_input_embeddings(self):
|
295 |
+
return self.embedding.word_embedding
|
296 |
+
|
297 |
+
def set_input_embeddings(self, value):
|
298 |
+
self.embedding.word_embedding = value
|
299 |
+
|
300 |
+
def get_contextualized_embeddings(
|
301 |
+
self,
|
302 |
+
input_ids: Optional[torch.Tensor] = None,
|
303 |
+
attention_mask: Optional[torch.Tensor] = None
|
304 |
+
) -> List[torch.Tensor]:
|
305 |
+
if input_ids is not None:
|
306 |
+
input_shape = input_ids.size()
|
307 |
+
else:
|
308 |
+
raise ValueError("You have to specify input_ids")
|
309 |
+
|
310 |
+
batch_size, seq_length = input_shape
|
311 |
+
device = input_ids.device
|
312 |
+
|
313 |
+
if attention_mask is None:
|
314 |
+
attention_mask = torch.zeros(batch_size, seq_length, dtype=torch.bool, device=device)
|
315 |
+
else:
|
316 |
+
attention_mask = ~attention_mask.bool()
|
317 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
318 |
+
|
319 |
+
static_embeddings, relative_embedding = self.embedding(input_ids.t())
|
320 |
+
contextualized_embeddings, attention_probs = self.transformer(static_embeddings, attention_mask, relative_embedding)
|
321 |
+
contextualized_embeddings = [e.transpose(0, 1) for e in contextualized_embeddings]
|
322 |
+
last_layer = contextualized_embeddings[-1]
|
323 |
+
contextualized_embeddings = [contextualized_embeddings[0]] + [
|
324 |
+
contextualized_embeddings[i] - contextualized_embeddings[i - 1]
|
325 |
+
for i in range(1, len(contextualized_embeddings))
|
326 |
+
]
|
327 |
+
return last_layer, contextualized_embeddings, attention_probs
|
328 |
+
|
329 |
+
def forward(
|
330 |
+
self,
|
331 |
+
input_ids: Optional[torch.Tensor] = None,
|
332 |
+
attention_mask: Optional[torch.Tensor] = None,
|
333 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
334 |
+
position_ids: Optional[torch.Tensor] = None,
|
335 |
+
output_hidden_states: Optional[bool] = None,
|
336 |
+
output_attentions: Optional[bool] = None,
|
337 |
+
return_dict: Optional[bool] = None,
|
338 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutput]:
|
339 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
340 |
+
|
341 |
+
sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
|
342 |
+
|
343 |
+
if not return_dict:
|
344 |
+
return sequence_output, contextualized_embeddings, attention_probs
|
345 |
+
|
346 |
+
return BaseModelOutput(
|
347 |
+
last_hidden_state=sequence_output,
|
348 |
+
hidden_states=contextualized_embeddings,
|
349 |
+
attentions=attention_probs
|
350 |
+
)
|
351 |
+
|
352 |
+
|
353 |
+
class LTGBertForMaskedLM(LTGBertModel):
|
354 |
+
_keys_to_ignore_on_load_unexpected = ["head"]
|
355 |
+
|
356 |
+
def __init__(self, config):
|
357 |
+
super().__init__(config, add_mlm_layer=True)
|
358 |
+
|
359 |
+
def get_output_embeddings(self):
|
360 |
+
return self.classifier.nonlinearity[-1].weight
|
361 |
+
|
362 |
+
def set_output_embeddings(self, new_embeddings):
|
363 |
+
self.classifier.nonlinearity[-1].weight = new_embeddings
|
364 |
+
|
365 |
+
def forward(
|
366 |
+
self,
|
367 |
+
input_ids: Optional[torch.Tensor] = None,
|
368 |
+
attention_mask: Optional[torch.Tensor] = None,
|
369 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
370 |
+
position_ids: Optional[torch.Tensor] = None,
|
371 |
+
output_hidden_states: Optional[bool] = None,
|
372 |
+
output_attentions: Optional[bool] = None,
|
373 |
+
return_dict: Optional[bool] = None,
|
374 |
+
labels: Optional[torch.LongTensor] = None,
|
375 |
+
) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
|
376 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
377 |
+
|
378 |
+
sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
|
379 |
+
subword_prediction = self.classifier(sequence_output)
|
380 |
+
subword_prediction[:, :, :106+1] = float("-inf")
|
381 |
+
|
382 |
+
masked_lm_loss = None
|
383 |
+
if labels is not None:
|
384 |
+
masked_lm_loss = F.cross_entropy(subword_prediction.flatten(0, 1), labels.flatten())
|
385 |
+
|
386 |
+
if not return_dict:
|
387 |
+
output = (subword_prediction, contextualized_embeddings, attention_probs)
|
388 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
389 |
+
|
390 |
+
return MaskedLMOutput(
|
391 |
+
loss=masked_lm_loss,
|
392 |
+
logits=subword_prediction,
|
393 |
+
hidden_states=contextualized_embeddings,
|
394 |
+
attentions=attention_probs
|
395 |
+
)
|
396 |
+
|
397 |
+
|
398 |
+
class Classifier(nn.Module):
|
399 |
+
def __init__(self, config, num_labels: int):
|
400 |
+
super().__init__()
|
401 |
+
|
402 |
+
drop_out = getattr(config, "cls_dropout", None)
|
403 |
+
drop_out = config.hidden_dropout_prob if drop_out is None else drop_out
|
404 |
+
|
405 |
+
self.nonlinearity = nn.Sequential(
|
406 |
+
nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
|
407 |
+
nn.Linear(config.hidden_size, config.hidden_size),
|
408 |
+
nn.GELU(),
|
409 |
+
nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
|
410 |
+
nn.Dropout(drop_out),
|
411 |
+
nn.Linear(config.hidden_size, num_labels)
|
412 |
+
)
|
413 |
+
self.initialize(config.hidden_size)
|
414 |
+
|
415 |
+
def initialize(self, hidden_size):
|
416 |
+
std = math.sqrt(2.0 / (5.0 * hidden_size))
|
417 |
+
nn.init.trunc_normal_(self.nonlinearity[1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
418 |
+
nn.init.trunc_normal_(self.nonlinearity[-1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
419 |
+
self.nonlinearity[1].bias.data.zero_()
|
420 |
+
self.nonlinearity[-1].bias.data.zero_()
|
421 |
+
|
422 |
+
def forward(self, x):
|
423 |
+
x = self.nonlinearity(x)
|
424 |
+
return x
|
425 |
+
|
426 |
+
|
427 |
+
class LTGBertForSequenceClassification(LTGBertModel):
|
428 |
+
_keys_to_ignore_on_load_unexpected = ["classifier"]
|
429 |
+
_keys_to_ignore_on_load_missing = ["head"]
|
430 |
+
|
431 |
+
def __init__(self, config):
|
432 |
+
super().__init__(config, add_mlm_layer=False)
|
433 |
+
|
434 |
+
self.num_labels = config.num_labels
|
435 |
+
self.head = Classifier(config, self.num_labels)
|
436 |
+
|
437 |
+
def forward(
|
438 |
+
self,
|
439 |
+
input_ids: Optional[torch.Tensor] = None,
|
440 |
+
attention_mask: Optional[torch.Tensor] = None,
|
441 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
442 |
+
position_ids: Optional[torch.Tensor] = None,
|
443 |
+
output_attentions: Optional[bool] = None,
|
444 |
+
output_hidden_states: Optional[bool] = None,
|
445 |
+
return_dict: Optional[bool] = None,
|
446 |
+
labels: Optional[torch.LongTensor] = None,
|
447 |
+
) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
|
448 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
449 |
+
|
450 |
+
sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
|
451 |
+
logits = self.head(sequence_output[:, 0, :])
|
452 |
+
|
453 |
+
loss = None
|
454 |
+
if labels is not None:
|
455 |
+
if self.config.problem_type is None:
|
456 |
+
if self.num_labels == 1:
|
457 |
+
self.config.problem_type = "regression"
|
458 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
459 |
+
self.config.problem_type = "single_label_classification"
|
460 |
+
else:
|
461 |
+
self.config.problem_type = "multi_label_classification"
|
462 |
+
|
463 |
+
if self.config.problem_type == "regression":
|
464 |
+
loss_fct = nn.MSELoss()
|
465 |
+
if self.num_labels == 1:
|
466 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
467 |
+
else:
|
468 |
+
loss = loss_fct(logits, labels)
|
469 |
+
elif self.config.problem_type == "single_label_classification":
|
470 |
+
loss_fct = nn.CrossEntropyLoss()
|
471 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
472 |
+
elif self.config.problem_type == "multi_label_classification":
|
473 |
+
loss_fct = nn.BCEWithLogitsLoss()
|
474 |
+
loss = loss_fct(logits, labels)
|
475 |
+
|
476 |
+
if not return_dict:
|
477 |
+
output = (logits, contextualized_embeddings, attention_probs)
|
478 |
+
return ((loss,) + output) if loss is not None else output
|
479 |
+
|
480 |
+
return SequenceClassifierOutput(
|
481 |
+
loss=loss,
|
482 |
+
logits=logits,
|
483 |
+
hidden_states=contextualized_embeddings,
|
484 |
+
attentions=attention_probs
|
485 |
+
)
|
486 |
+
|
487 |
+
|
488 |
+
class LTGBertForTokenClassification(LTGBertModel):
|
489 |
+
_keys_to_ignore_on_load_unexpected = ["classifier"]
|
490 |
+
_keys_to_ignore_on_load_missing = ["head"]
|
491 |
+
|
492 |
+
def __init__(self, config):
|
493 |
+
super().__init__(config, add_mlm_layer=False)
|
494 |
+
|
495 |
+
self.num_labels = config.num_labels
|
496 |
+
self.head = Classifier(config, self.num_labels)
|
497 |
+
|
498 |
+
def forward(
|
499 |
+
self,
|
500 |
+
input_ids: Optional[torch.Tensor] = None,
|
501 |
+
attention_mask: Optional[torch.Tensor] = None,
|
502 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
503 |
+
position_ids: Optional[torch.Tensor] = None,
|
504 |
+
output_attentions: Optional[bool] = None,
|
505 |
+
output_hidden_states: Optional[bool] = None,
|
506 |
+
return_dict: Optional[bool] = None,
|
507 |
+
labels: Optional[torch.LongTensor] = None,
|
508 |
+
) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
|
509 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
510 |
+
|
511 |
+
sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
|
512 |
+
logits = self.head(sequence_output)
|
513 |
+
|
514 |
+
loss = None
|
515 |
+
if labels is not None:
|
516 |
+
loss_fct = nn.CrossEntropyLoss()
|
517 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
518 |
+
|
519 |
+
if not return_dict:
|
520 |
+
output = (logits, contextualized_embeddings, attention_probs)
|
521 |
+
return ((loss,) + output) if loss is not None else output
|
522 |
+
|
523 |
+
return TokenClassifierOutput(
|
524 |
+
loss=loss,
|
525 |
+
logits=logits,
|
526 |
+
hidden_states=contextualized_embeddings,
|
527 |
+
attentions=attention_probs
|
528 |
+
)
|
529 |
+
|
530 |
+
|
531 |
+
class LTGBertForQuestionAnswering(LTGBertModel):
|
532 |
+
_keys_to_ignore_on_load_unexpected = ["classifier"]
|
533 |
+
_keys_to_ignore_on_load_missing = ["head"]
|
534 |
+
|
535 |
+
def __init__(self, config):
|
536 |
+
super().__init__(config, add_mlm_layer=False)
|
537 |
+
|
538 |
+
self.num_labels = config.num_labels
|
539 |
+
self.head = Classifier(config, self.num_labels)
|
540 |
+
|
541 |
+
def forward(
|
542 |
+
self,
|
543 |
+
input_ids: Optional[torch.Tensor] = None,
|
544 |
+
attention_mask: Optional[torch.Tensor] = None,
|
545 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
546 |
+
position_ids: Optional[torch.Tensor] = None,
|
547 |
+
output_attentions: Optional[bool] = None,
|
548 |
+
output_hidden_states: Optional[bool] = None,
|
549 |
+
return_dict: Optional[bool] = None,
|
550 |
+
start_positions: Optional[torch.Tensor] = None,
|
551 |
+
end_positions: Optional[torch.Tensor] = None
|
552 |
+
) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
|
553 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
554 |
+
|
555 |
+
sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
|
556 |
+
logits = self.head(sequence_output)
|
557 |
+
|
558 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
559 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
560 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
561 |
+
|
562 |
+
total_loss = None
|
563 |
+
if start_positions is not None and end_positions is not None:
|
564 |
+
# If we are on multi-GPU, split add a dimension
|
565 |
+
if len(start_positions.size()) > 1:
|
566 |
+
start_positions = start_positions.squeeze(-1)
|
567 |
+
if len(end_positions.size()) > 1:
|
568 |
+
end_positions = end_positions.squeeze(-1)
|
569 |
+
|
570 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
571 |
+
ignored_index = start_logits.size(1)
|
572 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
573 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
574 |
+
|
575 |
+
loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
|
576 |
+
start_loss = loss_fct(start_logits, start_positions)
|
577 |
+
end_loss = loss_fct(end_logits, end_positions)
|
578 |
+
total_loss = (start_loss + end_loss) / 2
|
579 |
+
|
580 |
+
if not return_dict:
|
581 |
+
output = start_logits, end_logits, contextualized_embeddings, attention_probs
|
582 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
583 |
+
|
584 |
+
return QuestionAnsweringModelOutput(
|
585 |
+
loss=total_loss,
|
586 |
+
start_logits=start_logits,
|
587 |
+
end_logits=end_logits,
|
588 |
+
hidden_states=contextualized_embeddings,
|
589 |
+
attentions=attention_probs,
|
590 |
+
)
|
591 |
+
|
592 |
+
|
593 |
+
class LTGBertForMultipleChoice(LTGBertModel):
|
594 |
+
_keys_to_ignore_on_load_unexpected = ["classifier"]
|
595 |
+
_keys_to_ignore_on_load_missing = ["head"]
|
596 |
+
|
597 |
+
def __init__(self, config):
|
598 |
+
super().__init__(config, add_mlm_layer=False)
|
599 |
+
|
600 |
+
self.num_labels = getattr(config, "num_labels", 2)
|
601 |
+
self.head = Classifier(config, self.num_labels)
|
602 |
+
|
603 |
+
def forward(
|
604 |
+
self,
|
605 |
+
input_ids: Optional[torch.Tensor] = None,
|
606 |
+
attention_mask: Optional[torch.Tensor] = None,
|
607 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
608 |
+
position_ids: Optional[torch.Tensor] = None,
|
609 |
+
labels: Optional[torch.Tensor] = None,
|
610 |
+
return_dict: Optional[bool] = None,
|
611 |
+
start_positions: Optional[torch.Tensor] = None,
|
612 |
+
end_positions: Optional[torch.Tensor] = None
|
613 |
+
) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
|
614 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
615 |
+
num_choices = input_ids.shape[1]
|
616 |
+
|
617 |
+
flat_input_ids = input_ids.view(-1, input_ids.size(-1))
|
618 |
+
flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
619 |
+
|
620 |
+
sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(flat_input_ids, flat_attention_mask)
|
621 |
+
logits = self.head(sequence_output)
|
622 |
+
reshaped_logits = logits.view(-1, num_choices)
|
623 |
+
|
624 |
+
loss = None
|
625 |
+
if labels is not None:
|
626 |
+
loss_fct = nn.CrossEntropyLoss()
|
627 |
+
loss = loss_fct(reshaped_logits, labels)
|
628 |
+
|
629 |
+
if not return_dict:
|
630 |
+
output = (reshaped_logits, contextualized_embeddings, attention_probs)
|
631 |
+
return ((loss,) + output) if loss is not None else output
|
632 |
+
|
633 |
+
return MultipleChoiceModelOutput(
|
634 |
+
loss=loss,
|
635 |
+
logits=reshaped_logits,
|
636 |
+
hidden_states=contextualized_embeddings,
|
637 |
+
attentions=attention_probs,
|
638 |
+
)
|
639 |
+
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:820ee7f7fdb806b0ce34758331cc6efb0f8b8bc4ba988d507386e5dfd3ef30a1
|
3 |
+
size 418130297
|
special_tokens_map.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"bos_token": "[BOS]", "eos_token": "[EOS]", "unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]"}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"model_max_length": 1000000000000000019884624838656,
|
3 |
+
"tokenizer_class": "PreTrainedTokenizerFast"
|
4 |
+
}
|