Tamás Ficsor commited on
Commit
11cdb73
·
1 Parent(s): d64ea7b
Files changed (5) hide show
  1. config.json +36 -0
  2. config.py +68 -0
  3. gbst.py +405 -0
  4. modeling_charmen.py +410 -0
  5. pytorch_model.bin +3 -0
config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "CharmenElectraModel"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "auto_map": {
7
+ "AutoConfig": "config.CharmenElectraConfig",
8
+ "AutoModel": "modeling_charmen.CharmenElectraModel"
9
+ },
10
+ "classifier_dropout": null,
11
+ "downsampling_factor": 4,
12
+ "embedding_size": 768,
13
+ "hidden_act": "gelu",
14
+ "hidden_dropout_prob": 0.1,
15
+ "hidden_size": 512,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 2048,
18
+ "layer_norm_eps": 1e-12,
19
+ "max_block_size": 4,
20
+ "max_position_embeddings": 1024,
21
+ "model_type": "SzegedAI/charmen-electra",
22
+ "num_attention_heads": 8,
23
+ "num_hidden_layers": 12,
24
+ "position_embedding_type": "absolute",
25
+ "sampling": "fp32_gumbel",
26
+ "score_consensus_attn": true,
27
+ "summary_activation": "gelu",
28
+ "summary_last_dropout": 0.1,
29
+ "summary_type": "first",
30
+ "summary_use_proj": true,
31
+ "torch_dtype": "float32",
32
+ "transformers_version": "4.21.0",
33
+ "type_vocab_size": 2,
34
+ "upsample_output": true,
35
+ "vocab_size": 261
36
+ }
config.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+ from typing import List, Literal, Optional
3
+
4
+
5
+ _SAMPLING_TYPE = Literal['fp32_gumbel', 'fp16_gumbel', 'multinomial']
6
+
7
+
8
+ class CharmenElectraConfig(PretrainedConfig):
9
+ model_type = "SzegedAI/charmen-electra"
10
+ _name_or_path = "SzegedAI/charmen-electra"
11
+
12
+ def __init__(
13
+ self,
14
+ downsampling_factor: int = 4,
15
+ max_block_size: int = 4,
16
+ score_consensus_attn: bool = True,
17
+ upsample_output: bool = True,
18
+ sampling: _SAMPLING_TYPE = 'fp32_gumbel',
19
+ attention_probs_dropout_prob: float = 0.1,
20
+ embedding_size: int = 768,
21
+ hidden_act: str = "gelu",
22
+ hidden_dropout_prob: float = 0.1,
23
+ hidden_size: int = 512,
24
+ initializer_range: float = 0.02,
25
+ intermediate_size: int = 2048,
26
+ layer_norm_eps: float = 1e-12,
27
+ max_position_embeddings: int = 1024,
28
+ model_type: str = "electra",
29
+ num_attention_heads: int = 8,
30
+ num_hidden_layers: int = 12,
31
+ pad_token_id: int = 0,
32
+ position_embedding_type: str = "absolute",
33
+ summary_activation: str = "gelu",
34
+ summary_last_dropout: float = 0.1,
35
+ summary_type: str = "first",
36
+ summary_use_proj: bool = True,
37
+ type_vocab_size: int = 2,
38
+ vocab_size: int = 261,
39
+ classifier_dropout: Optional[float] = None,
40
+ **kwargs,
41
+ ):
42
+ self.downsampling_factor = downsampling_factor
43
+ self.max_block_size = max_block_size
44
+ self.score_consensus_attn = score_consensus_attn
45
+ self.upsample_output = upsample_output
46
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
47
+ self.embedding_size = embedding_size
48
+ self.hidden_act = hidden_act
49
+ self.hidden_dropout_prob = hidden_dropout_prob
50
+ self.hidden_size = hidden_size
51
+ self.initializer_range = initializer_range
52
+ self.intermediate_size = intermediate_size
53
+ self.layer_norm_eps = layer_norm_eps
54
+ self.max_position_embeddings = max_position_embeddings
55
+ self.model_type = model_type
56
+ self.num_attention_heads = num_attention_heads
57
+ self.num_hidden_layers = num_hidden_layers
58
+ self.pad_token_id = pad_token_id
59
+ self.position_embedding_type = position_embedding_type
60
+ self.summary_activation = summary_activation
61
+ self.summary_last_dropout = summary_last_dropout
62
+ self.summary_type = summary_type
63
+ self.summary_use_proj = summary_use_proj
64
+ self.type_vocab_size = type_vocab_size
65
+ self.vocab_size = vocab_size
66
+ self.sampling = sampling
67
+ self.classifier_dropout = classifier_dropout
68
+ super().__init__(**kwargs)
gbst.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from math import gcd
3
+ import functools
4
+ import torch
5
+ import torch.nn.functional as F
6
+ from torch import nn, einsum
7
+
8
+ from einops import rearrange, reduce, repeat
9
+ from einops.layers.torch import Rearrange
10
+ from transformers.modeling_utils import PreTrainedModel
11
+
12
+
13
+ def exists(val):
14
+ return val is not None
15
+
16
+
17
+ def lcm(*numbers):
18
+ return int(functools.reduce(lambda x, y: int((x * y) / gcd(x, y)), numbers, 1))
19
+
20
+
21
+ def masked_mean(tensor, mask, dim = -1):
22
+ diff_len = len(tensor.shape) - len(mask.shape)
23
+ mask = mask[(..., *((None,) * diff_len))]
24
+ tensor.masked_fill_(~mask, 0.)
25
+
26
+ total_el = mask.sum(dim = dim)
27
+ mean = tensor.sum(dim = dim) / total_el.clamp(min = 1.)
28
+ mean.masked_fill_(total_el == 0, 0.)
29
+ return mean
30
+
31
+
32
+ def next_divisible_length(seqlen, multiple):
33
+ return math.ceil(seqlen / multiple) * multiple
34
+
35
+
36
+ def pad_to_multiple(tensor, multiple, *, seq_dim, dim = -1, value = 0.):
37
+ seqlen = tensor.shape[seq_dim]
38
+ length = next_divisible_length(seqlen, multiple)
39
+ if length == seqlen:
40
+ return tensor
41
+ remainder = length - seqlen
42
+ pad_offset = (0,) * (-1 - dim) * 2
43
+ return F.pad(tensor, (*pad_offset, 0, remainder), value = value)
44
+
45
+
46
+ # helper classes
47
+ class Pad(nn.Module):
48
+ def __init__(self, padding, value = 0.):
49
+ super().__init__()
50
+ self.padding = padding
51
+ self.value = value
52
+
53
+ def forward(self, x):
54
+ return F.pad(x, self.padding, value = self.value)
55
+
56
+
57
+ class DepthwiseConv1d(nn.Module):
58
+ def __init__(self, dim_in, dim_out, kernel_size):
59
+ super().__init__()
60
+ self.conv = nn.Conv1d(dim_in, dim_out, kernel_size, groups = dim_in)
61
+ self.proj_out = nn.Conv1d(dim_out, dim_out, 1)
62
+
63
+ def forward(self, x):
64
+ x = self.conv(x)
65
+ return self.proj_out(x)
66
+
67
+
68
+ # main class
69
+ class GBST(PreTrainedModel):
70
+ def _init_weights(self, module):
71
+ """Initialize the weights"""
72
+ if isinstance(module, nn.Linear):
73
+ # Slightly different from the TF version which uses truncated_normal for initialization
74
+ # cf https://github.com/pytorch/pytorch/pull/5617
75
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
76
+ if module.bias is not None:
77
+ module.bias.data.zero_()
78
+ elif isinstance(module, nn.Embedding):
79
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
80
+ if module.padding_idx is not None:
81
+ module.weight.data[module.padding_idx].zero_()
82
+ elif isinstance(module, nn.LayerNorm):
83
+ module.bias.data.zero_()
84
+ module.weight.data.fill_(1.0)
85
+
86
+ def __init__(
87
+ self,
88
+ *,
89
+ num_tokens,
90
+ dim,
91
+ max_block_size = None,
92
+ blocks = None,
93
+ downsample_factor = 4,
94
+ score_consensus_attn = True,
95
+ return_without_downsample = True,
96
+ config = None
97
+ ):
98
+ super(GBST, self).__init__(config=config)
99
+ assert exists(max_block_size) ^ exists(blocks), 'either max_block_size or blocks are given on initialization'
100
+ self.word_embeddings = nn.Embedding(num_tokens, dim)
101
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, dim)
102
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, dim)
103
+
104
+ self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
105
+
106
+ self.return_without_downsample = return_without_downsample
107
+
108
+ if exists(blocks):
109
+ assert isinstance(blocks, tuple), 'blocks must be a tuple of block sizes'
110
+ self.blocks = tuple(map(lambda el: el if isinstance(el, tuple) else (el, 0), blocks))
111
+ assert all([(offset < block_size) for block_size, offset in self.blocks]), 'offset must be always smaller than the block size'
112
+
113
+ max_block_size = max(list(map(lambda t: t[0], self.blocks)))
114
+ else:
115
+ self.blocks = tuple(map(lambda el: (el, 0), range(1, max_block_size + 1)))
116
+
117
+ self.pos_conv = nn.Sequential(
118
+ Pad((0, 0, 0, max_block_size - 1)),
119
+ Rearrange('b n d -> b d n'),
120
+ DepthwiseConv1d(dim, dim, kernel_size = max_block_size),
121
+ Rearrange('b d n -> b n d')
122
+ )
123
+
124
+ self.score_fn = nn.Sequential(
125
+ nn.Linear(dim, 1),
126
+ Rearrange('... () -> ...')
127
+ )
128
+
129
+ self.score_consensus_attn = score_consensus_attn
130
+
131
+ assert downsample_factor <= max_block_size, 'final downsample factor should be less than the maximum block size'
132
+
133
+ self.block_pad_multiple = lcm(*[block_size for block_size, _ in self.blocks])
134
+ self.downsample_factor = downsample_factor
135
+
136
+ def forward(self, input_ids, attention_mask=None, position_ids=None, token_type_ids=None, inputs_embeds=None):
137
+ b, n, block_mult, ds_factor, device = *input_ids.shape, self.block_pad_multiple, self.downsample_factor, input_ids.device
138
+ m = next_divisible_length(n, ds_factor)
139
+
140
+ # get character token embeddings
141
+
142
+ input_ids = self.word_embeddings(input_ids)
143
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
144
+
145
+ seq_len = input_ids.size()[1]
146
+ position_ids = self.position_ids[:, :seq_len]
147
+ position_embeddings = self.position_embeddings(position_ids)
148
+
149
+ input_ids = input_ids + token_type_embeddings + position_embeddings
150
+ # do a conv to generate the positions for the tokens
151
+
152
+ input_ids = self.pos_conv(input_ids)
153
+
154
+ # pad both sequence and attention_mask to length visibile by all block sizes from 0 to max block size
155
+
156
+ input_ids = pad_to_multiple(input_ids, block_mult, seq_dim=1, dim=-2)
157
+
158
+ if exists(attention_mask):
159
+ attention_mask = pad_to_multiple(attention_mask, block_mult, seq_dim=1, dim=-1, value=False)
160
+
161
+ # compute representations for all blocks by mean pooling
162
+
163
+ block_masks = []
164
+ block_reprs = []
165
+
166
+ for block_size, offset in self.blocks:
167
+ # clone the input sequence as well as the attention_mask, in order to pad for offsets
168
+
169
+ block_x = input_ids.clone()
170
+
171
+ if exists(attention_mask):
172
+ block_mask = attention_mask.clone()
173
+
174
+ # pad for offsets, if needed
175
+
176
+ need_padding = offset > 0
177
+
178
+ if need_padding:
179
+ left_offset, right_offset = (block_size - offset), offset
180
+ block_x = F.pad(block_x, (0, 0, left_offset, right_offset), value = 0.)
181
+
182
+ if exists(attention_mask):
183
+ block_mask = F.pad(block_mask, (left_offset, right_offset), value = False)
184
+
185
+ # group input sequence into blocks
186
+
187
+ blocks = rearrange(block_x, 'b (n m) d -> b n m d', m = block_size)
188
+
189
+ # either mean pool the blocks, or do a masked mean
190
+
191
+ if exists(attention_mask):
192
+ mask_blocks = rearrange(block_mask, 'b (n m) -> b n m', m = block_size)
193
+ block_repr = masked_mean(blocks, mask_blocks, dim = -2)
194
+ else:
195
+ block_repr = blocks.mean(dim = -2)
196
+
197
+ # append the block representations, as well as the pooled block masks
198
+
199
+ block_repr = repeat(block_repr, 'b n d -> b (n m) d', m = block_size)
200
+
201
+ if need_padding:
202
+ block_repr = block_repr[:, left_offset:-right_offset]
203
+
204
+ block_reprs.append(block_repr)
205
+
206
+ if exists(attention_mask):
207
+ mask_blocks = torch.any(mask_blocks, dim = -1)
208
+ mask_blocks = repeat(mask_blocks, 'b n -> b (n m)', m = block_size)
209
+
210
+ if need_padding:
211
+ mask_blocks = mask_blocks[:, left_offset:-right_offset]
212
+
213
+ block_masks.append(mask_blocks)
214
+
215
+ # stack all the block representations
216
+
217
+ block_reprs = torch.stack(block_reprs, dim = 2)
218
+
219
+ # calculate scores and softmax across the block size dimension
220
+
221
+ scores = self.score_fn(block_reprs)
222
+
223
+ if exists(attention_mask):
224
+ block_masks = torch.stack(block_masks, dim = 2)
225
+ max_neg_value = -torch.finfo(scores.dtype).max
226
+ scores = scores.masked_fill(~block_masks, max_neg_value)
227
+
228
+ scores = scores.softmax(dim = 2)
229
+
230
+ # do the cheap consensus attention, eq (5) in paper
231
+
232
+ if self.score_consensus_attn:
233
+ score_sim = einsum('b i d, b j d -> b i j', scores, scores)
234
+
235
+ if exists(attention_mask):
236
+ cross_mask = rearrange(attention_mask, 'b i -> b i ()') * rearrange(attention_mask, 'b j -> b () j')
237
+ max_neg_value = -torch.finfo(score_sim.dtype).max
238
+ score_sim = score_sim.masked_fill(~cross_mask, max_neg_value)
239
+
240
+ score_attn = score_sim.softmax(dim=-1)
241
+ scores = einsum('b i j, b j m -> b i m', score_attn, scores)
242
+
243
+ # multiply the block representations by the position-wise scores
244
+
245
+ scores = rearrange(scores, 'b n m -> b n m ()')
246
+ input_ids = (block_reprs * scores).sum(dim=2)
247
+
248
+ # truncate to length divisible by downsample factor
249
+
250
+ input_ids = input_ids[:, :m]
251
+
252
+ original = None
253
+ if self.return_without_downsample:
254
+ original = torch.clone(input_ids)
255
+
256
+ input_ids, attention_mask = self.down_sample(input_ids, attention_mask, ds_factor)
257
+
258
+ return input_ids, attention_mask, original
259
+
260
+ @staticmethod
261
+ def down_sample(input_ids, attention_mask, ds_factor):
262
+ n = input_ids.shape[1]
263
+ m = next_divisible_length(n, ds_factor)
264
+ if exists(attention_mask):
265
+ attention_mask = attention_mask[:, :m]
266
+
267
+ # final mean pooling downsample
268
+ input_ids = rearrange(input_ids, 'b (n m) d -> b n m d', m=ds_factor)
269
+
270
+ if exists(attention_mask):
271
+ attention_mask = rearrange(attention_mask, 'b (n m) -> b n m', m=ds_factor)
272
+ input_ids = masked_mean(input_ids, attention_mask, dim=2)
273
+ attention_mask = torch.any(attention_mask, dim=-1)
274
+ else:
275
+ input_ids = input_ids.mean(dim=-2)
276
+ return input_ids, attention_mask
277
+
278
+ def block_score(self, input_ids, attention_mask=None, position_ids=None, token_type_ids=None, inputs_embeds=None):
279
+ b, n, block_mult, ds_factor, device = *input_ids.shape, self.block_pad_multiple, self.downsample_factor, input_ids.device
280
+ m = next_divisible_length(n, ds_factor)
281
+
282
+ # get character token embeddings
283
+
284
+ input_ids = self.word_embeddings(input_ids)
285
+
286
+ # do a conv to generate the positions for the tokens
287
+
288
+ input_ids = self.pos_conv(input_ids)
289
+
290
+ # pad both sequence and attention_mask to length visibile by all block sizes from 0 to max block size
291
+
292
+ input_ids = pad_to_multiple(input_ids, block_mult, seq_dim=1, dim=-2)
293
+
294
+ if exists(attention_mask):
295
+ attention_mask = pad_to_multiple(attention_mask, block_mult, seq_dim=1, dim=-1, value=False)
296
+
297
+ # compute representations for all blocks by mean pooling
298
+
299
+ block_masks = []
300
+ block_reprs = []
301
+
302
+ for block_size, offset in self.blocks:
303
+ # clone the input sequence as well as the attention_mask, in order to pad for offsets
304
+
305
+ block_x = input_ids.clone()
306
+
307
+ if exists(attention_mask):
308
+ block_mask = attention_mask.clone()
309
+
310
+ # pad for offsets, if needed
311
+
312
+ need_padding = offset > 0
313
+
314
+ if need_padding:
315
+ left_offset, right_offset = (block_size - offset), offset
316
+ block_x = F.pad(block_x, (0, 0, left_offset, right_offset), value = 0.)
317
+
318
+ if exists(attention_mask):
319
+ block_mask = F.pad(block_mask, (left_offset, right_offset), value = False)
320
+
321
+ # group input sequence into blocks
322
+
323
+ blocks = rearrange(block_x, 'b (n m) d -> b n m d', m = block_size)
324
+
325
+ # either mean pool the blocks, or do a masked mean
326
+
327
+ if exists(attention_mask):
328
+ mask_blocks = rearrange(block_mask, 'b (n m) -> b n m', m = block_size)
329
+ block_repr = masked_mean(blocks, mask_blocks, dim = -2)
330
+ else:
331
+ block_repr = blocks.mean(dim = -2)
332
+
333
+ # append the block representations, as well as the pooled block masks
334
+
335
+ block_repr = repeat(block_repr, 'b n d -> b (n m) d', m = block_size)
336
+
337
+ if need_padding:
338
+ block_repr = block_repr[:, left_offset:-right_offset]
339
+
340
+ block_reprs.append(block_repr)
341
+
342
+ if exists(attention_mask):
343
+ mask_blocks = torch.any(mask_blocks, dim = -1)
344
+ mask_blocks = repeat(mask_blocks, 'b n -> b (n m)', m = block_size)
345
+
346
+ if need_padding:
347
+ mask_blocks = mask_blocks[:, left_offset:-right_offset]
348
+
349
+ block_masks.append(mask_blocks)
350
+
351
+ # stack all the block representations
352
+
353
+ block_reprs = torch.stack(block_reprs, dim = 2)
354
+
355
+ # calculate scores and softmax across the block size dimension
356
+
357
+ scores = self.score_fn(block_reprs)
358
+
359
+ if exists(attention_mask):
360
+ block_masks = torch.stack(block_masks, dim = 2)
361
+ max_neg_value = -torch.finfo(scores.dtype).max
362
+ scores = scores.masked_fill(~block_masks, max_neg_value)
363
+
364
+ scores = scores.softmax(dim = 2)
365
+
366
+ # do the cheap consensus attention, eq (5) in paper
367
+
368
+ if self.score_consensus_attn:
369
+ score_sim = einsum('b i d, b j d -> b i j', scores, scores)
370
+
371
+ if exists(attention_mask):
372
+ cross_mask = rearrange(attention_mask, 'b i -> b i ()') * rearrange(attention_mask, 'b j -> b () j')
373
+ max_neg_value = -torch.finfo(score_sim.dtype).max
374
+ score_sim = score_sim.masked_fill(~cross_mask, max_neg_value)
375
+
376
+ score_attn = score_sim.softmax(dim=-1)
377
+ scores = einsum('b i j, b j m -> b i m', score_attn, scores)
378
+
379
+ # multiply the block representations by the position-wise scores
380
+
381
+ scores = rearrange(scores, 'b n m -> b n m ()')
382
+ input_ids = (block_reprs * scores).sum(dim=2)
383
+
384
+ # truncate to length divisible by downsample factor
385
+
386
+ input_ids = input_ids[:, :m]
387
+
388
+ if exists(attention_mask):
389
+ attention_mask = attention_mask[:, :m]
390
+
391
+ original = None
392
+ if self.return_without_downsample:
393
+ original = torch.clone(input_ids)
394
+
395
+ # final mean pooling downsample
396
+ input_ids = rearrange(input_ids, 'b (n m) d -> b n m d', m=ds_factor)
397
+
398
+ if exists(attention_mask):
399
+ attention_mask = rearrange(attention_mask, 'b (n m) -> b n m', m=ds_factor)
400
+ input_ids = masked_mean(input_ids, attention_mask, dim=2)
401
+ attention_mask = torch.any(attention_mask, dim=-1)
402
+ else:
403
+ input_ids = input_ids.mean(dim=-2)
404
+
405
+ return scores
modeling_charmen.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.models.electra.modeling_electra import ElectraPreTrainedModel, ElectraEncoder, ElectraLayer, \
2
+ ModelOutput, ElectraForSequenceClassification, SequenceClassifierOutput, ElectraForTokenClassification, \
3
+ ElectraForMultipleChoice
4
+ from .config import CharmenElectraConfig
5
+ from .gbst import GBST
6
+ import torch.nn as nn
7
+ import copy
8
+ import torch
9
+ from torch import Tensor
10
+ from dataclasses import dataclass
11
+ from typing import Optional, Tuple
12
+ from typing import OrderedDict as OrderDictType
13
+ from collections import OrderedDict
14
+ from transformers.activations import get_activation
15
+
16
+
17
+ @dataclass
18
+ class CharmenElectraModelOutput(ModelOutput):
19
+ """
20
+ Output type of :class:`~.CharmenElectraModel`.
21
+ """
22
+ downsampled_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
23
+ upsampled_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
24
+
25
+
26
+ class CharmenElectraModel(ElectraPreTrainedModel):
27
+ config_class = CharmenElectraConfig
28
+
29
+ def __init__(self, config: CharmenElectraConfig, compatibility_with_transformers=False):
30
+ super().__init__(config)
31
+ self.embeddings: GBST = GBST(
32
+ num_tokens=config.vocab_size,
33
+ # number of tokens, should be 256 for byte encoding (+ 1 special token for padding in this example)
34
+ dim=config.embedding_size, # dimension of token and intra-block positional embedding
35
+ max_block_size=config.max_block_size, # maximum block size
36
+ downsample_factor=config.downsampling_factor,
37
+ # the final downsample factor by which the sequence length will decrease by
38
+ score_consensus_attn=config.score_consensus_attn,
39
+ config=config
40
+ # whether to do the cheap score consensus (aka attention) as in eq. 5 in the paper
41
+ )
42
+ self.compatibility_with_transformers = compatibility_with_transformers
43
+
44
+ if config.embedding_size != config.hidden_size:
45
+ self.embeddings_project = nn.Linear(config.embedding_size, config.hidden_size)
46
+
47
+ self.upsampling = nn.Upsample(scale_factor=config.downsampling_factor, mode='nearest')
48
+ self.upsampling_convolution = nn.Conv1d(in_channels=config.hidden_size * 2,
49
+ out_channels=config.hidden_size,
50
+ kernel_size=(config.downsampling_factor*2-1,),
51
+ padding='same',
52
+ dilation=(1,))
53
+ self.upsample_output = config.upsample_output
54
+
55
+ # config.num_hidden_layers = config.num_hidden_layers - 2
56
+
57
+ cfg = copy.deepcopy(config)
58
+ cfg.num_hidden_layers = config.num_hidden_layers - 2
59
+ self.encoder = ElectraEncoder(cfg)
60
+
61
+ # frame_hidden_size
62
+ self.encoder_first_layer = ElectraLayer(config)
63
+ self.encoder_last_layer = ElectraLayer(config)
64
+
65
+ self.config = config
66
+ self.init_weights()
67
+
68
+ def get_input_embeddings(self):
69
+ return self.embeddings.word_embeddings
70
+
71
+ def set_input_embeddings(self, value):
72
+ self.embeddings.word_embeddings = value
73
+
74
+ def _prune_heads(self, heads_to_prune):
75
+ """
76
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
77
+ class PreTrainedModel
78
+ """
79
+ for layer, heads in heads_to_prune.items():
80
+ self.encoder.layer[layer].attention.prune_heads(heads)
81
+
82
+ def forward(
83
+ self,
84
+ input_ids=None,
85
+ attention_mask=None,
86
+ token_type_ids=None,
87
+ position_ids=None,
88
+ head_mask=None,
89
+ inputs_embeds=None,
90
+ output_attentions=None,
91
+ output_hidden_states=None,
92
+ return_dict=None,
93
+ ):
94
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
95
+ output_hidden_states = (
96
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
97
+ )
98
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
99
+
100
+ if input_ids.shape.__len__() == 1:
101
+ input_ids = input_ids.view(1, -1)
102
+ attention_mask = attention_mask.view(1, -1)
103
+ token_type_ids = token_type_ids.view(1, -1)
104
+
105
+ if input_ids is not None and inputs_embeds is not None:
106
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
107
+ elif input_ids is not None:
108
+ input_shape = input_ids.size()
109
+ elif inputs_embeds is not None:
110
+ input_shape = inputs_embeds.size()[:-1]
111
+ else:
112
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
113
+
114
+ batch_size, seq_length = input_shape
115
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
116
+
117
+ if attention_mask is None:
118
+ attention_mask = torch.ones(input_shape, device=device)
119
+ if token_type_ids is None:
120
+ if hasattr(self.embeddings, "token_type_ids"):
121
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
122
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
123
+ token_type_ids = buffered_token_type_ids_expanded
124
+ else:
125
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
126
+
127
+ unscaled_attention_mask = torch.clone(attention_mask)
128
+
129
+ _, _, unscaled_hidden_states = self.embeddings(
130
+ input_ids=input_ids, attention_mask=attention_mask,
131
+ position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
132
+ )
133
+
134
+ if hasattr(self, "embeddings_project"):
135
+ unscaled_hidden_states = self.embeddings_project(unscaled_hidden_states)
136
+
137
+ extended_unscaled_attention_mask = self.get_extended_attention_mask(unscaled_attention_mask, input_shape,
138
+ device)
139
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
140
+
141
+ unscaled_hidden_states = self.encoder_first_layer(unscaled_hidden_states, extended_unscaled_attention_mask,
142
+ None, None, None, None, False)[0]
143
+
144
+ hidden_states, attention_mask = self.embeddings.down_sample(unscaled_hidden_states, unscaled_attention_mask,
145
+ self.config.downsampling_factor)
146
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, device)
147
+
148
+ encoder_output = self.encoder(
149
+ hidden_states,
150
+ attention_mask=extended_attention_mask,
151
+ head_mask=head_mask,
152
+ output_attentions=output_attentions,
153
+ output_hidden_states=output_hidden_states,
154
+ return_dict=return_dict,
155
+ )
156
+
157
+ downsampled_hidden_states = encoder_output[0]
158
+ hidden_states = encoder_output[0]
159
+
160
+ # upsampling
161
+ upsampled = self.upsampling(hidden_states.permute(0, 2, 1)).permute(0, 2, 1)
162
+ hidden_states = torch.cat([unscaled_hidden_states, upsampled], dim=-1)
163
+ # padded_hidden_states = F.pad(hidden_states.permute(0, 2, 1), (3, 3))
164
+ hidden_states = self.upsampling_convolution(hidden_states.permute(0, 2, 1)).permute(0, 2, 1)
165
+
166
+ hidden_states = self.encoder_last_layer(hidden_states, extended_unscaled_attention_mask,
167
+ None, None, None, None, False)
168
+
169
+ upsampled_output = hidden_states[0]
170
+
171
+ return CharmenElectraModelOutput(
172
+ downsampled_hidden_states=downsampled_hidden_states,
173
+ upsampled_hidden_states=upsampled_output
174
+ )
175
+
176
+ def load_state_dict(self, state_dict: OrderDictType[str, Tensor], strict: bool = True):
177
+ model = OrderedDict()
178
+ prefix = "discriminator.electra."
179
+
180
+ for key, value in state_dict.items():
181
+ if key.startswith(prefix):
182
+ model[key[len(prefix):]] = value
183
+
184
+ super(CharmenElectraModel, self).load_state_dict(model, strict)
185
+
186
+
187
+ class CharmenElectraClassificationHead(nn.Module):
188
+ """Head for sentence-level classification tasks."""
189
+
190
+ def __init__(self, config: CharmenElectraConfig):
191
+ super().__init__()
192
+ self.config = config
193
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
194
+ classifier_dropout = (
195
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
196
+ )
197
+ self.dropout = nn.Dropout(classifier_dropout)
198
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
199
+ self.ds_factor = config.downsampling_factor
200
+
201
+ def forward(self, features, **kwargs):
202
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
203
+ x = self.dropout(x)
204
+ x = self.dense(x)
205
+ x = get_activation(self.config.summary_activation)(x)
206
+ x = self.dropout(x)
207
+ x = self.out_proj(x)
208
+ return x
209
+
210
+
211
+ class CharmenElectraForSequenceClassification(ElectraForSequenceClassification):
212
+ config_class = CharmenElectraConfig
213
+
214
+ def __init__(self, config: CharmenElectraConfig, class_weight=None, label_smoothing=0.0):
215
+ super().__init__(config)
216
+
217
+ self.num_labels = config.num_labels
218
+ self.config = config
219
+ self.model = CharmenElectraModel(config, compatibility_with_transformers=True)
220
+ self.classifier = CharmenElectraClassificationHead(config)
221
+ self.cls_loss_fct = torch.nn.CrossEntropyLoss(weight=class_weight, label_smoothing=label_smoothing)
222
+
223
+ self.init_weights()
224
+
225
+ def forward(
226
+ self,
227
+ input_ids=None,
228
+ attention_mask=None,
229
+ token_type_ids=None,
230
+ position_ids=None,
231
+ head_mask=None,
232
+ inputs_embeds=None,
233
+ labels=None,
234
+ output_attentions=None,
235
+ output_hidden_states=None,
236
+ return_dict=None,
237
+ ):
238
+ output_discriminator: CharmenElectraModelOutput = self.model(input_ids, attention_mask, token_type_ids)
239
+
240
+ if self.carmen_config.upsample_output:
241
+ cls = self.classifier(output_discriminator.upsampled_hidden_states)
242
+ else:
243
+ cls = self.classifier(output_discriminator.downsampled_hidden_states)
244
+ cls_loss = self.cls_loss_fct(cls, labels)
245
+
246
+ return SequenceClassifierOutput(
247
+ loss=cls_loss,
248
+ logits=cls,
249
+ hidden_states=output_discriminator.downsampled_hidden_states,
250
+ attentions=None,
251
+ )
252
+
253
+ def load_state_dict(self, state_dict: OrderDictType[str, Tensor], strict: bool = True):
254
+ model = OrderedDict()
255
+ prefix = "discriminator.electra."
256
+
257
+ for key, value in state_dict.items():
258
+ if key.startswith(prefix):
259
+ model[key[len(prefix):]] = value
260
+
261
+ self.model.load_state_dict(state_dict=model, strict=strict)
262
+
263
+
264
+ class CharmenElectraForTokenClassification(ElectraForTokenClassification):
265
+ def __init__(self, config: CharmenElectraConfig, class_weight=None, label_smoothing=0.0):
266
+ super().__init__(config)
267
+
268
+ self.num_labels = config.num_labels
269
+ self.config = config
270
+
271
+ self.carmen_config = config
272
+ self.model = CharmenElectraModel(config, compatibility_with_transformers=True)
273
+
274
+ classifier_dropout = (
275
+ config.discriminator.classifier_dropout if config.discriminator.classifier_dropout is not None else config.discriminator.hidden_dropout_prob
276
+ )
277
+ self.dropout = nn.Dropout(classifier_dropout)
278
+ self.classifier = nn.Linear(config.discriminator.hidden_size, config.num_labels)
279
+
280
+ self.cls_loss_fct = torch.nn.CrossEntropyLoss(weight=class_weight, label_smoothing=label_smoothing)
281
+
282
+ self.init_weights()
283
+
284
+ def forward(
285
+ self,
286
+ input_ids=None,
287
+ attention_mask=None,
288
+ token_type_ids=None,
289
+ position_ids=None,
290
+ head_mask=None,
291
+ inputs_embeds=None,
292
+ labels=None,
293
+ output_attentions=None,
294
+ output_hidden_states=None,
295
+ return_dict=None,
296
+ ):
297
+ output_discriminator: CharmenElectraModelOutput = self.model(
298
+ input_ids, attention_mask, token_type_ids)
299
+
300
+ discriminator_sequence_output = self.dropout(output_discriminator.upsampled_hidden_states)
301
+ logits = self.classifier(discriminator_sequence_output)
302
+
303
+ if labels is not None:
304
+ cls_loss = self.cls_loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
305
+ else:
306
+ cls_loss = None
307
+
308
+ return SequenceClassifierOutput(
309
+ loss=cls_loss,
310
+ logits=logits,
311
+ hidden_states=output_discriminator.upsampled_hidden_states,
312
+ attentions=None,
313
+ )
314
+
315
+ def get_input_embeddings(self) -> nn.Module:
316
+ return self.electra.get_input_embeddings()
317
+
318
+ def load_state_dict(self, state_dict: OrderDictType[str, Tensor], strict: bool = True):
319
+ model = OrderedDict()
320
+ prefix = "discriminator.electra."
321
+
322
+ for key, value in state_dict.items():
323
+ if key.startswith(prefix):
324
+ model[key[len(prefix):]] = value
325
+
326
+ self.model.load_state_dict(state_dict=model, strict=strict)
327
+
328
+
329
+ class Pooler(nn.Module):
330
+ def __init__(self, config):
331
+ super().__init__()
332
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
333
+ self.activation = nn.Tanh()
334
+
335
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
336
+ # We "pool" the model by simply taking the hidden state corresponding
337
+ # to the first token.
338
+ first_token_tensor = hidden_states[:, 0]
339
+ pooled_output = self.dense(first_token_tensor)
340
+ pooled_output = self.activation(pooled_output)
341
+ return pooled_output
342
+
343
+
344
+ class CharmenElectraForMultipleChoice(ElectraForMultipleChoice):
345
+ def __init__(self, config: CharmenElectraConfig, class_weight=None, label_smoothing=0.0):
346
+ super().__init__(config)
347
+ self.num_labels = config.num_labels
348
+ self.config = config
349
+ self.carmen_config = config
350
+ self.model = CharmenElectraModel(config, compatibility_with_transformers=True)
351
+ self.pooler = Pooler(config)
352
+
353
+ classifier_dropout = (
354
+ config.classifier_dropout if config.discriminator.classifier_dropout is not None else config.hidden_dropout_prob
355
+ )
356
+ self.dropout = nn.Dropout(classifier_dropout)
357
+ self.classifier = nn.Linear(config.hidden_size, 1)
358
+
359
+ self.cls_loss_fct = torch.nn.CrossEntropyLoss(weight=class_weight, label_smoothing=label_smoothing)
360
+
361
+ self.init_weights()
362
+
363
+ def forward(
364
+ self,
365
+ input_ids=None,
366
+ attention_mask=None,
367
+ token_type_ids=None,
368
+ position_ids=None,
369
+ head_mask=None,
370
+ inputs_embeds=None,
371
+ labels=None,
372
+ output_attentions=None,
373
+ output_hidden_states=None,
374
+ return_dict=None,
375
+ ):
376
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
377
+
378
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
379
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
380
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
381
+
382
+ output_discriminator: CharmenElectraModelOutput = self.model(
383
+ input_ids, attention_mask, token_type_ids)
384
+
385
+ if self.carmen_config.upsample_output:
386
+ pooled_output = self.pooler(output_discriminator.upsampled_hidden_states)
387
+ else:
388
+ pooled_output = self.pooler(output_discriminator.downsampled_hidden_states)
389
+ pooled_output = self.dropout(pooled_output)
390
+ logits = self.classifier(pooled_output)
391
+ reshaped_logits = logits.view(-1, num_choices)
392
+
393
+ cls_loss = self.cls_loss_fct(reshaped_logits, labels)
394
+
395
+ return SequenceClassifierOutput(
396
+ loss=cls_loss,
397
+ logits=reshaped_logits,
398
+ hidden_states=output_discriminator.downsampled_hidden_states,
399
+ attentions=None,
400
+ )
401
+
402
+ def load_state_dict(self, state_dict: OrderDictType[str, Tensor], strict: bool = True):
403
+ model = OrderedDict()
404
+ prefix = "discriminator.electra."
405
+
406
+ for key, value in state_dict.items():
407
+ if key.startswith(prefix):
408
+ model[key[len(prefix):]] = value
409
+
410
+ self.model.load_state_dict(state_dict=model, strict=strict)
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7074667cdc918bf66a2b408b6e879995964891452d4dd598f0b42fbbdc0ee60b
3
+ size 173978597