ltg
/

PyTorch
English
custom_code
davda54 commited on
Commit
1998a54
1 Parent(s): b368a47

initial upload

Browse files
__init__.py ADDED
File without changes
config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "LtgbertFoCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_ltgbert.LtgbertConfig",
7
+ "AutoModel": "modeling_ltgbert.LtgbertModel",
8
+ "AutoModelForCausalLM": "modeling_ltgbert.LtgbertForCausalLM",
9
+ "AutoModelForMaskedLM": "modeling_ltgbert.LtgbertForMaskedLM",
10
+ "AutoModelForSequenceClassification": "modeling_ltgbert.LtgbertForSequenceClassification",
11
+ "AutoModelForTokenClassification": "modeling_ltgbert.LtgbertForTokenClassification",
12
+ "AutoModelForQuestionAnswering": "modeling_ltgbert.LtgbertForQuestionAnswering",
13
+ "AutoModelForMultipleChoice": "modeling_ltgbert.LtgbertForMultipleChoice"
14
+ },
15
+ "attention_probs_dropout_prob": 0.1,
16
+ "hidden_dropout_prob": 0.1,
17
+ "hidden_size": 384,
18
+ "intermediate_size": 1280,
19
+ "layer_norm_eps": 1e-07,
20
+ "max_position_embeddings": 512,
21
+ "num_attention_heads": 6,
22
+ "num_hidden_layers": 12,
23
+ "position_bucket_size": 32,
24
+ "torch_dtype": "float32",
25
+ "vocab_size": 8192,
26
+ "temperature": 2.65
27
+ }
configuration_ltgbert.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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=32768,
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
+ temperature=1.0,
21
+ **kwargs,
22
+ ):
23
+ super().__init__(**kwargs)
24
+
25
+ self.vocab_size = vocab_size
26
+ self.hidden_size = hidden_size
27
+ self.num_hidden_layers = num_hidden_layers
28
+ self.num_attention_heads = num_attention_heads
29
+ self.intermediate_size = intermediate_size
30
+ self.hidden_dropout_prob = hidden_dropout_prob
31
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
32
+ self.max_position_embeddings = max_position_embeddings
33
+ self.output_all_encoded_layers = output_all_encoded_layers
34
+ self.position_bucket_size = position_bucket_size
35
+ self.layer_norm_eps = layer_norm_eps
36
+ self.temperature = temperature
modeling_ltgbert.py ADDED
@@ -0,0 +1,823 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from torch.utils import checkpoint
8
+
9
+ from .configuration_ltgbert import LtgbertConfig
10
+ from transformers.modeling_utils import PreTrainedModel
11
+ from transformers.activations import gelu_new
12
+ from transformers.modeling_outputs import (
13
+ MaskedLMOutput,
14
+ MultipleChoiceModelOutput,
15
+ QuestionAnsweringModelOutput,
16
+ SequenceClassifierOutput,
17
+ TokenClassifierOutput,
18
+ BaseModelOutput,
19
+ CausalLMOutput
20
+ )
21
+ from transformers.pytorch_utils import softmax_backward_data
22
+
23
+
24
+ class InPlaceSetSlice(torch.autograd.Function):
25
+ @staticmethod
26
+ def forward(ctx, full_tensor, last_slice, x_idx, x_val):
27
+ full_tensor[x_idx] = x_val
28
+ ctx.x_idx = x_idx
29
+ ret = torch.Tensor().to(full_tensor.device)
30
+ ret.set_(full_tensor[:x_idx + 1])
31
+ return ret
32
+
33
+ @staticmethod
34
+ def backward(ctx, grad_out):
35
+ if ctx.x_idx == 0:
36
+ return None, None, None, grad_out[ctx.x_idx]
37
+ else:
38
+ return None, grad_out[:ctx.x_idx], None, grad_out[ctx.x_idx]
39
+
40
+
41
+ def apply_inplace_set(x_acc, x_idx, x_val):
42
+ full_tensor, last_slice = x_acc
43
+ new_slice = InPlaceSetSlice.apply(full_tensor, last_slice, x_idx, x_val)
44
+ return full_tensor, new_slice
45
+
46
+
47
+ class DWAModules(torch.nn.Module):
48
+ def __init__(self, hidden_size, n_blocks):
49
+ super().__init__()
50
+ self.n_blocks = n_blocks
51
+ self.alphas = nn.ParameterList([nn.Parameter(torch.zeros(i + 2)) for i in range(n_blocks)])
52
+ self.accumulator = None
53
+ self._init_weights()
54
+
55
+ def _init_weights(self):
56
+ for module in self.alphas:
57
+ module.data.zero_()
58
+ module.data[-1] = 1.0
59
+
60
+ def init_accumulator(self, x):
61
+ self.accumulator = (torch.zeros((self.n_blocks + 1, *x.shape), device=x.device, dtype=x.dtype), None)
62
+ self.accumulator = apply_inplace_set(self.accumulator, 0, x)
63
+
64
+ def forward(self, x, block_idx):
65
+ assert self.accumulator is not None, "`init_accumulator(x)` needs to be called first"
66
+ self.accumulator = apply_inplace_set(
67
+ self.accumulator,
68
+ block_idx + 1,
69
+ x
70
+ )
71
+ x = torch.tensordot(self.alphas[block_idx], self.accumulator[1], dims=1)
72
+ return x
73
+
74
+
75
+ class Encoder(nn.Module):
76
+ def __init__(self, config):
77
+ super().__init__()
78
+ self.attention_layers = nn.ModuleList([Attention(config) for _ in range(config.num_hidden_layers)])
79
+ self.mlp_layers = nn.ModuleList([FeedForward(config) for _ in range(config.num_hidden_layers)])
80
+ self.dwa_modules = DWAModules(config.hidden_size, config.num_hidden_layers * 2)
81
+
82
+ for i, layer in enumerate(self.mlp_layers):
83
+ layer.mlp[1].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))
84
+ layer.mlp[-2].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))
85
+
86
+ def forward(self, x, attention_mask, relative_embedding):
87
+ hidden_states, attention_probs = [x], []
88
+
89
+ self.dwa_modules.init_accumulator(x)
90
+ for i, (attention_layer, mlp_layer) in enumerate(zip(self.attention_layers, self.mlp_layers)):
91
+ attention_output, attention_p = attention_layer(x, attention_mask, relative_embedding)
92
+ x = x + attention_output
93
+ x = self.dwa_modules(x, block_idx=i * 2)
94
+
95
+ x = x + mlp_layer(x)
96
+ x = self.dwa_modules(x, block_idx=i * 2 + 1)
97
+
98
+ hidden_states.append(x)
99
+ attention_probs.append(attention_p)
100
+
101
+ return hidden_states, attention_probs
102
+
103
+
104
+ class MaskClassifier(nn.Module):
105
+ def __init__(self, config, subword_embedding):
106
+ super().__init__()
107
+ self.nonlinearity = nn.Sequential(
108
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
109
+ nn.Linear(config.hidden_size, config.hidden_size),
110
+ nn.GELU(),
111
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
112
+ nn.Dropout(config.hidden_dropout_prob),
113
+ nn.Linear(subword_embedding.size(1), subword_embedding.size(0))
114
+ )
115
+
116
+ def forward(self, x, masked_lm_labels=None):
117
+ if masked_lm_labels is not None:
118
+ x = torch.index_select(x.flatten(0, 1), 0, torch.nonzero(masked_lm_labels.flatten() != -100).squeeze())
119
+ x = self.nonlinearity(x)
120
+ return x
121
+
122
+
123
+ # class EncoderLayer(nn.Module):
124
+ # def __init__(self, config):
125
+ # super().__init__()
126
+ # self.attention = Attention(config)
127
+ # self.mlp = FeedForward(config)
128
+
129
+ # def forward(self, x, padding_mask, relative_embedding):
130
+ # attention_output, attention_probs = self.attention(x, padding_mask, relative_embedding)
131
+ # x = x + attention_output
132
+ # x = x + self.mlp(x)
133
+ # return x, attention_probs
134
+
135
+
136
+ class GeGLU(nn.Module):
137
+ def forward(self, x):
138
+ x, gate = x.chunk(2, dim=-1)
139
+ x = x * gelu_new(gate)
140
+ return x
141
+
142
+
143
+ class FeedForward(nn.Module):
144
+ def __init__(self, config):
145
+ super().__init__()
146
+ self.mlp = nn.Sequential(
147
+ nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False),
148
+ nn.Linear(config.hidden_size, 2*config.intermediate_size, bias=False),
149
+ GeGLU(),
150
+ nn.LayerNorm(config.intermediate_size, eps=config.layer_norm_eps, elementwise_affine=False),
151
+ nn.Linear(config.intermediate_size, config.hidden_size, bias=False),
152
+ nn.Dropout(config.hidden_dropout_prob)
153
+ )
154
+
155
+ def forward(self, x):
156
+ return self.mlp(x)
157
+
158
+
159
+ class MaskedSoftmax(torch.autograd.Function):
160
+ @staticmethod
161
+ def forward(self, x, mask, dim):
162
+ self.dim = dim
163
+
164
+ x.masked_fill_(mask, float('-inf'))
165
+ x = torch.softmax(x, self.dim)
166
+ x.masked_fill_(mask, 0.0)
167
+ self.save_for_backward(x)
168
+ return x
169
+
170
+ @staticmethod
171
+ def backward(self, grad_output):
172
+ output, = self.saved_tensors
173
+ input_grad = softmax_backward_data(self, grad_output, output, self.dim, output)
174
+ return input_grad, None, None
175
+
176
+
177
+ class Attention(nn.Module):
178
+ def __init__(self, config):
179
+ super().__init__()
180
+
181
+ self.config = config
182
+
183
+ if config.hidden_size % config.num_attention_heads != 0:
184
+ raise ValueError(f"The hidden size {config.hidden_size} is not a multiple of the number of attention heads {config.num_attention_heads}")
185
+
186
+ self.hidden_size = config.hidden_size
187
+ self.num_heads = config.num_attention_heads
188
+ self.head_size = config.hidden_size // config.num_attention_heads
189
+
190
+ self.in_proj_qk = nn.Linear(config.hidden_size, 2*config.hidden_size, bias=True)
191
+ self.in_proj_vg = nn.Linear(config.hidden_size, 2*config.hidden_size, bias=True)
192
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
193
+
194
+ self.pre_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False)
195
+ self.post_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False)
196
+
197
+ position_indices = torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(1) \
198
+ - torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(0)
199
+ position_indices = self.make_log_bucket_position(position_indices, config.position_bucket_size, config.max_position_embeddings)
200
+ position_indices = config.position_bucket_size - 1 + position_indices
201
+ self.register_buffer("position_indices", position_indices, persistent=True)
202
+
203
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
204
+ self.scale = 1.0 / math.sqrt(3 * self.head_size)
205
+
206
+ def make_log_bucket_position(self, relative_pos, bucket_size, max_position):
207
+ sign = torch.sign(relative_pos)
208
+ mid = bucket_size // 2
209
+ abs_pos = torch.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, torch.abs(relative_pos).clamp(max=max_position - 1))
210
+ log_pos = torch.ceil(torch.log(abs_pos / mid) / math.log((max_position-1) / mid) * (mid - 1)).int() + mid
211
+ bucket_pos = torch.where(abs_pos <= mid, relative_pos, log_pos * sign).long()
212
+ return bucket_pos
213
+
214
+ def forward(self, hidden_states, attention_mask, relative_embedding):
215
+ key_len, batch_size, _ = hidden_states.size()
216
+ query_len = key_len
217
+
218
+ if self.position_indices.size(0) < query_len:
219
+ position_indices = torch.arange(query_len, dtype=torch.long).unsqueeze(1) \
220
+ - torch.arange(query_len, dtype=torch.long).unsqueeze(0)
221
+ position_indices = self.make_log_bucket_position(position_indices, self.config.position_bucket_size, 512)
222
+ position_indices = self.config.position_bucket_size - 1 + position_indices
223
+ self.position_indices = position_indices.to(hidden_states.device)
224
+
225
+ hidden_states = self.pre_layer_norm(hidden_states)
226
+
227
+ query, key = self.in_proj_qk(hidden_states).chunk(2, dim=2) # shape: [T, B, D]
228
+ value, gate = self.in_proj_vg(hidden_states).chunk(2, dim=2) # shape: [T, B, D]
229
+ gate = F.gelu(gate)
230
+
231
+ query = query.reshape(query_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
232
+ key = key.reshape(key_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
233
+ value = value.view(key_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
234
+
235
+ attention_scores = torch.bmm(query, key.transpose(1, 2) * self.scale)
236
+
237
+ query_pos, key_pos = self.in_proj_qk(self.dropout(relative_embedding)).chunk(2, dim=-1) # shape: [2T-1, D]
238
+ query_pos = query_pos.view(-1, self.num_heads, self.head_size) # shape: [2T-1, H, D]
239
+ key_pos = key_pos.view(-1, self.num_heads, self.head_size) # shape: [2T-1, H, D]
240
+
241
+ query = query.view(batch_size, self.num_heads, query_len, self.head_size)
242
+ key = key.view(batch_size, self.num_heads, query_len, self.head_size)
243
+
244
+ attention_c_p = torch.einsum("bhqd,khd->bhqk", query, key_pos.squeeze(1) * self.scale)
245
+ attention_p_c = torch.einsum("bhkd,qhd->bhqk", key * self.scale, query_pos.squeeze(1))
246
+
247
+ position_indices = self.position_indices[:query_len, :key_len].expand(batch_size, self.num_heads, -1, -1)
248
+ attention_c_p = attention_c_p.gather(3, position_indices)
249
+ attention_p_c = attention_p_c.gather(2, position_indices)
250
+
251
+ attention_scores = attention_scores.view(batch_size, self.num_heads, query_len, key_len)
252
+ attention_scores.add_(attention_c_p)
253
+ attention_scores.add_(attention_p_c)
254
+
255
+ attention_probs = MaskedSoftmax.apply(attention_scores, attention_mask, -1)
256
+
257
+ attention_probs = self.dropout(attention_probs)
258
+ context = torch.bmm(attention_probs.flatten(0, 1), value) # shape: [B*H, Q, D]
259
+ context = context.transpose(0, 1).reshape(context.size(1), -1, self.hidden_size) # shape: [Q, B, H*D]
260
+ context = context * gate
261
+ context = self.post_layer_norm(context)
262
+ context = self.out_proj(context)
263
+ context = self.dropout(context)
264
+
265
+ return context, attention_probs.detach()
266
+
267
+
268
+ class Embedding(nn.Module):
269
+ def __init__(self, config):
270
+ super().__init__()
271
+ self.hidden_size = config.hidden_size
272
+
273
+ self.word_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
274
+ self.word_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False)
275
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
276
+
277
+ self.relative_embedding = nn.Parameter(torch.empty(2 * config.position_bucket_size - 1, config.hidden_size))
278
+ self.relative_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
279
+
280
+ def forward(self, input_ids):
281
+ word_embedding = self.dropout(self.word_layer_norm(self.word_embedding(input_ids)))
282
+ relative_embeddings = self.relative_layer_norm(self.relative_embedding)
283
+ return word_embedding, relative_embeddings
284
+
285
+
286
+ #
287
+ # HuggingFace wrappers
288
+ #
289
+
290
+ class LtgbertPreTrainedModel(PreTrainedModel):
291
+ config_class = LtgbertConfig
292
+ supports_gradient_checkpointing = False
293
+
294
+ def _set_gradient_checkpointing(self, module, value=False):
295
+ raise NotImplementedError("Gradient checkpointing is not supported by this model")
296
+
297
+ def _init_weights(self, module):
298
+ std = math.sqrt(2.0 / (5.0 * self.hidden_size))
299
+
300
+ if isinstance(module, nn.Linear):
301
+ nn.init.trunc_normal_(module.weight.data, mean=0.0, std=std, a=-2*std, b=2*std)
302
+ if module.bias is not None:
303
+ module.bias.data.zero_()
304
+ elif isinstance(module, nn.Embedding):
305
+ nn.init.trunc_normal_(module.weight.data, mean=0.0, std=std, a=-2*std, b=2*std)
306
+ elif isinstance(module, nn.LayerNorm):
307
+ module.bias.data.zero_()
308
+ module.weight.data.fill_(1.0)
309
+
310
+
311
+ class LtgbertModel(LtgbertPreTrainedModel):
312
+ def __init__(self, config, add_mlm_layer=False, **kwargs):
313
+ super().__init__(config, **kwargs)
314
+ self.config = config
315
+ self.hidden_size = config.hidden_size
316
+
317
+ self.embedding = Embedding(config)
318
+ self.transformer = Encoder(config)
319
+ self.classifier = MaskClassifier(config, self.embedding.word_embedding.weight) if add_mlm_layer else None
320
+
321
+ def get_input_embeddings(self):
322
+ return self.embedding.word_embedding
323
+
324
+ def set_input_embeddings(self, value):
325
+ self.embedding.word_embedding = value
326
+
327
+ def get_contextualized_embeddings(
328
+ self,
329
+ input_ids: Optional[torch.Tensor] = None,
330
+ attention_mask: Optional[torch.Tensor] = None
331
+ ) -> List[torch.Tensor]:
332
+ if input_ids is not None:
333
+ input_shape = input_ids.size()
334
+ else:
335
+ raise ValueError("You have to specify input_ids")
336
+
337
+ batch_size, seq_length = input_shape
338
+ device = input_ids.device
339
+
340
+ if attention_mask is None:
341
+ attention_mask = torch.zeros(batch_size, seq_length, dtype=torch.bool, device=device)
342
+ else:
343
+ attention_mask = ~attention_mask.bool()
344
+
345
+ if self.config.is_decoder:
346
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) | torch.triu(torch.ones(seq_length, seq_length, dtype=torch.bool, device=device), 1).unsqueeze(0).unsqueeze(0)
347
+ else:
348
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
349
+
350
+ static_embeddings, relative_embedding = self.embedding(input_ids.t())
351
+ contextualized_embeddings, attention_probs = self.transformer(static_embeddings, attention_mask, relative_embedding)
352
+ contextualized_embeddings = [e.transpose(0, 1) for e in contextualized_embeddings]
353
+ last_layer = contextualized_embeddings[-1]
354
+ contextualized_embeddings = [contextualized_embeddings[0]] + [
355
+ contextualized_embeddings[i] - contextualized_embeddings[i - 1]
356
+ for i in range(1, len(contextualized_embeddings))
357
+ ]
358
+ return last_layer, contextualized_embeddings, attention_probs
359
+
360
+ def forward(
361
+ self,
362
+ input_ids: Optional[torch.Tensor] = None,
363
+ attention_mask: Optional[torch.Tensor] = None,
364
+ token_type_ids: Optional[torch.Tensor] = None,
365
+ position_ids: Optional[torch.Tensor] = None,
366
+ output_hidden_states: Optional[bool] = None,
367
+ output_attentions: Optional[bool] = None,
368
+ return_dict: Optional[bool] = None,
369
+ **kwargs
370
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutput]:
371
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
372
+
373
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
374
+
375
+ if not return_dict:
376
+ return (
377
+ sequence_output,
378
+ *([contextualized_embeddings] if output_hidden_states else []),
379
+ *([attention_probs] if output_attentions else [])
380
+ )
381
+
382
+ return BaseModelOutput(
383
+ last_hidden_state=sequence_output,
384
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
385
+ attentions=attention_probs if output_attentions else None
386
+ )
387
+
388
+
389
+ class LtgbertForMaskedLM(LtgbertModel):
390
+ _keys_to_ignore_on_load_unexpected = ["head"]
391
+
392
+ def __init__(self, config, **kwargs):
393
+ super().__init__(config, add_mlm_layer=True, **kwargs)
394
+
395
+ def get_output_embeddings(self):
396
+ return self.classifier.nonlinearity[-1].weight
397
+
398
+ def set_output_embeddings(self, new_embeddings):
399
+ self.classifier.nonlinearity[-1].weight = new_embeddings
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_hidden_states: Optional[bool] = None,
408
+ output_attentions: Optional[bool] = None,
409
+ return_dict: Optional[bool] = None,
410
+ labels: Optional[torch.LongTensor] = None,
411
+ **kwargs
412
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
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
+ subword_prediction = self.classifier(sequence_output)
417
+ subword_prediction[:, :, :16+1] = float("-inf")
418
+
419
+ masked_lm_loss = None
420
+ if labels is not None:
421
+ labels_flatten = labels[:, 1:].flatten()
422
+ subword_prediction_flatten = subword_prediction[:, :-1].flatten(0, 1)
423
+ masked_lm_loss = F.cross_entropy(subword_prediction_flatten, labels_flatten)
424
+
425
+ if not return_dict:
426
+ output = (
427
+ subword_prediction,
428
+ *([contextualized_embeddings] if output_hidden_states else []),
429
+ *([attention_probs] if output_attentions else [])
430
+ )
431
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
432
+
433
+ return MaskedLMOutput(
434
+ loss=masked_lm_loss,
435
+ logits=subword_prediction,
436
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
437
+ attentions=attention_probs if output_attentions else None
438
+ )
439
+
440
+
441
+ class Classifier(nn.Module):
442
+ def __init__(self, config, num_labels: int):
443
+ super().__init__()
444
+
445
+ self.temperature = config.temperature
446
+
447
+ drop_out = getattr(config, "cls_dropout", None)
448
+ drop_out = config.hidden_dropout_prob if drop_out is None else drop_out
449
+
450
+ self.nonlinearity = nn.Sequential(
451
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
452
+ nn.Linear(config.hidden_size, config.hidden_size),
453
+ nn.GELU(),
454
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
455
+ nn.Dropout(drop_out),
456
+ nn.Linear(config.hidden_size, num_labels)
457
+ )
458
+
459
+ def forward(self, x):
460
+ x = self.nonlinearity(x) / self.temperature
461
+ return x
462
+
463
+
464
+ class LtgbertForCausalLM(LtgbertModel):
465
+ _keys_to_ignore_on_load_unexpected = ["head"]
466
+
467
+ def __init__(self, config, **kwargs):
468
+ config.is_decoder = True
469
+ super().__init__(config, add_mlm_layer=True, **kwargs)
470
+
471
+ def get_output_embeddings(self):
472
+ return self.classifier.nonlinearity[-1].weight
473
+
474
+ def set_output_embeddings(self, new_embeddings):
475
+ self.classifier.nonlinearity[-1].weight = new_embeddings
476
+
477
+ def get_input_embeddings(self):
478
+ return self.embedding.word_embedding
479
+
480
+ def set_input_embeddings(self, value):
481
+ self.embedding.word_embedding = value
482
+
483
+ def set_decoder(self, decoder):
484
+ self.transformer = decoder
485
+
486
+ def get_decoder(self):
487
+ return self.transformer
488
+
489
+ def can_generate(self):
490
+ return True
491
+
492
+ def forward(
493
+ self,
494
+ input_ids: torch.LongTensor = None,
495
+ attention_mask: Optional[torch.Tensor] = None,
496
+ position_ids: Optional[torch.LongTensor] = None,
497
+ past_key_values = None,
498
+ inputs_embeds: Optional[torch.FloatTensor] = None,
499
+ labels: Optional[torch.LongTensor] = None,
500
+ use_cache: Optional[bool] = None,
501
+ cache_position: Optional[torch.LongTensor] = None,
502
+ output_attentions: Optional[bool] = None,
503
+ output_hidden_states: Optional[bool] = None,
504
+ return_dict: Optional[bool] = None
505
+ ) -> Union[Tuple, CausalLMOutput]:
506
+
507
+ assert inputs_embeds is None, "inputs_embeds is not supported for now"
508
+ assert past_key_values is None, "past_key_values is not supported for now"
509
+ assert not use_cache, "use_cache is not supported for now"
510
+ # assert cache_position is None, "cache_position is not supported for now"
511
+
512
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
513
+ subword_prediction = self.classifier(sequence_output)
514
+ subword_prediction[:, :, :16+1] = float("-inf")
515
+
516
+ masked_lm_loss = None
517
+ if labels is not None:
518
+ labels_flatten = labels[:, 1:].flatten()
519
+ subword_prediction_flatten = subword_prediction[:, :-1].flatten(0, 1)
520
+ masked_lm_loss = F.cross_entropy(subword_prediction_flatten, labels_flatten)
521
+
522
+ if not return_dict:
523
+ output = (
524
+ subword_prediction,
525
+ *([contextualized_embeddings] if output_hidden_states else []),
526
+ *([attention_probs] if output_attentions else [])
527
+ )
528
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
529
+
530
+ return MaskedLMOutput(
531
+ loss=masked_lm_loss,
532
+ logits=subword_prediction,
533
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
534
+ attentions=attention_probs if output_attentions else None
535
+ )
536
+
537
+
538
+ def prepare_inputs_for_generation(
539
+ self,
540
+ input_ids,
541
+ past_key_values=None,
542
+ attention_mask=None,
543
+ inputs_embeds=None,
544
+ cache_position=None,
545
+ position_ids=None,
546
+ use_cache=True,
547
+ num_logits_to_keep=None,
548
+ **kwargs,
549
+ ):
550
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
551
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
552
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
553
+ if past_key_values is not None:
554
+ if inputs_embeds is not None: # Exception 1
555
+ input_ids = input_ids[:, -cache_position.shape[0] :]
556
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
557
+ input_ids = input_ids[:, cache_position]
558
+
559
+ if attention_mask is not None and position_ids is None:
560
+ # create position_ids on the fly for batch generation
561
+ position_ids = attention_mask.long().cumsum(-1) - 1
562
+ position_ids.masked_fill_(attention_mask == 0, 1)
563
+ if past_key_values:
564
+ position_ids = position_ids[:, -input_ids.shape[1] :]
565
+
566
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
567
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
568
+
569
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
570
+ if inputs_embeds is not None and cache_position[0] == 0:
571
+ model_inputs = {"inputs_embeds": inputs_embeds}
572
+ else:
573
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
574
+
575
+ if num_logits_to_keep is not None:
576
+ model_inputs["num_logits_to_keep"] = num_logits_to_keep
577
+
578
+ model_inputs.update(
579
+ {
580
+ "position_ids": position_ids,
581
+ "cache_position": cache_position,
582
+ "past_key_values": past_key_values,
583
+ "use_cache": use_cache,
584
+ "attention_mask": attention_mask,
585
+ }
586
+ )
587
+ return model_inputs
588
+
589
+
590
+
591
+ class LtgbertForSequenceClassification(LtgbertModel):
592
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
593
+ _keys_to_ignore_on_load_missing = ["head"]
594
+
595
+ def __init__(self, config, **kwargs):
596
+ super().__init__(config, add_mlm_layer=False, **kwargs)
597
+
598
+ self.num_labels = config.num_labels
599
+ self.head = Classifier(config, self.num_labels)
600
+
601
+ def forward(
602
+ self,
603
+ input_ids: Optional[torch.Tensor] = None,
604
+ attention_mask: Optional[torch.Tensor] = None,
605
+ token_type_ids: Optional[torch.Tensor] = None,
606
+ position_ids: Optional[torch.Tensor] = None,
607
+ output_attentions: Optional[bool] = None,
608
+ output_hidden_states: Optional[bool] = None,
609
+ return_dict: Optional[bool] = None,
610
+ labels: Optional[torch.LongTensor] = None,
611
+ **kwargs
612
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
613
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
614
+
615
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
616
+ logits = self.head(sequence_output[:, 0, :])
617
+
618
+ loss = None
619
+ if labels is not None:
620
+ if self.config.problem_type is None:
621
+ if self.num_labels == 1:
622
+ self.config.problem_type = "regression"
623
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
624
+ self.config.problem_type = "single_label_classification"
625
+ else:
626
+ self.config.problem_type = "multi_label_classification"
627
+
628
+ if self.config.problem_type == "regression":
629
+ loss_fct = nn.MSELoss()
630
+ if self.num_labels == 1:
631
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
632
+ else:
633
+ loss = loss_fct(logits, labels)
634
+ elif self.config.problem_type == "single_label_classification":
635
+ loss_fct = nn.CrossEntropyLoss()
636
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
637
+ elif self.config.problem_type == "multi_label_classification":
638
+ loss_fct = nn.BCEWithLogitsLoss()
639
+ loss = loss_fct(logits, labels)
640
+
641
+ if not return_dict:
642
+ output = (
643
+ logits,
644
+ *([contextualized_embeddings] if output_hidden_states else []),
645
+ *([attention_probs] if output_attentions else [])
646
+ )
647
+ return ((loss,) + output) if loss is not None else output
648
+
649
+ return SequenceClassifierOutput(
650
+ loss=loss,
651
+ logits=logits,
652
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
653
+ attentions=attention_probs if output_attentions else None
654
+ )
655
+
656
+
657
+ class LtgbertForTokenClassification(LtgbertModel):
658
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
659
+ _keys_to_ignore_on_load_missing = ["head"]
660
+
661
+ def __init__(self, config, **kwargs):
662
+ super().__init__(config, add_mlm_layer=False, **kwargs)
663
+
664
+ self.num_labels = config.num_labels
665
+ self.head = Classifier(config, self.num_labels)
666
+
667
+ def forward(
668
+ self,
669
+ input_ids: Optional[torch.Tensor] = None,
670
+ attention_mask: Optional[torch.Tensor] = None,
671
+ token_type_ids: Optional[torch.Tensor] = None,
672
+ position_ids: Optional[torch.Tensor] = None,
673
+ output_attentions: Optional[bool] = None,
674
+ output_hidden_states: Optional[bool] = None,
675
+ return_dict: Optional[bool] = None,
676
+ labels: Optional[torch.LongTensor] = None,
677
+ **kwargs
678
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
679
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
680
+
681
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
682
+ logits = self.head(sequence_output)
683
+
684
+ loss = None
685
+ if labels is not None:
686
+ loss_fct = nn.CrossEntropyLoss()
687
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
688
+
689
+ if not return_dict:
690
+ output = (
691
+ logits,
692
+ *([contextualized_embeddings] if output_hidden_states else []),
693
+ *([attention_probs] if output_attentions else [])
694
+ )
695
+ return ((loss,) + output) if loss is not None else output
696
+
697
+ return TokenClassifierOutput(
698
+ loss=loss,
699
+ logits=logits,
700
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
701
+ attentions=attention_probs if output_attentions else None
702
+ )
703
+
704
+
705
+ class LtgbertForQuestionAnswering(LtgbertModel):
706
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
707
+ _keys_to_ignore_on_load_missing = ["head"]
708
+
709
+ def __init__(self, config, **kwargs):
710
+ super().__init__(config, add_mlm_layer=False, **kwargs)
711
+
712
+ self.num_labels = config.num_labels
713
+ self.head = Classifier(config, self.num_labels)
714
+
715
+ def forward(
716
+ self,
717
+ input_ids: Optional[torch.Tensor] = None,
718
+ attention_mask: Optional[torch.Tensor] = None,
719
+ token_type_ids: Optional[torch.Tensor] = None,
720
+ position_ids: Optional[torch.Tensor] = None,
721
+ output_attentions: Optional[bool] = None,
722
+ output_hidden_states: Optional[bool] = None,
723
+ return_dict: Optional[bool] = None,
724
+ start_positions: Optional[torch.Tensor] = None,
725
+ end_positions: Optional[torch.Tensor] = None,
726
+ **kwargs
727
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
728
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
729
+
730
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
731
+ logits = self.head(sequence_output)
732
+
733
+ start_logits, end_logits = logits.split(1, dim=-1)
734
+ start_logits = start_logits.squeeze(-1).contiguous()
735
+ end_logits = end_logits.squeeze(-1).contiguous()
736
+
737
+ total_loss = None
738
+ if start_positions is not None and end_positions is not None:
739
+ # If we are on multi-GPU, split add a dimension
740
+ if len(start_positions.size()) > 1:
741
+ start_positions = start_positions.squeeze(-1)
742
+ if len(end_positions.size()) > 1:
743
+ end_positions = end_positions.squeeze(-1)
744
+
745
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
746
+ ignored_index = start_logits.size(1)
747
+ start_positions = start_positions.clamp(0, ignored_index)
748
+ end_positions = end_positions.clamp(0, ignored_index)
749
+
750
+ loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
751
+ start_loss = loss_fct(start_logits, start_positions)
752
+ end_loss = loss_fct(end_logits, end_positions)
753
+ total_loss = (start_loss + end_loss) / 2
754
+
755
+ if not return_dict:
756
+ output = (
757
+ start_logits,
758
+ end_logits,
759
+ *([contextualized_embeddings] if output_hidden_states else []),
760
+ *([attention_probs] if output_attentions else [])
761
+ )
762
+ return ((total_loss,) + output) if total_loss is not None else output
763
+
764
+ return QuestionAnsweringModelOutput(
765
+ loss=total_loss,
766
+ start_logits=start_logits,
767
+ end_logits=end_logits,
768
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
769
+ attentions=attention_probs if output_attentions else None
770
+ )
771
+
772
+
773
+ class LtgbertForMultipleChoice(LtgbertModel):
774
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
775
+ _keys_to_ignore_on_load_missing = ["head"]
776
+
777
+ def __init__(self, config, **kwargs):
778
+ super().__init__(config, add_mlm_layer=False, **kwargs)
779
+
780
+ self.num_labels = getattr(config, "num_labels", 2)
781
+ self.head = Classifier(config, self.num_labels)
782
+
783
+ def forward(
784
+ self,
785
+ input_ids: Optional[torch.Tensor] = None,
786
+ attention_mask: Optional[torch.Tensor] = None,
787
+ token_type_ids: Optional[torch.Tensor] = None,
788
+ position_ids: Optional[torch.Tensor] = None,
789
+ labels: Optional[torch.Tensor] = None,
790
+ output_attentions: Optional[bool] = None,
791
+ output_hidden_states: Optional[bool] = None,
792
+ return_dict: Optional[bool] = None,
793
+ **kwargs
794
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
795
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
796
+ num_choices = input_ids.shape[1]
797
+
798
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1))
799
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
800
+
801
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(flat_input_ids, flat_attention_mask)
802
+ logits = self.head(sequence_output)
803
+ reshaped_logits = logits.view(-1, num_choices)
804
+
805
+ loss = None
806
+ if labels is not None:
807
+ loss_fct = nn.CrossEntropyLoss()
808
+ loss = loss_fct(reshaped_logits, labels)
809
+
810
+ if not return_dict:
811
+ output = (
812
+ reshaped_logits,
813
+ *([contextualized_embeddings] if output_hidden_states else []),
814
+ *([attention_probs] if output_attentions else [])
815
+ )
816
+ return ((loss,) + output) if loss is not None else output
817
+
818
+ return MultipleChoiceModelOutput(
819
+ loss=loss,
820
+ logits=reshaped_logits,
821
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
822
+ attentions=attention_probs if output_attentions else None
823
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9ebfa40e36af2133d3214287675c9793aa379c3f888f600cef27b7a6394e045c
3
+ size 144795453
spacial_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "sep_token": "</s>", "pad_token": "<oad>", "cls_token": "<s>", "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,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tokenizer_class": "PreTrainedTokenizerFast",
3
+ "bos_token": "<s>",
4
+ "eos_token": "</s>",
5
+ "unk_token": "<unk>",
6
+ "sep_token": "</s>",
7
+ "pad_token": "<pad>",
8
+ "cls_token": "<s>",
9
+ "mask_token": "<mask>"
10
+ }