ltg
/

PyTorch
English
custom_code
davda54 commited on
Commit
7f321a9
β€’
1 Parent(s): 747a3ed

initial upload

Browse files
__init__.py ADDED
File without changes
config.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": 1024,
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
+ }
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=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
+ **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,822 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
322
+ def get_input_embeddings(self):
323
+ return self.embedding.word_embedding
324
+
325
+ def set_input_embeddings(self, value):
326
+ self.embedding.word_embedding = value
327
+
328
+ def get_contextualized_embeddings(
329
+ self,
330
+ input_ids: Optional[torch.Tensor] = None,
331
+ attention_mask: Optional[torch.Tensor] = None
332
+ ) -> List[torch.Tensor]:
333
+ if input_ids is not None:
334
+ input_shape = input_ids.size()
335
+ else:
336
+ raise ValueError("You have to specify input_ids")
337
+
338
+ batch_size, seq_length = input_shape
339
+ device = input_ids.device
340
+
341
+ if attention_mask is None:
342
+ attention_mask = torch.zeros(batch_size, seq_length, dtype=torch.bool, device=device)
343
+ else:
344
+ attention_mask = ~attention_mask.bool()
345
+
346
+ if self.config.is_decoder:
347
+ 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)
348
+ else:
349
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
350
+
351
+ static_embeddings, relative_embedding = self.embedding(input_ids.t())
352
+ contextualized_embeddings, attention_probs = self.transformer(static_embeddings, attention_mask, relative_embedding)
353
+ contextualized_embeddings = [e.transpose(0, 1) for e in contextualized_embeddings]
354
+ last_layer = contextualized_embeddings[-1]
355
+ contextualized_embeddings = [contextualized_embeddings[0]] + [
356
+ contextualized_embeddings[i] - contextualized_embeddings[i - 1]
357
+ for i in range(1, len(contextualized_embeddings))
358
+ ]
359
+ return last_layer, contextualized_embeddings, attention_probs
360
+
361
+ def forward(
362
+ self,
363
+ input_ids: Optional[torch.Tensor] = None,
364
+ attention_mask: Optional[torch.Tensor] = None,
365
+ token_type_ids: Optional[torch.Tensor] = None,
366
+ position_ids: Optional[torch.Tensor] = None,
367
+ output_hidden_states: Optional[bool] = None,
368
+ output_attentions: Optional[bool] = None,
369
+ return_dict: Optional[bool] = None,
370
+ **kwargs
371
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutput]:
372
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
373
+
374
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
375
+
376
+ if not return_dict:
377
+ return (
378
+ sequence_output,
379
+ *([contextualized_embeddings] if output_hidden_states else []),
380
+ *([attention_probs] if output_attentions else [])
381
+ )
382
+
383
+ return BaseModelOutput(
384
+ last_hidden_state=sequence_output,
385
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
386
+ attentions=attention_probs if output_attentions else None
387
+ )
388
+
389
+
390
+ class LtgbertForMaskedLM(LtgbertModel):
391
+ _keys_to_ignore_on_load_unexpected = ["head"]
392
+
393
+ def __init__(self, config, **kwargs):
394
+ super().__init__(config, add_mlm_layer=True, **kwargs)
395
+
396
+ def get_output_embeddings(self):
397
+ return self.classifier.nonlinearity[-1].weight
398
+
399
+ def set_output_embeddings(self, new_embeddings):
400
+ self.classifier.nonlinearity[-1].weight = new_embeddings
401
+
402
+ def forward(
403
+ self,
404
+ input_ids: Optional[torch.Tensor] = None,
405
+ attention_mask: Optional[torch.Tensor] = None,
406
+ token_type_ids: Optional[torch.Tensor] = None,
407
+ position_ids: Optional[torch.Tensor] = None,
408
+ output_hidden_states: Optional[bool] = None,
409
+ output_attentions: Optional[bool] = None,
410
+ return_dict: Optional[bool] = None,
411
+ labels: Optional[torch.LongTensor] = None,
412
+ **kwargs
413
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
414
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
415
+
416
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
417
+ subword_prediction = self.classifier(sequence_output)
418
+ subword_prediction[:, :, :16+1] = float("-inf")
419
+
420
+ masked_lm_loss = None
421
+ if labels is not None:
422
+ labels_flatten = labels[:, 1:].flatten()
423
+ subword_prediction_flatten = subword_prediction[:, :-1].flatten(0, 1)
424
+ masked_lm_loss = F.cross_entropy(subword_prediction_flatten, labels_flatten)
425
+
426
+ if not return_dict:
427
+ output = (
428
+ subword_prediction,
429
+ *([contextualized_embeddings] if output_hidden_states else []),
430
+ *([attention_probs] if output_attentions else [])
431
+ )
432
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
433
+
434
+ return MaskedLMOutput(
435
+ loss=masked_lm_loss,
436
+ logits=subword_prediction,
437
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
438
+ attentions=attention_probs if output_attentions else None
439
+ )
440
+
441
+
442
+ class Classifier(nn.Module):
443
+ def __init__(self, config, num_labels: int):
444
+ super().__init__()
445
+
446
+ drop_out = getattr(config, "cls_dropout", None)
447
+ drop_out = config.hidden_dropout_prob if drop_out is None else drop_out
448
+
449
+ self.nonlinearity = nn.Sequential(
450
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
451
+ nn.Linear(config.hidden_size, config.hidden_size),
452
+ nn.GELU(),
453
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
454
+ nn.Dropout(drop_out),
455
+ nn.Linear(config.hidden_size, num_labels)
456
+ )
457
+
458
+ def forward(self, x):
459
+ x = self.nonlinearity(x)
460
+ return x
461
+
462
+
463
+ class LtgbertForCausalLM(LtgbertModel):
464
+ _keys_to_ignore_on_load_unexpected = ["head"]
465
+
466
+ def __init__(self, config, **kwargs):
467
+ config.is_decoder = True
468
+ super().__init__(config, add_mlm_layer=True, **kwargs)
469
+
470
+ def get_output_embeddings(self):
471
+ return self.classifier.nonlinearity[-1].weight
472
+
473
+ def set_output_embeddings(self, new_embeddings):
474
+ self.classifier.nonlinearity[-1].weight = new_embeddings
475
+
476
+ def get_input_embeddings(self):
477
+ return self.embedding.word_embedding
478
+
479
+ def set_input_embeddings(self, value):
480
+ self.embedding.word_embedding = value
481
+
482
+ def set_decoder(self, decoder):
483
+ self.transformer = decoder
484
+
485
+ def get_decoder(self):
486
+ return self.transformer
487
+
488
+ def can_generate(self):
489
+ return True
490
+
491
+ def forward(
492
+ self,
493
+ input_ids: torch.LongTensor = None,
494
+ attention_mask: Optional[torch.Tensor] = None,
495
+ position_ids: Optional[torch.LongTensor] = None,
496
+ past_key_values = None,
497
+ inputs_embeds: Optional[torch.FloatTensor] = None,
498
+ labels: Optional[torch.LongTensor] = None,
499
+ use_cache: Optional[bool] = None,
500
+ cache_position: Optional[torch.LongTensor] = None,
501
+ output_attentions: Optional[bool] = None,
502
+ output_hidden_states: Optional[bool] = None,
503
+ return_dict: Optional[bool] = None
504
+ ) -> Union[Tuple, CausalLMOutput]:
505
+
506
+ assert inputs_embeds is None, "inputs_embeds is not supported for now"
507
+ assert past_key_values is None, "past_key_values is not supported for now"
508
+ assert not use_cache, "use_cache is not supported for now"
509
+ # assert cache_position is None, "cache_position is not supported for now"
510
+
511
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
512
+ subword_prediction = self.classifier(sequence_output)
513
+ subword_prediction[:, :, :16+1] = float("-inf")
514
+
515
+ masked_lm_loss = None
516
+ if labels is not None:
517
+ labels_flatten = labels[:, 1:].flatten()
518
+ subword_prediction_flatten = subword_prediction[:, :-1].flatten(0, 1)
519
+ masked_lm_loss = F.cross_entropy(subword_prediction_flatten, labels_flatten)
520
+
521
+ if not return_dict:
522
+ output = (
523
+ subword_prediction,
524
+ *([contextualized_embeddings] if output_hidden_states else []),
525
+ *([attention_probs] if output_attentions else [])
526
+ )
527
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
528
+
529
+ return MaskedLMOutput(
530
+ loss=masked_lm_loss,
531
+ logits=subword_prediction,
532
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
533
+ attentions=attention_probs if output_attentions else None
534
+ )
535
+
536
+
537
+ def prepare_inputs_for_generation(
538
+ self,
539
+ input_ids,
540
+ past_key_values=None,
541
+ attention_mask=None,
542
+ inputs_embeds=None,
543
+ cache_position=None,
544
+ position_ids=None,
545
+ use_cache=True,
546
+ num_logits_to_keep=None,
547
+ **kwargs,
548
+ ):
549
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
550
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
551
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
552
+ if past_key_values is not None:
553
+ if inputs_embeds is not None: # Exception 1
554
+ input_ids = input_ids[:, -cache_position.shape[0] :]
555
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
556
+ input_ids = input_ids[:, cache_position]
557
+
558
+ if attention_mask is not None and position_ids is None:
559
+ # create position_ids on the fly for batch generation
560
+ position_ids = attention_mask.long().cumsum(-1) - 1
561
+ position_ids.masked_fill_(attention_mask == 0, 1)
562
+ if past_key_values:
563
+ position_ids = position_ids[:, -input_ids.shape[1] :]
564
+
565
+ # 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.
566
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
567
+
568
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
569
+ if inputs_embeds is not None and cache_position[0] == 0:
570
+ model_inputs = {"inputs_embeds": inputs_embeds}
571
+ else:
572
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
573
+
574
+ if num_logits_to_keep is not None:
575
+ model_inputs["num_logits_to_keep"] = num_logits_to_keep
576
+
577
+ model_inputs.update(
578
+ {
579
+ "position_ids": position_ids,
580
+ "cache_position": cache_position,
581
+ "past_key_values": past_key_values,
582
+ "use_cache": use_cache,
583
+ "attention_mask": attention_mask,
584
+ }
585
+ )
586
+ return model_inputs
587
+
588
+
589
+
590
+ class LtgbertForSequenceClassification(LtgbertModel):
591
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
592
+ _keys_to_ignore_on_load_missing = ["head"]
593
+
594
+ def __init__(self, config, **kwargs):
595
+ super().__init__(config, add_mlm_layer=False, **kwargs)
596
+
597
+ self.num_labels = config.num_labels
598
+ self.head = Classifier(config, self.num_labels)
599
+
600
+ def forward(
601
+ self,
602
+ input_ids: Optional[torch.Tensor] = None,
603
+ attention_mask: Optional[torch.Tensor] = None,
604
+ token_type_ids: Optional[torch.Tensor] = None,
605
+ position_ids: Optional[torch.Tensor] = None,
606
+ output_attentions: Optional[bool] = None,
607
+ output_hidden_states: Optional[bool] = None,
608
+ return_dict: Optional[bool] = None,
609
+ labels: Optional[torch.LongTensor] = None,
610
+ **kwargs
611
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
612
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
613
+
614
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
615
+ logits = self.head(sequence_output[:, 0, :])
616
+
617
+ loss = None
618
+ if labels is not None:
619
+ if self.config.problem_type is None:
620
+ if self.num_labels == 1:
621
+ self.config.problem_type = "regression"
622
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
623
+ self.config.problem_type = "single_label_classification"
624
+ else:
625
+ self.config.problem_type = "multi_label_classification"
626
+
627
+ if self.config.problem_type == "regression":
628
+ loss_fct = nn.MSELoss()
629
+ if self.num_labels == 1:
630
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
631
+ else:
632
+ loss = loss_fct(logits, labels)
633
+ elif self.config.problem_type == "single_label_classification":
634
+ loss_fct = nn.CrossEntropyLoss()
635
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
636
+ elif self.config.problem_type == "multi_label_classification":
637
+ loss_fct = nn.BCEWithLogitsLoss()
638
+ loss = loss_fct(logits, labels)
639
+
640
+ if not return_dict:
641
+ output = (
642
+ logits,
643
+ *([contextualized_embeddings] if output_hidden_states else []),
644
+ *([attention_probs] if output_attentions else [])
645
+ )
646
+ return ((loss,) + output) if loss is not None else output
647
+
648
+ return SequenceClassifierOutput(
649
+ loss=loss,
650
+ logits=logits,
651
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
652
+ attentions=attention_probs if output_attentions else None
653
+ )
654
+
655
+
656
+ class LtgbertForTokenClassification(LtgbertModel):
657
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
658
+ _keys_to_ignore_on_load_missing = ["head"]
659
+
660
+ def __init__(self, config, **kwargs):
661
+ super().__init__(config, add_mlm_layer=False, **kwargs)
662
+
663
+ self.num_labels = config.num_labels
664
+ self.head = Classifier(config, self.num_labels)
665
+
666
+ def forward(
667
+ self,
668
+ input_ids: Optional[torch.Tensor] = None,
669
+ attention_mask: Optional[torch.Tensor] = None,
670
+ token_type_ids: Optional[torch.Tensor] = None,
671
+ position_ids: Optional[torch.Tensor] = None,
672
+ output_attentions: Optional[bool] = None,
673
+ output_hidden_states: Optional[bool] = None,
674
+ return_dict: Optional[bool] = None,
675
+ labels: Optional[torch.LongTensor] = None,
676
+ **kwargs
677
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
678
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
679
+
680
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
681
+ logits = self.head(sequence_output)
682
+
683
+ loss = None
684
+ if labels is not None:
685
+ loss_fct = nn.CrossEntropyLoss()
686
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
687
+
688
+ if not return_dict:
689
+ output = (
690
+ logits,
691
+ *([contextualized_embeddings] if output_hidden_states else []),
692
+ *([attention_probs] if output_attentions else [])
693
+ )
694
+ return ((loss,) + output) if loss is not None else output
695
+
696
+ return TokenClassifierOutput(
697
+ loss=loss,
698
+ logits=logits,
699
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
700
+ attentions=attention_probs if output_attentions else None
701
+ )
702
+
703
+
704
+ class LtgbertForQuestionAnswering(LtgbertModel):
705
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
706
+ _keys_to_ignore_on_load_missing = ["head"]
707
+
708
+ def __init__(self, config, **kwargs):
709
+ super().__init__(config, add_mlm_layer=False, **kwargs)
710
+
711
+ self.num_labels = config.num_labels
712
+ self.head = Classifier(config, self.num_labels)
713
+
714
+ def forward(
715
+ self,
716
+ input_ids: Optional[torch.Tensor] = None,
717
+ attention_mask: Optional[torch.Tensor] = None,
718
+ token_type_ids: Optional[torch.Tensor] = None,
719
+ position_ids: Optional[torch.Tensor] = None,
720
+ output_attentions: Optional[bool] = None,
721
+ output_hidden_states: Optional[bool] = None,
722
+ return_dict: Optional[bool] = None,
723
+ start_positions: Optional[torch.Tensor] = None,
724
+ end_positions: Optional[torch.Tensor] = None,
725
+ **kwargs
726
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
727
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
728
+
729
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
730
+ logits = self.head(sequence_output)
731
+
732
+ start_logits, end_logits = logits.split(1, dim=-1)
733
+ start_logits = start_logits.squeeze(-1).contiguous()
734
+ end_logits = end_logits.squeeze(-1).contiguous()
735
+
736
+ total_loss = None
737
+ if start_positions is not None and end_positions is not None:
738
+ # If we are on multi-GPU, split add a dimension
739
+ if len(start_positions.size()) > 1:
740
+ start_positions = start_positions.squeeze(-1)
741
+ if len(end_positions.size()) > 1:
742
+ end_positions = end_positions.squeeze(-1)
743
+
744
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
745
+ ignored_index = start_logits.size(1)
746
+ start_positions = start_positions.clamp(0, ignored_index)
747
+ end_positions = end_positions.clamp(0, ignored_index)
748
+
749
+ loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
750
+ start_loss = loss_fct(start_logits, start_positions)
751
+ end_loss = loss_fct(end_logits, end_positions)
752
+ total_loss = (start_loss + end_loss) / 2
753
+
754
+ if not return_dict:
755
+ output = (
756
+ start_logits,
757
+ end_logits,
758
+ *([contextualized_embeddings] if output_hidden_states else []),
759
+ *([attention_probs] if output_attentions else [])
760
+ )
761
+ return ((total_loss,) + output) if total_loss is not None else output
762
+
763
+ return QuestionAnsweringModelOutput(
764
+ loss=total_loss,
765
+ start_logits=start_logits,
766
+ end_logits=end_logits,
767
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
768
+ attentions=attention_probs if output_attentions else None
769
+ )
770
+
771
+
772
+ class LtgbertForMultipleChoice(LtgbertModel):
773
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
774
+ _keys_to_ignore_on_load_missing = ["head"]
775
+
776
+ def __init__(self, config, **kwargs):
777
+ super().__init__(config, add_mlm_layer=False, **kwargs)
778
+
779
+ self.num_labels = getattr(config, "num_labels", 2)
780
+ self.head = Classifier(config, self.num_labels)
781
+
782
+ def forward(
783
+ self,
784
+ input_ids: Optional[torch.Tensor] = None,
785
+ attention_mask: Optional[torch.Tensor] = None,
786
+ token_type_ids: Optional[torch.Tensor] = None,
787
+ position_ids: Optional[torch.Tensor] = None,
788
+ labels: Optional[torch.Tensor] = None,
789
+ output_attentions: Optional[bool] = None,
790
+ output_hidden_states: Optional[bool] = None,
791
+ return_dict: Optional[bool] = None,
792
+ **kwargs
793
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
794
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
795
+ num_choices = input_ids.shape[1]
796
+
797
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1))
798
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
799
+
800
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(flat_input_ids, flat_attention_mask)
801
+ logits = self.head(sequence_output)
802
+ reshaped_logits = logits.view(-1, num_choices)
803
+
804
+ loss = None
805
+ if labels is not None:
806
+ loss_fct = nn.CrossEntropyLoss()
807
+ loss = loss_fct(reshaped_logits, labels)
808
+
809
+ if not return_dict:
810
+ output = (
811
+ reshaped_logits,
812
+ *([contextualized_embeddings] if output_hidden_states else []),
813
+ *([attention_probs] if output_attentions else [])
814
+ )
815
+ return ((loss,) + output) if loss is not None else output
816
+
817
+ return MultipleChoiceModelOutput(
818
+ loss=loss,
819
+ logits=reshaped_logits,
820
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
821
+ attentions=attention_probs if output_attentions else None
822
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e1e5fbe6e83f2268d4f30334df9e64bbb4cc5a2e2986d60594e2c9f27cbf60a
3
+ size 130639876
spacial_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"bos_token": "␂", "eos_token": "␃", "unk_token": "␦", "sep_token": "␃", "pad_token": "␒", "cls_token": "␂", "mask_token": "β₯"}
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": "␂",
4
+ "eos_token": "␃",
5
+ "unk_token": "␦",
6
+ "sep_token": "␃",
7
+ "pad_token": "␒",
8
+ "cls_token": "␂",
9
+ "mask_token": "β₯"
10
+ }