Omar commited on
Commit
efff561
1 Parent(s): 3ca263d

upload results

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. finetune/boolq/all_results.json +16 -0
  2. finetune/boolq/checkpoint-200/config.json +41 -0
  3. finetune/boolq/checkpoint-200/merges.txt +0 -0
  4. finetune/boolq/checkpoint-200/optimizer.pt +3 -0
  5. finetune/boolq/checkpoint-200/pytorch_model.bin +3 -0
  6. finetune/boolq/checkpoint-200/rng_state.pth +3 -0
  7. finetune/boolq/checkpoint-200/scheduler.pt +3 -0
  8. finetune/boolq/checkpoint-200/special_tokens_map.json +15 -0
  9. finetune/boolq/checkpoint-200/structformer.py +867 -0
  10. finetune/boolq/checkpoint-200/tokenizer_config.json +65 -0
  11. finetune/boolq/checkpoint-200/trainer_state.json +27 -0
  12. finetune/boolq/checkpoint-200/training_args.bin +3 -0
  13. finetune/boolq/checkpoint-200/vocab.json +0 -0
  14. finetune/boolq/config.json +41 -0
  15. finetune/boolq/eval_results.json +11 -0
  16. finetune/boolq/merges.txt +0 -0
  17. finetune/boolq/predict_results.txt +724 -0
  18. finetune/boolq/pytorch_model.bin +3 -0
  19. finetune/boolq/special_tokens_map.json +15 -0
  20. finetune/boolq/structformer.py +867 -0
  21. finetune/boolq/tokenizer_config.json +65 -0
  22. finetune/boolq/train_results.json +8 -0
  23. finetune/boolq/trainer_state.json +36 -0
  24. finetune/boolq/training_args.bin +3 -0
  25. finetune/boolq/vocab.json +0 -0
  26. finetune/cola/all_results.json +16 -0
  27. finetune/cola/checkpoint-200/config.json +41 -0
  28. finetune/cola/checkpoint-200/merges.txt +0 -0
  29. finetune/cola/checkpoint-200/optimizer.pt +3 -0
  30. finetune/cola/checkpoint-200/pytorch_model.bin +3 -0
  31. finetune/cola/checkpoint-200/rng_state.pth +3 -0
  32. finetune/cola/checkpoint-200/scheduler.pt +3 -0
  33. finetune/cola/checkpoint-200/special_tokens_map.json +15 -0
  34. finetune/cola/checkpoint-200/structformer.py +867 -0
  35. finetune/cola/checkpoint-200/tokenizer_config.json +65 -0
  36. finetune/cola/checkpoint-200/trainer_state.json +27 -0
  37. finetune/cola/checkpoint-200/training_args.bin +3 -0
  38. finetune/cola/checkpoint-200/vocab.json +0 -0
  39. finetune/cola/config.json +41 -0
  40. finetune/cola/eval_results.json +11 -0
  41. finetune/cola/merges.txt +0 -0
  42. finetune/cola/predict_results.txt +1020 -0
  43. finetune/cola/pytorch_model.bin +3 -0
  44. finetune/cola/special_tokens_map.json +15 -0
  45. finetune/cola/structformer.py +867 -0
  46. finetune/cola/tokenizer_config.json +65 -0
  47. finetune/cola/train_results.json +8 -0
  48. finetune/cola/trainer_state.json +103 -0
  49. finetune/cola/training_args.bin +3 -0
  50. finetune/cola/vocab.json +0 -0
finetune/boolq/all_results.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 10.0,
3
+ "eval_accuracy": 0.658367931842804,
4
+ "eval_f1": 0.7282728272827282,
5
+ "eval_loss": 0.9740044474601746,
6
+ "eval_mcc": 0.27328046278245693,
7
+ "eval_runtime": 1.2249,
8
+ "eval_samples": 723,
9
+ "eval_samples_per_second": 590.256,
10
+ "eval_steps_per_second": 74.292,
11
+ "train_loss": 0.3263397216796875,
12
+ "train_runtime": 70.9595,
13
+ "train_samples": 2072,
14
+ "train_samples_per_second": 291.998,
15
+ "train_steps_per_second": 4.651
16
+ }
finetune/boolq/checkpoint-200/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "omarmomen/sf_babylm_1",
3
+ "architectures": [
4
+ "StructFormerModelForSequenceClassification"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "structformer.StructFormerConfig",
8
+ "AutoModelForMaskedLM": "structformer.StructFormerModel",
9
+ "AutoModelForSequenceClassification": "structformer.StructFormerModelForSequenceClassification"
10
+ },
11
+ "conv_size": 9,
12
+ "dropatt": 0.1,
13
+ "dropout": 0.1,
14
+ "hidden_dropout_prob": 0.1,
15
+ "hidden_size": 512,
16
+ "id2label": {
17
+ "0": 0,
18
+ "1": 1
19
+ },
20
+ "initializer_range": 0.02,
21
+ "label2id": {
22
+ "0": 0,
23
+ "1": 1
24
+ },
25
+ "model_type": "structformer",
26
+ "n_parser_layers": 3,
27
+ "nhead": 8,
28
+ "nlayers": 8,
29
+ "ntokens": 16000,
30
+ "pad": 1,
31
+ "pos_emb": true,
32
+ "problem_type": "single_label_classification",
33
+ "relations": [
34
+ "head",
35
+ "child"
36
+ ],
37
+ "relative_bias": false,
38
+ "torch_dtype": "float32",
39
+ "transformers_version": "4.26.1",
40
+ "weight_act": "softmax"
41
+ }
finetune/boolq/checkpoint-200/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
finetune/boolq/checkpoint-200/optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2c3f651c5c9f9981bb14d59d7cb9fa2f4fd0096fc5c4dad0fb5f270c5d9d0205
3
+ size 334487930
finetune/boolq/checkpoint-200/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e4f79d98ac75f5de6364c0f52da1493dc993efa95b33032b8444be736b945bf5
3
+ size 167313902
finetune/boolq/checkpoint-200/rng_state.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50aec6bc0ddef9c74c961b5729c90a128fd273f00030cf8bb80ad486887cc174
3
+ size 14244
finetune/boolq/checkpoint-200/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0b2de95c5fb4e38745233f92e6332f510dfd17896063583c072cd541a34cccb0
3
+ size 1064
finetune/boolq/checkpoint-200/special_tokens_map.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<s>",
3
+ "cls_token": "<s>",
4
+ "eos_token": "</s>",
5
+ "mask_token": {
6
+ "content": "<mask>",
7
+ "lstrip": true,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "pad_token": "<pad>",
13
+ "sep_token": "</s>",
14
+ "unk_token": "<unk>"
15
+ }
finetune/boolq/checkpoint-200/structformer.py ADDED
@@ -0,0 +1,867 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Google Research Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """StructFormer and transformer model."""
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from torch.nn import init
22
+ from transformers import PretrainedConfig, PreTrainedModel
23
+ from transformers.modeling_outputs import MaskedLMOutput, SequenceClassifierOutput
24
+
25
+ def _get_activation_fn(activation):
26
+ """Get specified activation function."""
27
+ if activation == "relu":
28
+ return nn.ReLU()
29
+ elif activation == "gelu":
30
+ return nn.GELU()
31
+ elif activation == "leakyrelu":
32
+ return nn.LeakyReLU()
33
+
34
+ raise RuntimeError(
35
+ "activation should be relu/gelu, not {}".format(activation))
36
+
37
+
38
+ class Conv1d(nn.Module):
39
+ """1D convolution layer."""
40
+
41
+ def __init__(self, hidden_size, kernel_size, dilation=1):
42
+ """Initialization.
43
+
44
+ Args:
45
+ hidden_size: dimension of input embeddings
46
+ kernel_size: convolution kernel size
47
+ dilation: the spacing between the kernel points
48
+ """
49
+ super(Conv1d, self).__init__()
50
+
51
+ if kernel_size % 2 == 0:
52
+ padding = (kernel_size // 2) * dilation
53
+ self.shift = True
54
+ else:
55
+ padding = ((kernel_size - 1) // 2) * dilation
56
+ self.shift = False
57
+ self.conv = nn.Conv1d(
58
+ hidden_size,
59
+ hidden_size,
60
+ kernel_size,
61
+ padding=padding,
62
+ dilation=dilation)
63
+
64
+ def forward(self, x):
65
+ """Compute convolution.
66
+
67
+ Args:
68
+ x: input embeddings
69
+ Returns:
70
+ conv_output: convolution results
71
+ """
72
+
73
+ if self.shift:
74
+ return self.conv(x.transpose(1, 2)).transpose(1, 2)[:, 1:]
75
+ else:
76
+ return self.conv(x.transpose(1, 2)).transpose(1, 2)
77
+
78
+
79
+ class MultiheadAttention(nn.Module):
80
+ """Multi-head self-attention layer."""
81
+
82
+ def __init__(self,
83
+ embed_dim,
84
+ num_heads,
85
+ dropout=0.,
86
+ bias=True,
87
+ v_proj=True,
88
+ out_proj=True,
89
+ relative_bias=True):
90
+ """Initialization.
91
+
92
+ Args:
93
+ embed_dim: dimension of input embeddings
94
+ num_heads: number of self-attention heads
95
+ dropout: dropout rate
96
+ bias: bool, indicate whether include bias for linear transformations
97
+ v_proj: bool, indicate whether project inputs to new values
98
+ out_proj: bool, indicate whether project outputs to new values
99
+ relative_bias: bool, indicate whether use a relative position based
100
+ attention bias
101
+ """
102
+
103
+ super(MultiheadAttention, self).__init__()
104
+ self.embed_dim = embed_dim
105
+
106
+ self.num_heads = num_heads
107
+ self.drop = nn.Dropout(dropout)
108
+ self.head_dim = embed_dim // num_heads
109
+ assert self.head_dim * num_heads == self.embed_dim, ("embed_dim must be "
110
+ "divisible by "
111
+ "num_heads")
112
+
113
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
114
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
115
+ if v_proj:
116
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
117
+ else:
118
+ self.v_proj = nn.Identity()
119
+
120
+ if out_proj:
121
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
122
+ else:
123
+ self.out_proj = nn.Identity()
124
+
125
+ if relative_bias:
126
+ self.relative_bias = nn.Parameter(torch.zeros((self.num_heads, 512)))
127
+ else:
128
+ self.relative_bias = None
129
+
130
+ self._reset_parameters()
131
+
132
+ def _reset_parameters(self):
133
+ """Initialize attention parameters."""
134
+
135
+ init.xavier_uniform_(self.q_proj.weight)
136
+ init.constant_(self.q_proj.bias, 0.)
137
+
138
+ init.xavier_uniform_(self.k_proj.weight)
139
+ init.constant_(self.k_proj.bias, 0.)
140
+
141
+ if isinstance(self.v_proj, nn.Linear):
142
+ init.xavier_uniform_(self.v_proj.weight)
143
+ init.constant_(self.v_proj.bias, 0.)
144
+
145
+ if isinstance(self.out_proj, nn.Linear):
146
+ init.xavier_uniform_(self.out_proj.weight)
147
+ init.constant_(self.out_proj.bias, 0.)
148
+
149
+ def forward(self, query, key_padding_mask=None, attn_mask=None):
150
+ """Compute multi-head self-attention.
151
+
152
+ Args:
153
+ query: input embeddings
154
+ key_padding_mask: 3D mask that prevents attention to certain positions
155
+ attn_mask: 3D mask that rescale the attention weight at each position
156
+ Returns:
157
+ attn_output: self-attention output
158
+ """
159
+
160
+ length, bsz, embed_dim = query.size()
161
+ assert embed_dim == self.embed_dim
162
+
163
+ head_dim = embed_dim // self.num_heads
164
+ assert head_dim * self.num_heads == embed_dim, ("embed_dim must be "
165
+ "divisible by num_heads")
166
+ scaling = float(head_dim)**-0.5
167
+
168
+ q = self.q_proj(query)
169
+ k = self.k_proj(query)
170
+ v = self.v_proj(query)
171
+
172
+ q = q * scaling
173
+
174
+ if attn_mask is not None:
175
+ assert list(attn_mask.size()) == [bsz * self.num_heads,
176
+ query.size(0), query.size(0)]
177
+
178
+ q = q.contiguous().view(length, bsz * self.num_heads,
179
+ head_dim).transpose(0, 1)
180
+ k = k.contiguous().view(length, bsz * self.num_heads,
181
+ head_dim).transpose(0, 1)
182
+ v = v.contiguous().view(length, bsz * self.num_heads,
183
+ head_dim).transpose(0, 1)
184
+
185
+ attn_output_weights = torch.bmm(q, k.transpose(1, 2))
186
+ assert list(
187
+ attn_output_weights.size()) == [bsz * self.num_heads, length, length]
188
+
189
+ if self.relative_bias is not None:
190
+ pos = torch.arange(length, device=query.device)
191
+ relative_pos = torch.abs(pos[:, None] - pos[None, :]) + 256
192
+ relative_pos = relative_pos[None, :, :].expand(bsz * self.num_heads, -1,
193
+ -1)
194
+
195
+ relative_bias = self.relative_bias.repeat_interleave(bsz, dim=0)
196
+ relative_bias = relative_bias[:, None, :].expand(-1, length, -1)
197
+ relative_bias = torch.gather(relative_bias, 2, relative_pos)
198
+ attn_output_weights = attn_output_weights + relative_bias
199
+
200
+ if key_padding_mask is not None:
201
+ attn_output_weights = attn_output_weights + key_padding_mask
202
+
203
+ if attn_mask is None:
204
+ attn_output_weights = torch.softmax(attn_output_weights, dim=-1)
205
+ else:
206
+ attn_output_weights = torch.sigmoid(attn_output_weights) * attn_mask
207
+
208
+ attn_output_weights = self.drop(attn_output_weights)
209
+
210
+ attn_output = torch.bmm(attn_output_weights, v)
211
+
212
+ assert list(attn_output.size()) == [bsz * self.num_heads, length, head_dim]
213
+ attn_output = attn_output.transpose(0, 1).contiguous().view(
214
+ length, bsz, embed_dim)
215
+ attn_output = self.out_proj(attn_output)
216
+
217
+ return attn_output
218
+
219
+
220
+ class TransformerLayer(nn.Module):
221
+ """TransformerEncoderLayer is made up of self-attn and feedforward network."""
222
+
223
+ def __init__(self,
224
+ d_model,
225
+ nhead,
226
+ dim_feedforward=2048,
227
+ dropout=0.1,
228
+ dropatt=0.1,
229
+ activation="leakyrelu",
230
+ relative_bias=True):
231
+ """Initialization.
232
+
233
+ Args:
234
+ d_model: dimension of inputs
235
+ nhead: number of self-attention heads
236
+ dim_feedforward: dimension of hidden layer in feedforward layer
237
+ dropout: dropout rate
238
+ dropatt: drop attention rate
239
+ activation: activation function
240
+ relative_bias: bool, indicate whether use a relative position based
241
+ attention bias
242
+ """
243
+
244
+ super(TransformerLayer, self).__init__()
245
+ self.self_attn = MultiheadAttention(
246
+ d_model, nhead, dropout=dropatt, relative_bias=relative_bias)
247
+ # Implementation of Feedforward model
248
+ self.feedforward = nn.Sequential(
249
+ nn.LayerNorm(d_model), nn.Linear(d_model, dim_feedforward),
250
+ _get_activation_fn(activation), nn.Dropout(dropout),
251
+ nn.Linear(dim_feedforward, d_model))
252
+
253
+ self.norm = nn.LayerNorm(d_model)
254
+ self.dropout1 = nn.Dropout(dropout)
255
+ self.dropout2 = nn.Dropout(dropout)
256
+
257
+ self.nhead = nhead
258
+
259
+ def forward(self, src, attn_mask=None, key_padding_mask=None):
260
+ """Pass the input through the encoder layer.
261
+
262
+ Args:
263
+ src: the sequence to the encoder layer (required).
264
+ attn_mask: the mask for the src sequence (optional).
265
+ key_padding_mask: the mask for the src keys per batch (optional).
266
+ Returns:
267
+ src3: the output of transformer layer, share the same shape as src.
268
+ """
269
+ src2 = self.self_attn(
270
+ self.norm(src), attn_mask=attn_mask, key_padding_mask=key_padding_mask)
271
+ src2 = src + self.dropout1(src2)
272
+ src3 = self.feedforward(src2)
273
+ src3 = src2 + self.dropout2(src3)
274
+
275
+ return src3
276
+
277
+
278
+ def cumprod(x, reverse=False, exclusive=False):
279
+ """cumulative product."""
280
+ if reverse:
281
+ x = x.flip([-1])
282
+
283
+ if exclusive:
284
+ x = F.pad(x[:, :, :-1], (1, 0), value=1)
285
+
286
+ cx = x.cumprod(-1)
287
+
288
+ if reverse:
289
+ cx = cx.flip([-1])
290
+ return cx
291
+
292
+ def cumsum(x, reverse=False, exclusive=False):
293
+ """cumulative sum."""
294
+ bsz, _, length = x.size()
295
+ device = x.device
296
+ if reverse:
297
+ if exclusive:
298
+ w = torch.ones([bsz, length, length], device=device).tril(-1)
299
+ else:
300
+ w = torch.ones([bsz, length, length], device=device).tril(0)
301
+ cx = torch.bmm(x, w)
302
+ else:
303
+ if exclusive:
304
+ w = torch.ones([bsz, length, length], device=device).triu(1)
305
+ else:
306
+ w = torch.ones([bsz, length, length], device=device).triu(0)
307
+ cx = torch.bmm(x, w)
308
+ return cx
309
+
310
+ def cummin(x, reverse=False, exclusive=False, max_value=1e9):
311
+ """cumulative min."""
312
+ if reverse:
313
+ if exclusive:
314
+ x = F.pad(x[:, :, 1:], (0, 1), value=max_value)
315
+ x = x.flip([-1]).cummin(-1)[0].flip([-1])
316
+ else:
317
+ if exclusive:
318
+ x = F.pad(x[:, :, :-1], (1, 0), value=max_value)
319
+ x = x.cummin(-1)[0]
320
+ return x
321
+
322
+ class Transformer(nn.Module):
323
+ """Transformer model."""
324
+
325
+ def __init__(self,
326
+ hidden_size,
327
+ nlayers,
328
+ ntokens,
329
+ nhead=8,
330
+ dropout=0.1,
331
+ dropatt=0.1,
332
+ relative_bias=True,
333
+ pos_emb=False,
334
+ pad=0):
335
+ """Initialization.
336
+
337
+ Args:
338
+ hidden_size: dimension of inputs and hidden states
339
+ nlayers: number of layers
340
+ ntokens: number of output categories
341
+ nhead: number of self-attention heads
342
+ dropout: dropout rate
343
+ dropatt: drop attention rate
344
+ relative_bias: bool, indicate whether use a relative position based
345
+ attention bias
346
+ pos_emb: bool, indicate whether use a learnable positional embedding
347
+ pad: pad token index
348
+ """
349
+
350
+ super(Transformer, self).__init__()
351
+
352
+ self.drop = nn.Dropout(dropout)
353
+
354
+ self.emb = nn.Embedding(ntokens, hidden_size)
355
+ if pos_emb:
356
+ self.pos_emb = nn.Embedding(500, hidden_size)
357
+
358
+ self.layers = nn.ModuleList([
359
+ TransformerLayer(hidden_size, nhead, hidden_size * 4, dropout,
360
+ dropatt=dropatt, relative_bias=relative_bias)
361
+ for _ in range(nlayers)])
362
+
363
+ self.norm = nn.LayerNorm(hidden_size)
364
+
365
+ self.output_layer = nn.Linear(hidden_size, ntokens)
366
+ self.output_layer.weight = self.emb.weight
367
+
368
+ self.init_weights()
369
+
370
+ self.nlayers = nlayers
371
+ self.nhead = nhead
372
+ self.ntokens = ntokens
373
+ self.hidden_size = hidden_size
374
+ self.pad = pad
375
+
376
+ def init_weights(self):
377
+ """Initialize token embedding and output bias."""
378
+ initrange = 0.1
379
+ self.emb.weight.data.uniform_(-initrange, initrange)
380
+ if hasattr(self, 'pos_emb'):
381
+ self.pos_emb.weight.data.uniform_(-initrange, initrange)
382
+ self.output_layer.bias.data.fill_(0)
383
+
384
+ def visibility(self, x, device):
385
+ """Mask pad tokens."""
386
+ visibility = (x != self.pad).float()
387
+ visibility = visibility[:, None, :].expand(-1, x.size(1), -1)
388
+ visibility = torch.repeat_interleave(visibility, self.nhead, dim=0)
389
+ return visibility.log()
390
+
391
+ def encode(self, x, pos):
392
+ """Standard transformer encode process."""
393
+ h = self.emb(x)
394
+ if hasattr(self, 'pos_emb'):
395
+ h = h + self.pos_emb(pos)
396
+ h_list = []
397
+ visibility = self.visibility(x, x.device)
398
+
399
+ for i in range(self.nlayers):
400
+ h_list.append(h)
401
+ h = self.layers[i](
402
+ h.transpose(0, 1), key_padding_mask=visibility).transpose(0, 1)
403
+
404
+ output = h
405
+ h_array = torch.stack(h_list, dim=2)
406
+
407
+ return output, h_array
408
+
409
+ def forward(self, x, pos):
410
+ """Pass the input through the encoder layer.
411
+
412
+ Args:
413
+ x: input tokens (required).
414
+ pos: position for each token (optional).
415
+ Returns:
416
+ output: probability distributions for missing tokens.
417
+ state_dict: parsing results and raw output
418
+ """
419
+
420
+ batch_size, length = x.size()
421
+
422
+ raw_output, _ = self.encode(x, pos)
423
+ raw_output = self.norm(raw_output)
424
+ raw_output = self.drop(raw_output)
425
+
426
+ output = self.output_layer(raw_output)
427
+ return output.view(batch_size * length, -1), {'raw_output': raw_output,}
428
+
429
+ class StructFormer(Transformer):
430
+ """StructFormer model."""
431
+
432
+ def __init__(self,
433
+ hidden_size,
434
+ nlayers,
435
+ ntokens,
436
+ nhead=8,
437
+ dropout=0.1,
438
+ dropatt=0.1,
439
+ relative_bias=False,
440
+ pos_emb=False,
441
+ pad=0,
442
+ n_parser_layers=4,
443
+ conv_size=9,
444
+ relations=('head', 'child'),
445
+ weight_act='softmax'):
446
+ """Initialization.
447
+
448
+ Args:
449
+ hidden_size: dimension of inputs and hidden states
450
+ nlayers: number of layers
451
+ ntokens: number of output categories
452
+ nhead: number of self-attention heads
453
+ dropout: dropout rate
454
+ dropatt: drop attention rate
455
+ relative_bias: bool, indicate whether use a relative position based
456
+ attention bias
457
+ pos_emb: bool, indicate whether use a learnable positional embedding
458
+ pad: pad token index
459
+ n_parser_layers: number of parsing layers
460
+ conv_size: convolution kernel size for parser
461
+ relations: relations that are used to compute self attention
462
+ weight_act: relations distribution activation function
463
+ """
464
+
465
+ super(StructFormer, self).__init__(
466
+ hidden_size,
467
+ nlayers,
468
+ ntokens,
469
+ nhead=nhead,
470
+ dropout=dropout,
471
+ dropatt=dropatt,
472
+ relative_bias=relative_bias,
473
+ pos_emb=pos_emb,
474
+ pad=pad)
475
+
476
+ self.parser_layers = nn.ModuleList([
477
+ nn.Sequential(Conv1d(hidden_size, conv_size),
478
+ nn.LayerNorm(hidden_size, elementwise_affine=False),
479
+ nn.Tanh()) for i in range(n_parser_layers)])
480
+
481
+ self.distance_ff = nn.Sequential(
482
+ Conv1d(hidden_size, 2),
483
+ nn.LayerNorm(hidden_size, elementwise_affine=False), nn.Tanh(),
484
+ nn.Linear(hidden_size, 1))
485
+
486
+ self.height_ff = nn.Sequential(
487
+ nn.Linear(hidden_size, hidden_size),
488
+ nn.LayerNorm(hidden_size, elementwise_affine=False), nn.Tanh(),
489
+ nn.Linear(hidden_size, 1))
490
+
491
+ n_rel = len(relations)
492
+ self._rel_weight = nn.Parameter(torch.zeros((nlayers, nhead, n_rel)))
493
+ self._rel_weight.data.normal_(0, 0.1)
494
+
495
+ self._scaler = nn.Parameter(torch.zeros(2))
496
+
497
+ self.n_parse_layers = n_parser_layers
498
+ self.weight_act = weight_act
499
+ self.relations = relations
500
+
501
+ @property
502
+ def scaler(self):
503
+ return self._scaler.exp()
504
+
505
+ @property
506
+ def rel_weight(self):
507
+ if self.weight_act == 'sigmoid':
508
+ return torch.sigmoid(self._rel_weight)
509
+ elif self.weight_act == 'softmax':
510
+ return torch.softmax(self._rel_weight, dim=-1)
511
+
512
+ def parse(self, x, pos):
513
+ """Parse input sentence.
514
+
515
+ Args:
516
+ x: input tokens (required).
517
+ pos: position for each token (optional).
518
+ Returns:
519
+ distance: syntactic distance
520
+ height: syntactic height
521
+ """
522
+
523
+ mask = (x != self.pad)
524
+ mask_shifted = F.pad(mask[:, 1:], (0, 1), value=0)
525
+
526
+ h = self.emb(x)
527
+ for i in range(self.n_parse_layers):
528
+ h = h.masked_fill(~mask[:, :, None], 0)
529
+ h = self.parser_layers[i](h)
530
+
531
+ height = self.height_ff(h).squeeze(-1)
532
+ height.masked_fill_(~mask, -1e9)
533
+
534
+ distance = self.distance_ff(h).squeeze(-1)
535
+ distance.masked_fill_(~mask_shifted, 1e9)
536
+
537
+ # Calbrating the distance and height to the same level
538
+ length = distance.size(1)
539
+ height_max = height[:, None, :].expand(-1, length, -1)
540
+ height_max = torch.cummax(
541
+ height_max.triu(0) - torch.ones_like(height_max).tril(-1) * 1e9,
542
+ dim=-1)[0].triu(0)
543
+
544
+ margin_left = torch.relu(
545
+ F.pad(distance[:, :-1, None], (0, 0, 1, 0), value=1e9) - height_max)
546
+ margin_right = torch.relu(distance[:, None, :] - height_max)
547
+ margin = torch.where(margin_left > margin_right, margin_right,
548
+ margin_left).triu(0)
549
+
550
+ margin_mask = torch.stack([mask_shifted] + [mask] * (length - 1), dim=1)
551
+ margin.masked_fill_(~margin_mask, 0)
552
+ margin = margin.max()
553
+
554
+ distance = distance - margin
555
+
556
+ return distance, height
557
+
558
+ def compute_block(self, distance, height):
559
+ """Compute constituents from distance and height."""
560
+
561
+ beta_logits = (distance[:, None, :] - height[:, :, None]) * self.scaler[0]
562
+
563
+ gamma = torch.sigmoid(-beta_logits)
564
+ ones = torch.ones_like(gamma)
565
+
566
+ block_mask_left = cummin(
567
+ gamma.tril(-1) + ones.triu(0), reverse=True, max_value=1)
568
+ block_mask_left = block_mask_left - F.pad(
569
+ block_mask_left[:, :, :-1], (1, 0), value=0)
570
+ block_mask_left.tril_(0)
571
+
572
+ block_mask_right = cummin(
573
+ gamma.triu(0) + ones.tril(-1), exclusive=True, max_value=1)
574
+ block_mask_right = block_mask_right - F.pad(
575
+ block_mask_right[:, :, 1:], (0, 1), value=0)
576
+ block_mask_right.triu_(0)
577
+
578
+ block_p = block_mask_left[:, :, :, None] * block_mask_right[:, :, None, :]
579
+ block = cumsum(block_mask_left).tril(0) + cumsum(
580
+ block_mask_right, reverse=True).triu(1)
581
+
582
+ return block_p, block
583
+
584
+ def compute_head(self, height):
585
+ """Estimate head for each constituent."""
586
+
587
+ _, length = height.size()
588
+ head_logits = height * self.scaler[1]
589
+ index = torch.arange(length, device=height.device)
590
+
591
+ mask = (index[:, None, None] <= index[None, None, :]) * (
592
+ index[None, None, :] <= index[None, :, None])
593
+ head_logits = head_logits[:, None, None, :].repeat(1, length, length, 1)
594
+ head_logits.masked_fill_(~mask[None, :, :, :], -1e9)
595
+
596
+ head_p = torch.softmax(head_logits, dim=-1)
597
+
598
+ return head_p
599
+
600
+ def generate_mask(self, x, distance, height):
601
+ """Compute head and cibling distribution for each token."""
602
+
603
+ bsz, length = x.size()
604
+
605
+ eye = torch.eye(length, device=x.device, dtype=torch.bool)
606
+ eye = eye[None, :, :].expand((bsz, -1, -1))
607
+
608
+ block_p, block = self.compute_block(distance, height)
609
+ head_p = self.compute_head(height)
610
+ head = torch.einsum('blij,bijh->blh', block_p, head_p)
611
+ head = head.masked_fill(eye, 0)
612
+ child = head.transpose(1, 2)
613
+ cibling = torch.bmm(head, child).masked_fill(eye, 0)
614
+
615
+ rel_list = []
616
+ if 'head' in self.relations:
617
+ rel_list.append(head)
618
+ if 'child' in self.relations:
619
+ rel_list.append(child)
620
+ if 'cibling' in self.relations:
621
+ rel_list.append(cibling)
622
+
623
+ rel = torch.stack(rel_list, dim=1)
624
+
625
+ rel_weight = self.rel_weight
626
+
627
+ dep = torch.einsum('lhr,brij->lbhij', rel_weight, rel)
628
+ att_mask = dep.reshape(self.nlayers, bsz * self.nhead, length, length)
629
+
630
+ return att_mask, cibling, head, block
631
+
632
+ def encode(self, x, pos, att_mask):
633
+ """Structformer encoding process."""
634
+
635
+ visibility = self.visibility(x, x.device)
636
+ h = self.emb(x)
637
+ if hasattr(self, 'pos_emb'):
638
+ assert pos.max() < 500
639
+ h = h + self.pos_emb(pos)
640
+ for i in range(self.nlayers):
641
+ h = self.layers[i](
642
+ h.transpose(0, 1), attn_mask=att_mask[i],
643
+ key_padding_mask=visibility).transpose(0, 1)
644
+ return h
645
+
646
+ def forward(self, x, pos):
647
+ """Pass the input through the encoder layer.
648
+
649
+ Args:
650
+ x: input tokens (required).
651
+ pos: position for each token (optional).
652
+ Returns:
653
+ output: probability distributions for missing tokens.
654
+ state_dict: parsing results and raw output
655
+ """
656
+
657
+ batch_size, length = x.size()
658
+
659
+ distance, height = self.parse(x, pos)
660
+ att_mask, cibling, head, block = self.generate_mask(x, distance, height)
661
+
662
+ raw_output = self.encode(x, pos, att_mask)
663
+ raw_output = self.norm(raw_output)
664
+ raw_output = self.drop(raw_output)
665
+
666
+ output = self.output_layer(raw_output)
667
+
668
+ return output.view(batch_size * length, -1), \
669
+ {'raw_output': raw_output, 'distance': distance, 'height': height,
670
+ 'cibling': cibling, 'head': head, 'block': block}
671
+
672
+
673
+ ##########################################
674
+ # Clasication Head For BabyLM Evaluation Tasks
675
+ ##########################################
676
+ class ClassificationHead(nn.Module):
677
+ """Head for sentence-level classification tasks."""
678
+ def __init__(self, config):
679
+ super(ClassificationHead, self).__init__()
680
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
681
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
682
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
683
+
684
+ def forward(self, features, **kwargs):
685
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
686
+ x = self.dropout(x)
687
+ x = self.dense(x)
688
+ x = torch.tanh(x)
689
+ x = self.dropout(x)
690
+ x = self.out_proj(x)
691
+ return x
692
+
693
+ ##########################################
694
+ # HuggingFace Config
695
+ ##########################################
696
+ class StructFormerConfig(PretrainedConfig):
697
+ model_type = "structformer"
698
+
699
+ def __init__(
700
+ self,
701
+ hidden_size=512,
702
+ nlayers=8,
703
+ ntokens=10_000,
704
+ nhead=8,
705
+ dropout=0.1,
706
+ dropatt=0.1,
707
+ relative_bias=False,
708
+ pos_emb=False,
709
+ pad=0,
710
+ n_parser_layers=4,
711
+ conv_size=9,
712
+ relations=('head', 'child'),
713
+ weight_act='softmax',
714
+ num_labels=1,
715
+ hidden_dropout_prob=0.1,
716
+ initializer_range=0.02,
717
+ **kwargs,
718
+ ):
719
+ self.hidden_size = hidden_size
720
+ self.nlayers = nlayers
721
+ self.ntokens = ntokens
722
+ self.nhead = nhead
723
+ self.dropout = dropout
724
+ self.dropatt = dropatt
725
+ self.relative_bias = relative_bias
726
+ self.pos_emb = pos_emb
727
+ self.pad = pad
728
+ self.n_parser_layers = n_parser_layers
729
+ self.conv_size = conv_size
730
+ self.relations = relations
731
+ self.weight_act = weight_act
732
+ self.num_labels = num_labels
733
+ self.hidden_dropout_prob = hidden_dropout_prob
734
+ self.initializer_range=initializer_range
735
+ super().__init__(**kwargs)
736
+
737
+ ##########################################
738
+ # HuggingFace Model
739
+ ##########################################
740
+ class StructFormerModel(PreTrainedModel):
741
+ config_class = StructFormerConfig
742
+
743
+ def __init__(self, config):
744
+ super().__init__(config)
745
+ self.model = StructFormer(
746
+ hidden_size=config.hidden_size,
747
+ nlayers=config.nlayers,
748
+ ntokens=config.ntokens,
749
+ nhead=config.nhead,
750
+ dropout=config.dropout,
751
+ dropatt=config.dropatt,
752
+ relative_bias=config.relative_bias,
753
+ pos_emb=config.pos_emb,
754
+ pad=config.pad,
755
+ n_parser_layers=config.n_parser_layers,
756
+ conv_size=config.conv_size,
757
+ relations=config.relations,
758
+ weight_act=config.weight_act
759
+ )
760
+ self.config = config
761
+
762
+ def parse(self, input_ids, **kwargs):
763
+ x = input_ids
764
+ batch_size, length = x.size()
765
+ pos = kwargs['position_ids'] if 'position_ids' in kwargs.keys() else torch.arange(length, device=x.device).expand(batch_size, length)
766
+
767
+ sf_output = self.model(x, pos)
768
+
769
+ return sf_output[1]
770
+
771
+ def forward(self, input_ids, labels=None, **kwargs):
772
+ x = input_ids
773
+ batch_size, length = x.size()
774
+ pos = kwargs['position_ids'] if 'position_ids' in kwargs.keys() else torch.arange(length, device=x.device).expand(batch_size, length)
775
+
776
+ sf_output = self.model(x, pos)
777
+
778
+ loss = None
779
+ if labels is not None:
780
+ loss_fct = nn.CrossEntropyLoss()
781
+ loss = loss_fct(sf_output[0], labels.reshape(-1))
782
+
783
+ return MaskedLMOutput(
784
+ loss=loss, # shape: 1
785
+ logits=sf_output[0].view(batch_size, length, -1), # shape: (batch_size, length, ntokens)
786
+ hidden_states=None,
787
+ attentions=None
788
+ )
789
+
790
+ class StructFormerModelForSequenceClassification(PreTrainedModel):
791
+ config_class = StructFormerConfig
792
+
793
+ def __init__(self, config):
794
+ super().__init__(config)
795
+ self.model = StructFormer(
796
+ hidden_size=config.hidden_size,
797
+ nlayers=config.nlayers,
798
+ ntokens=config.ntokens,
799
+ nhead=config.nhead,
800
+ dropout=config.dropout,
801
+ dropatt=config.dropatt,
802
+ relative_bias=config.relative_bias,
803
+ pos_emb=config.pos_emb,
804
+ pad=config.pad,
805
+ n_parser_layers=config.n_parser_layers,
806
+ conv_size=config.conv_size,
807
+ relations=config.relations,
808
+ weight_act=config.weight_act
809
+ )
810
+ self.config = config
811
+ self.num_labels = config.num_labels
812
+ self.model.classifier = ClassificationHead(config)
813
+
814
+ def _init_weights(self, module):
815
+ """Initialize the weights"""
816
+ if isinstance(module, nn.Linear):
817
+ # Slightly different from the TF version which uses truncated_normal for initialization
818
+ # cf https://github.com/pytorch/pytorch/pull/5617
819
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
820
+ if module.bias is not None:
821
+ module.bias.data.zero_()
822
+ elif isinstance(module, nn.Embedding):
823
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
824
+ if module.padding_idx is not None:
825
+ module.weight.data[module.padding_idx].zero_()
826
+ elif isinstance(module, nn.LayerNorm):
827
+ if module.bias is not None:
828
+ module.bias.data.zero_()
829
+ module.weight.data.fill_(1.0)
830
+
831
+ def forward(self, input_ids, labels=None, **kwargs):
832
+ x = input_ids
833
+ batch_size, length = x.size()
834
+ pos = kwargs['position_ids'] if 'position_ids' in kwargs.keys() else torch.arange(length, device=x.device).expand(batch_size, length)
835
+
836
+ sf_output = self.model(x, pos)
837
+
838
+ logits = self.model.classifier(sf_output[1]['raw_output'])
839
+ loss = None
840
+ if labels is not None:
841
+ if self.config.problem_type is None:
842
+ if self.num_labels == 1:
843
+ self.config.problem_type = "regression"
844
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
845
+ self.config.problem_type = "single_label_classification"
846
+ else:
847
+ self.config.problem_type = "multi_label_classification"
848
+
849
+ if self.config.problem_type == "regression":
850
+ loss_fct = nn.MSELoss()
851
+ if self.num_labels == 1:
852
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
853
+ else:
854
+ loss = loss_fct(logits, labels)
855
+ elif self.config.problem_type == "single_label_classification":
856
+ loss_fct = nn.CrossEntropyLoss()
857
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
858
+ elif self.config.problem_type == "multi_label_classification":
859
+ loss_fct = nn.BCEWithLogitsLoss()
860
+ loss = loss_fct(logits, labels)
861
+
862
+ return SequenceClassifierOutput(
863
+ loss=loss,
864
+ logits=logits,
865
+ hidden_states=None,
866
+ attentions=None,
867
+ )
finetune/boolq/checkpoint-200/tokenizer_config.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "bos_token": {
4
+ "__type": "AddedToken",
5
+ "content": "<s>",
6
+ "lstrip": false,
7
+ "normalized": true,
8
+ "rstrip": false,
9
+ "single_word": false
10
+ },
11
+ "cls_token": {
12
+ "__type": "AddedToken",
13
+ "content": "<s>",
14
+ "lstrip": false,
15
+ "normalized": true,
16
+ "rstrip": false,
17
+ "single_word": false
18
+ },
19
+ "eos_token": {
20
+ "__type": "AddedToken",
21
+ "content": "</s>",
22
+ "lstrip": false,
23
+ "normalized": true,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ },
27
+ "errors": "replace",
28
+ "mask_token": {
29
+ "__type": "AddedToken",
30
+ "content": "<mask>",
31
+ "lstrip": true,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false
35
+ },
36
+ "model_max_length": 512,
37
+ "name_or_path": "omarmomen/sf_babylm_1",
38
+ "pad_token": {
39
+ "__type": "AddedToken",
40
+ "content": "<pad>",
41
+ "lstrip": false,
42
+ "normalized": true,
43
+ "rstrip": false,
44
+ "single_word": false
45
+ },
46
+ "sep_token": {
47
+ "__type": "AddedToken",
48
+ "content": "</s>",
49
+ "lstrip": false,
50
+ "normalized": true,
51
+ "rstrip": false,
52
+ "single_word": false
53
+ },
54
+ "special_tokens_map_file": null,
55
+ "tokenizer_class": "RobertaTokenizer",
56
+ "trim_offsets": true,
57
+ "unk_token": {
58
+ "__type": "AddedToken",
59
+ "content": "<unk>",
60
+ "lstrip": false,
61
+ "normalized": true,
62
+ "rstrip": false,
63
+ "single_word": false
64
+ }
65
+ }
finetune/boolq/checkpoint-200/trainer_state.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": 0.7282728272827282,
3
+ "best_model_checkpoint": "omarmomen/sf_babylm_1/finetune/boolq/checkpoint-200",
4
+ "epoch": 6.0606060606060606,
5
+ "global_step": 200,
6
+ "is_hyper_param_search": false,
7
+ "is_local_process_zero": true,
8
+ "is_world_process_zero": true,
9
+ "log_history": [
10
+ {
11
+ "epoch": 6.06,
12
+ "eval_accuracy": 0.658367931842804,
13
+ "eval_f1": 0.7282728272827282,
14
+ "eval_loss": 0.9740044474601746,
15
+ "eval_mcc": 0.27328046278245693,
16
+ "eval_runtime": 1.2669,
17
+ "eval_samples_per_second": 570.67,
18
+ "eval_steps_per_second": 71.827,
19
+ "step": 200
20
+ }
21
+ ],
22
+ "max_steps": 330,
23
+ "num_train_epochs": 10,
24
+ "total_flos": 321868603269120.0,
25
+ "trial_name": null,
26
+ "trial_params": null
27
+ }
finetune/boolq/checkpoint-200/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:553f78e16a096fe90d36b0a7936e92787a1172a9f02cf4e4611e107248227ef4
3
+ size 3960
finetune/boolq/checkpoint-200/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
finetune/boolq/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "omarmomen/sf_babylm_1",
3
+ "architectures": [
4
+ "StructFormerModelForSequenceClassification"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "structformer.StructFormerConfig",
8
+ "AutoModelForMaskedLM": "structformer.StructFormerModel",
9
+ "AutoModelForSequenceClassification": "structformer.StructFormerModelForSequenceClassification"
10
+ },
11
+ "conv_size": 9,
12
+ "dropatt": 0.1,
13
+ "dropout": 0.1,
14
+ "hidden_dropout_prob": 0.1,
15
+ "hidden_size": 512,
16
+ "id2label": {
17
+ "0": 0,
18
+ "1": 1
19
+ },
20
+ "initializer_range": 0.02,
21
+ "label2id": {
22
+ "0": 0,
23
+ "1": 1
24
+ },
25
+ "model_type": "structformer",
26
+ "n_parser_layers": 3,
27
+ "nhead": 8,
28
+ "nlayers": 8,
29
+ "ntokens": 16000,
30
+ "pad": 1,
31
+ "pos_emb": true,
32
+ "problem_type": "single_label_classification",
33
+ "relations": [
34
+ "head",
35
+ "child"
36
+ ],
37
+ "relative_bias": false,
38
+ "torch_dtype": "float32",
39
+ "transformers_version": "4.26.1",
40
+ "weight_act": "softmax"
41
+ }
finetune/boolq/eval_results.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 10.0,
3
+ "eval_accuracy": 0.658367931842804,
4
+ "eval_f1": 0.7282728272827282,
5
+ "eval_loss": 0.9740044474601746,
6
+ "eval_mcc": 0.27328046278245693,
7
+ "eval_runtime": 1.2249,
8
+ "eval_samples": 723,
9
+ "eval_samples_per_second": 590.256,
10
+ "eval_steps_per_second": 74.292
11
+ }
finetune/boolq/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
finetune/boolq/predict_results.txt ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ index prediction
2
+ 0 1
3
+ 1 1
4
+ 2 1
5
+ 3 1
6
+ 4 1
7
+ 5 1
8
+ 6 1
9
+ 7 1
10
+ 8 1
11
+ 9 0
12
+ 10 1
13
+ 11 1
14
+ 12 0
15
+ 13 0
16
+ 14 1
17
+ 15 1
18
+ 16 1
19
+ 17 1
20
+ 18 1
21
+ 19 1
22
+ 20 0
23
+ 21 1
24
+ 22 1
25
+ 23 0
26
+ 24 0
27
+ 25 0
28
+ 26 1
29
+ 27 1
30
+ 28 0
31
+ 29 1
32
+ 30 1
33
+ 31 1
34
+ 32 0
35
+ 33 1
36
+ 34 1
37
+ 35 1
38
+ 36 1
39
+ 37 1
40
+ 38 1
41
+ 39 1
42
+ 40 0
43
+ 41 0
44
+ 42 1
45
+ 43 1
46
+ 44 1
47
+ 45 1
48
+ 46 1
49
+ 47 1
50
+ 48 1
51
+ 49 1
52
+ 50 1
53
+ 51 1
54
+ 52 0
55
+ 53 1
56
+ 54 0
57
+ 55 1
58
+ 56 1
59
+ 57 0
60
+ 58 0
61
+ 59 0
62
+ 60 1
63
+ 61 0
64
+ 62 1
65
+ 63 0
66
+ 64 1
67
+ 65 1
68
+ 66 1
69
+ 67 0
70
+ 68 1
71
+ 69 1
72
+ 70 1
73
+ 71 0
74
+ 72 0
75
+ 73 1
76
+ 74 0
77
+ 75 0
78
+ 76 1
79
+ 77 0
80
+ 78 1
81
+ 79 0
82
+ 80 1
83
+ 81 0
84
+ 82 0
85
+ 83 1
86
+ 84 1
87
+ 85 1
88
+ 86 0
89
+ 87 0
90
+ 88 0
91
+ 89 1
92
+ 90 1
93
+ 91 0
94
+ 92 0
95
+ 93 1
96
+ 94 0
97
+ 95 1
98
+ 96 0
99
+ 97 1
100
+ 98 0
101
+ 99 1
102
+ 100 1
103
+ 101 0
104
+ 102 1
105
+ 103 0
106
+ 104 0
107
+ 105 1
108
+ 106 1
109
+ 107 0
110
+ 108 1
111
+ 109 1
112
+ 110 1
113
+ 111 1
114
+ 112 0
115
+ 113 0
116
+ 114 1
117
+ 115 0
118
+ 116 0
119
+ 117 1
120
+ 118 1
121
+ 119 1
122
+ 120 1
123
+ 121 1
124
+ 122 1
125
+ 123 0
126
+ 124 1
127
+ 125 1
128
+ 126 0
129
+ 127 1
130
+ 128 1
131
+ 129 1
132
+ 130 0
133
+ 131 0
134
+ 132 0
135
+ 133 1
136
+ 134 1
137
+ 135 1
138
+ 136 1
139
+ 137 0
140
+ 138 1
141
+ 139 0
142
+ 140 0
143
+ 141 1
144
+ 142 1
145
+ 143 1
146
+ 144 1
147
+ 145 0
148
+ 146 1
149
+ 147 0
150
+ 148 1
151
+ 149 1
152
+ 150 0
153
+ 151 1
154
+ 152 1
155
+ 153 1
156
+ 154 1
157
+ 155 0
158
+ 156 0
159
+ 157 1
160
+ 158 1
161
+ 159 1
162
+ 160 1
163
+ 161 1
164
+ 162 1
165
+ 163 0
166
+ 164 1
167
+ 165 0
168
+ 166 1
169
+ 167 0
170
+ 168 0
171
+ 169 0
172
+ 170 1
173
+ 171 0
174
+ 172 0
175
+ 173 1
176
+ 174 1
177
+ 175 1
178
+ 176 1
179
+ 177 1
180
+ 178 0
181
+ 179 1
182
+ 180 0
183
+ 181 1
184
+ 182 1
185
+ 183 1
186
+ 184 0
187
+ 185 1
188
+ 186 1
189
+ 187 0
190
+ 188 1
191
+ 189 1
192
+ 190 1
193
+ 191 0
194
+ 192 1
195
+ 193 0
196
+ 194 1
197
+ 195 0
198
+ 196 1
199
+ 197 1
200
+ 198 0
201
+ 199 1
202
+ 200 1
203
+ 201 1
204
+ 202 1
205
+ 203 0
206
+ 204 1
207
+ 205 1
208
+ 206 1
209
+ 207 1
210
+ 208 1
211
+ 209 1
212
+ 210 1
213
+ 211 1
214
+ 212 1
215
+ 213 1
216
+ 214 1
217
+ 215 1
218
+ 216 1
219
+ 217 1
220
+ 218 1
221
+ 219 0
222
+ 220 1
223
+ 221 1
224
+ 222 1
225
+ 223 0
226
+ 224 0
227
+ 225 0
228
+ 226 1
229
+ 227 1
230
+ 228 0
231
+ 229 1
232
+ 230 0
233
+ 231 0
234
+ 232 0
235
+ 233 0
236
+ 234 0
237
+ 235 1
238
+ 236 0
239
+ 237 1
240
+ 238 1
241
+ 239 1
242
+ 240 1
243
+ 241 0
244
+ 242 1
245
+ 243 1
246
+ 244 0
247
+ 245 0
248
+ 246 1
249
+ 247 0
250
+ 248 0
251
+ 249 1
252
+ 250 1
253
+ 251 0
254
+ 252 1
255
+ 253 1
256
+ 254 1
257
+ 255 0
258
+ 256 0
259
+ 257 0
260
+ 258 1
261
+ 259 0
262
+ 260 1
263
+ 261 1
264
+ 262 1
265
+ 263 1
266
+ 264 1
267
+ 265 1
268
+ 266 1
269
+ 267 0
270
+ 268 1
271
+ 269 1
272
+ 270 0
273
+ 271 1
274
+ 272 1
275
+ 273 1
276
+ 274 1
277
+ 275 1
278
+ 276 0
279
+ 277 1
280
+ 278 1
281
+ 279 0
282
+ 280 0
283
+ 281 1
284
+ 282 0
285
+ 283 0
286
+ 284 1
287
+ 285 0
288
+ 286 1
289
+ 287 1
290
+ 288 1
291
+ 289 0
292
+ 290 1
293
+ 291 0
294
+ 292 1
295
+ 293 1
296
+ 294 1
297
+ 295 1
298
+ 296 1
299
+ 297 0
300
+ 298 1
301
+ 299 0
302
+ 300 1
303
+ 301 0
304
+ 302 1
305
+ 303 0
306
+ 304 0
307
+ 305 0
308
+ 306 0
309
+ 307 0
310
+ 308 0
311
+ 309 0
312
+ 310 0
313
+ 311 1
314
+ 312 1
315
+ 313 1
316
+ 314 0
317
+ 315 1
318
+ 316 1
319
+ 317 1
320
+ 318 1
321
+ 319 1
322
+ 320 0
323
+ 321 1
324
+ 322 1
325
+ 323 1
326
+ 324 1
327
+ 325 0
328
+ 326 1
329
+ 327 1
330
+ 328 1
331
+ 329 1
332
+ 330 0
333
+ 331 1
334
+ 332 1
335
+ 333 1
336
+ 334 0
337
+ 335 0
338
+ 336 0
339
+ 337 1
340
+ 338 1
341
+ 339 1
342
+ 340 1
343
+ 341 0
344
+ 342 1
345
+ 343 0
346
+ 344 0
347
+ 345 1
348
+ 346 1
349
+ 347 1
350
+ 348 1
351
+ 349 0
352
+ 350 0
353
+ 351 0
354
+ 352 1
355
+ 353 1
356
+ 354 1
357
+ 355 1
358
+ 356 0
359
+ 357 1
360
+ 358 0
361
+ 359 1
362
+ 360 1
363
+ 361 1
364
+ 362 0
365
+ 363 1
366
+ 364 0
367
+ 365 1
368
+ 366 0
369
+ 367 1
370
+ 368 1
371
+ 369 1
372
+ 370 0
373
+ 371 1
374
+ 372 1
375
+ 373 1
376
+ 374 1
377
+ 375 1
378
+ 376 1
379
+ 377 1
380
+ 378 0
381
+ 379 0
382
+ 380 0
383
+ 381 1
384
+ 382 1
385
+ 383 0
386
+ 384 1
387
+ 385 0
388
+ 386 1
389
+ 387 1
390
+ 388 1
391
+ 389 0
392
+ 390 1
393
+ 391 0
394
+ 392 1
395
+ 393 1
396
+ 394 1
397
+ 395 0
398
+ 396 1
399
+ 397 1
400
+ 398 1
401
+ 399 1
402
+ 400 1
403
+ 401 0
404
+ 402 1
405
+ 403 1
406
+ 404 1
407
+ 405 1
408
+ 406 0
409
+ 407 0
410
+ 408 1
411
+ 409 1
412
+ 410 1
413
+ 411 0
414
+ 412 0
415
+ 413 1
416
+ 414 1
417
+ 415 0
418
+ 416 1
419
+ 417 0
420
+ 418 0
421
+ 419 1
422
+ 420 1
423
+ 421 0
424
+ 422 1
425
+ 423 0
426
+ 424 1
427
+ 425 0
428
+ 426 1
429
+ 427 1
430
+ 428 1
431
+ 429 1
432
+ 430 1
433
+ 431 0
434
+ 432 1
435
+ 433 1
436
+ 434 1
437
+ 435 0
438
+ 436 0
439
+ 437 1
440
+ 438 1
441
+ 439 1
442
+ 440 0
443
+ 441 0
444
+ 442 0
445
+ 443 1
446
+ 444 0
447
+ 445 1
448
+ 446 1
449
+ 447 0
450
+ 448 1
451
+ 449 1
452
+ 450 0
453
+ 451 1
454
+ 452 1
455
+ 453 0
456
+ 454 1
457
+ 455 0
458
+ 456 1
459
+ 457 0
460
+ 458 1
461
+ 459 1
462
+ 460 1
463
+ 461 1
464
+ 462 0
465
+ 463 1
466
+ 464 0
467
+ 465 0
468
+ 466 1
469
+ 467 1
470
+ 468 1
471
+ 469 0
472
+ 470 1
473
+ 471 1
474
+ 472 1
475
+ 473 1
476
+ 474 1
477
+ 475 1
478
+ 476 1
479
+ 477 0
480
+ 478 0
481
+ 479 1
482
+ 480 1
483
+ 481 1
484
+ 482 0
485
+ 483 1
486
+ 484 1
487
+ 485 1
488
+ 486 1
489
+ 487 1
490
+ 488 1
491
+ 489 0
492
+ 490 1
493
+ 491 1
494
+ 492 1
495
+ 493 0
496
+ 494 1
497
+ 495 1
498
+ 496 1
499
+ 497 0
500
+ 498 0
501
+ 499 1
502
+ 500 1
503
+ 501 1
504
+ 502 0
505
+ 503 1
506
+ 504 0
507
+ 505 0
508
+ 506 1
509
+ 507 0
510
+ 508 1
511
+ 509 1
512
+ 510 1
513
+ 511 1
514
+ 512 1
515
+ 513 1
516
+ 514 0
517
+ 515 0
518
+ 516 1
519
+ 517 1
520
+ 518 1
521
+ 519 1
522
+ 520 1
523
+ 521 1
524
+ 522 0
525
+ 523 0
526
+ 524 1
527
+ 525 1
528
+ 526 0
529
+ 527 1
530
+ 528 0
531
+ 529 0
532
+ 530 1
533
+ 531 1
534
+ 532 0
535
+ 533 1
536
+ 534 1
537
+ 535 1
538
+ 536 1
539
+ 537 1
540
+ 538 1
541
+ 539 0
542
+ 540 1
543
+ 541 1
544
+ 542 1
545
+ 543 0
546
+ 544 1
547
+ 545 1
548
+ 546 0
549
+ 547 1
550
+ 548 1
551
+ 549 1
552
+ 550 1
553
+ 551 0
554
+ 552 0
555
+ 553 0
556
+ 554 0
557
+ 555 0
558
+ 556 1
559
+ 557 0
560
+ 558 0
561
+ 559 1
562
+ 560 0
563
+ 561 1
564
+ 562 1
565
+ 563 1
566
+ 564 0
567
+ 565 0
568
+ 566 1
569
+ 567 1
570
+ 568 1
571
+ 569 1
572
+ 570 1
573
+ 571 1
574
+ 572 1
575
+ 573 1
576
+ 574 1
577
+ 575 1
578
+ 576 1
579
+ 577 1
580
+ 578 1
581
+ 579 1
582
+ 580 1
583
+ 581 0
584
+ 582 1
585
+ 583 1
586
+ 584 1
587
+ 585 1
588
+ 586 1
589
+ 587 1
590
+ 588 0
591
+ 589 0
592
+ 590 1
593
+ 591 1
594
+ 592 0
595
+ 593 1
596
+ 594 1
597
+ 595 1
598
+ 596 0
599
+ 597 0
600
+ 598 0
601
+ 599 1
602
+ 600 0
603
+ 601 0
604
+ 602 1
605
+ 603 1
606
+ 604 1
607
+ 605 1
608
+ 606 1
609
+ 607 1
610
+ 608 1
611
+ 609 1
612
+ 610 1
613
+ 611 1
614
+ 612 0
615
+ 613 1
616
+ 614 1
617
+ 615 0
618
+ 616 1
619
+ 617 1
620
+ 618 1
621
+ 619 1
622
+ 620 1
623
+ 621 1
624
+ 622 0
625
+ 623 1
626
+ 624 1
627
+ 625 0
628
+ 626 1
629
+ 627 1
630
+ 628 1
631
+ 629 0
632
+ 630 1
633
+ 631 1
634
+ 632 0
635
+ 633 1
636
+ 634 1
637
+ 635 0
638
+ 636 1
639
+ 637 1
640
+ 638 1
641
+ 639 0
642
+ 640 1
643
+ 641 0
644
+ 642 0
645
+ 643 0
646
+ 644 0
647
+ 645 1
648
+ 646 1
649
+ 647 0
650
+ 648 1
651
+ 649 1
652
+ 650 1
653
+ 651 1
654
+ 652 1
655
+ 653 1
656
+ 654 0
657
+ 655 1
658
+ 656 1
659
+ 657 0
660
+ 658 0
661
+ 659 1
662
+ 660 0
663
+ 661 0
664
+ 662 1
665
+ 663 1
666
+ 664 1
667
+ 665 1
668
+ 666 0
669
+ 667 1
670
+ 668 0
671
+ 669 1
672
+ 670 1
673
+ 671 1
674
+ 672 1
675
+ 673 1
676
+ 674 0
677
+ 675 1
678
+ 676 1
679
+ 677 1
680
+ 678 0
681
+ 679 0
682
+ 680 1
683
+ 681 1
684
+ 682 1
685
+ 683 1
686
+ 684 0
687
+ 685 1
688
+ 686 1
689
+ 687 0
690
+ 688 0
691
+ 689 1
692
+ 690 1
693
+ 691 0
694
+ 692 0
695
+ 693 1
696
+ 694 1
697
+ 695 1
698
+ 696 1
699
+ 697 1
700
+ 698 1
701
+ 699 0
702
+ 700 1
703
+ 701 0
704
+ 702 1
705
+ 703 1
706
+ 704 1
707
+ 705 1
708
+ 706 1
709
+ 707 1
710
+ 708 1
711
+ 709 1
712
+ 710 1
713
+ 711 0
714
+ 712 1
715
+ 713 0
716
+ 714 0
717
+ 715 1
718
+ 716 0
719
+ 717 0
720
+ 718 0
721
+ 719 0
722
+ 720 0
723
+ 721 1
724
+ 722 1
finetune/boolq/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e4f79d98ac75f5de6364c0f52da1493dc993efa95b33032b8444be736b945bf5
3
+ size 167313902
finetune/boolq/special_tokens_map.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<s>",
3
+ "cls_token": "<s>",
4
+ "eos_token": "</s>",
5
+ "mask_token": {
6
+ "content": "<mask>",
7
+ "lstrip": true,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "pad_token": "<pad>",
13
+ "sep_token": "</s>",
14
+ "unk_token": "<unk>"
15
+ }
finetune/boolq/structformer.py ADDED
@@ -0,0 +1,867 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Google Research Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """StructFormer and transformer model."""
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from torch.nn import init
22
+ from transformers import PretrainedConfig, PreTrainedModel
23
+ from transformers.modeling_outputs import MaskedLMOutput, SequenceClassifierOutput
24
+
25
+ def _get_activation_fn(activation):
26
+ """Get specified activation function."""
27
+ if activation == "relu":
28
+ return nn.ReLU()
29
+ elif activation == "gelu":
30
+ return nn.GELU()
31
+ elif activation == "leakyrelu":
32
+ return nn.LeakyReLU()
33
+
34
+ raise RuntimeError(
35
+ "activation should be relu/gelu, not {}".format(activation))
36
+
37
+
38
+ class Conv1d(nn.Module):
39
+ """1D convolution layer."""
40
+
41
+ def __init__(self, hidden_size, kernel_size, dilation=1):
42
+ """Initialization.
43
+
44
+ Args:
45
+ hidden_size: dimension of input embeddings
46
+ kernel_size: convolution kernel size
47
+ dilation: the spacing between the kernel points
48
+ """
49
+ super(Conv1d, self).__init__()
50
+
51
+ if kernel_size % 2 == 0:
52
+ padding = (kernel_size // 2) * dilation
53
+ self.shift = True
54
+ else:
55
+ padding = ((kernel_size - 1) // 2) * dilation
56
+ self.shift = False
57
+ self.conv = nn.Conv1d(
58
+ hidden_size,
59
+ hidden_size,
60
+ kernel_size,
61
+ padding=padding,
62
+ dilation=dilation)
63
+
64
+ def forward(self, x):
65
+ """Compute convolution.
66
+
67
+ Args:
68
+ x: input embeddings
69
+ Returns:
70
+ conv_output: convolution results
71
+ """
72
+
73
+ if self.shift:
74
+ return self.conv(x.transpose(1, 2)).transpose(1, 2)[:, 1:]
75
+ else:
76
+ return self.conv(x.transpose(1, 2)).transpose(1, 2)
77
+
78
+
79
+ class MultiheadAttention(nn.Module):
80
+ """Multi-head self-attention layer."""
81
+
82
+ def __init__(self,
83
+ embed_dim,
84
+ num_heads,
85
+ dropout=0.,
86
+ bias=True,
87
+ v_proj=True,
88
+ out_proj=True,
89
+ relative_bias=True):
90
+ """Initialization.
91
+
92
+ Args:
93
+ embed_dim: dimension of input embeddings
94
+ num_heads: number of self-attention heads
95
+ dropout: dropout rate
96
+ bias: bool, indicate whether include bias for linear transformations
97
+ v_proj: bool, indicate whether project inputs to new values
98
+ out_proj: bool, indicate whether project outputs to new values
99
+ relative_bias: bool, indicate whether use a relative position based
100
+ attention bias
101
+ """
102
+
103
+ super(MultiheadAttention, self).__init__()
104
+ self.embed_dim = embed_dim
105
+
106
+ self.num_heads = num_heads
107
+ self.drop = nn.Dropout(dropout)
108
+ self.head_dim = embed_dim // num_heads
109
+ assert self.head_dim * num_heads == self.embed_dim, ("embed_dim must be "
110
+ "divisible by "
111
+ "num_heads")
112
+
113
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
114
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
115
+ if v_proj:
116
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
117
+ else:
118
+ self.v_proj = nn.Identity()
119
+
120
+ if out_proj:
121
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
122
+ else:
123
+ self.out_proj = nn.Identity()
124
+
125
+ if relative_bias:
126
+ self.relative_bias = nn.Parameter(torch.zeros((self.num_heads, 512)))
127
+ else:
128
+ self.relative_bias = None
129
+
130
+ self._reset_parameters()
131
+
132
+ def _reset_parameters(self):
133
+ """Initialize attention parameters."""
134
+
135
+ init.xavier_uniform_(self.q_proj.weight)
136
+ init.constant_(self.q_proj.bias, 0.)
137
+
138
+ init.xavier_uniform_(self.k_proj.weight)
139
+ init.constant_(self.k_proj.bias, 0.)
140
+
141
+ if isinstance(self.v_proj, nn.Linear):
142
+ init.xavier_uniform_(self.v_proj.weight)
143
+ init.constant_(self.v_proj.bias, 0.)
144
+
145
+ if isinstance(self.out_proj, nn.Linear):
146
+ init.xavier_uniform_(self.out_proj.weight)
147
+ init.constant_(self.out_proj.bias, 0.)
148
+
149
+ def forward(self, query, key_padding_mask=None, attn_mask=None):
150
+ """Compute multi-head self-attention.
151
+
152
+ Args:
153
+ query: input embeddings
154
+ key_padding_mask: 3D mask that prevents attention to certain positions
155
+ attn_mask: 3D mask that rescale the attention weight at each position
156
+ Returns:
157
+ attn_output: self-attention output
158
+ """
159
+
160
+ length, bsz, embed_dim = query.size()
161
+ assert embed_dim == self.embed_dim
162
+
163
+ head_dim = embed_dim // self.num_heads
164
+ assert head_dim * self.num_heads == embed_dim, ("embed_dim must be "
165
+ "divisible by num_heads")
166
+ scaling = float(head_dim)**-0.5
167
+
168
+ q = self.q_proj(query)
169
+ k = self.k_proj(query)
170
+ v = self.v_proj(query)
171
+
172
+ q = q * scaling
173
+
174
+ if attn_mask is not None:
175
+ assert list(attn_mask.size()) == [bsz * self.num_heads,
176
+ query.size(0), query.size(0)]
177
+
178
+ q = q.contiguous().view(length, bsz * self.num_heads,
179
+ head_dim).transpose(0, 1)
180
+ k = k.contiguous().view(length, bsz * self.num_heads,
181
+ head_dim).transpose(0, 1)
182
+ v = v.contiguous().view(length, bsz * self.num_heads,
183
+ head_dim).transpose(0, 1)
184
+
185
+ attn_output_weights = torch.bmm(q, k.transpose(1, 2))
186
+ assert list(
187
+ attn_output_weights.size()) == [bsz * self.num_heads, length, length]
188
+
189
+ if self.relative_bias is not None:
190
+ pos = torch.arange(length, device=query.device)
191
+ relative_pos = torch.abs(pos[:, None] - pos[None, :]) + 256
192
+ relative_pos = relative_pos[None, :, :].expand(bsz * self.num_heads, -1,
193
+ -1)
194
+
195
+ relative_bias = self.relative_bias.repeat_interleave(bsz, dim=0)
196
+ relative_bias = relative_bias[:, None, :].expand(-1, length, -1)
197
+ relative_bias = torch.gather(relative_bias, 2, relative_pos)
198
+ attn_output_weights = attn_output_weights + relative_bias
199
+
200
+ if key_padding_mask is not None:
201
+ attn_output_weights = attn_output_weights + key_padding_mask
202
+
203
+ if attn_mask is None:
204
+ attn_output_weights = torch.softmax(attn_output_weights, dim=-1)
205
+ else:
206
+ attn_output_weights = torch.sigmoid(attn_output_weights) * attn_mask
207
+
208
+ attn_output_weights = self.drop(attn_output_weights)
209
+
210
+ attn_output = torch.bmm(attn_output_weights, v)
211
+
212
+ assert list(attn_output.size()) == [bsz * self.num_heads, length, head_dim]
213
+ attn_output = attn_output.transpose(0, 1).contiguous().view(
214
+ length, bsz, embed_dim)
215
+ attn_output = self.out_proj(attn_output)
216
+
217
+ return attn_output
218
+
219
+
220
+ class TransformerLayer(nn.Module):
221
+ """TransformerEncoderLayer is made up of self-attn and feedforward network."""
222
+
223
+ def __init__(self,
224
+ d_model,
225
+ nhead,
226
+ dim_feedforward=2048,
227
+ dropout=0.1,
228
+ dropatt=0.1,
229
+ activation="leakyrelu",
230
+ relative_bias=True):
231
+ """Initialization.
232
+
233
+ Args:
234
+ d_model: dimension of inputs
235
+ nhead: number of self-attention heads
236
+ dim_feedforward: dimension of hidden layer in feedforward layer
237
+ dropout: dropout rate
238
+ dropatt: drop attention rate
239
+ activation: activation function
240
+ relative_bias: bool, indicate whether use a relative position based
241
+ attention bias
242
+ """
243
+
244
+ super(TransformerLayer, self).__init__()
245
+ self.self_attn = MultiheadAttention(
246
+ d_model, nhead, dropout=dropatt, relative_bias=relative_bias)
247
+ # Implementation of Feedforward model
248
+ self.feedforward = nn.Sequential(
249
+ nn.LayerNorm(d_model), nn.Linear(d_model, dim_feedforward),
250
+ _get_activation_fn(activation), nn.Dropout(dropout),
251
+ nn.Linear(dim_feedforward, d_model))
252
+
253
+ self.norm = nn.LayerNorm(d_model)
254
+ self.dropout1 = nn.Dropout(dropout)
255
+ self.dropout2 = nn.Dropout(dropout)
256
+
257
+ self.nhead = nhead
258
+
259
+ def forward(self, src, attn_mask=None, key_padding_mask=None):
260
+ """Pass the input through the encoder layer.
261
+
262
+ Args:
263
+ src: the sequence to the encoder layer (required).
264
+ attn_mask: the mask for the src sequence (optional).
265
+ key_padding_mask: the mask for the src keys per batch (optional).
266
+ Returns:
267
+ src3: the output of transformer layer, share the same shape as src.
268
+ """
269
+ src2 = self.self_attn(
270
+ self.norm(src), attn_mask=attn_mask, key_padding_mask=key_padding_mask)
271
+ src2 = src + self.dropout1(src2)
272
+ src3 = self.feedforward(src2)
273
+ src3 = src2 + self.dropout2(src3)
274
+
275
+ return src3
276
+
277
+
278
+ def cumprod(x, reverse=False, exclusive=False):
279
+ """cumulative product."""
280
+ if reverse:
281
+ x = x.flip([-1])
282
+
283
+ if exclusive:
284
+ x = F.pad(x[:, :, :-1], (1, 0), value=1)
285
+
286
+ cx = x.cumprod(-1)
287
+
288
+ if reverse:
289
+ cx = cx.flip([-1])
290
+ return cx
291
+
292
+ def cumsum(x, reverse=False, exclusive=False):
293
+ """cumulative sum."""
294
+ bsz, _, length = x.size()
295
+ device = x.device
296
+ if reverse:
297
+ if exclusive:
298
+ w = torch.ones([bsz, length, length], device=device).tril(-1)
299
+ else:
300
+ w = torch.ones([bsz, length, length], device=device).tril(0)
301
+ cx = torch.bmm(x, w)
302
+ else:
303
+ if exclusive:
304
+ w = torch.ones([bsz, length, length], device=device).triu(1)
305
+ else:
306
+ w = torch.ones([bsz, length, length], device=device).triu(0)
307
+ cx = torch.bmm(x, w)
308
+ return cx
309
+
310
+ def cummin(x, reverse=False, exclusive=False, max_value=1e9):
311
+ """cumulative min."""
312
+ if reverse:
313
+ if exclusive:
314
+ x = F.pad(x[:, :, 1:], (0, 1), value=max_value)
315
+ x = x.flip([-1]).cummin(-1)[0].flip([-1])
316
+ else:
317
+ if exclusive:
318
+ x = F.pad(x[:, :, :-1], (1, 0), value=max_value)
319
+ x = x.cummin(-1)[0]
320
+ return x
321
+
322
+ class Transformer(nn.Module):
323
+ """Transformer model."""
324
+
325
+ def __init__(self,
326
+ hidden_size,
327
+ nlayers,
328
+ ntokens,
329
+ nhead=8,
330
+ dropout=0.1,
331
+ dropatt=0.1,
332
+ relative_bias=True,
333
+ pos_emb=False,
334
+ pad=0):
335
+ """Initialization.
336
+
337
+ Args:
338
+ hidden_size: dimension of inputs and hidden states
339
+ nlayers: number of layers
340
+ ntokens: number of output categories
341
+ nhead: number of self-attention heads
342
+ dropout: dropout rate
343
+ dropatt: drop attention rate
344
+ relative_bias: bool, indicate whether use a relative position based
345
+ attention bias
346
+ pos_emb: bool, indicate whether use a learnable positional embedding
347
+ pad: pad token index
348
+ """
349
+
350
+ super(Transformer, self).__init__()
351
+
352
+ self.drop = nn.Dropout(dropout)
353
+
354
+ self.emb = nn.Embedding(ntokens, hidden_size)
355
+ if pos_emb:
356
+ self.pos_emb = nn.Embedding(500, hidden_size)
357
+
358
+ self.layers = nn.ModuleList([
359
+ TransformerLayer(hidden_size, nhead, hidden_size * 4, dropout,
360
+ dropatt=dropatt, relative_bias=relative_bias)
361
+ for _ in range(nlayers)])
362
+
363
+ self.norm = nn.LayerNorm(hidden_size)
364
+
365
+ self.output_layer = nn.Linear(hidden_size, ntokens)
366
+ self.output_layer.weight = self.emb.weight
367
+
368
+ self.init_weights()
369
+
370
+ self.nlayers = nlayers
371
+ self.nhead = nhead
372
+ self.ntokens = ntokens
373
+ self.hidden_size = hidden_size
374
+ self.pad = pad
375
+
376
+ def init_weights(self):
377
+ """Initialize token embedding and output bias."""
378
+ initrange = 0.1
379
+ self.emb.weight.data.uniform_(-initrange, initrange)
380
+ if hasattr(self, 'pos_emb'):
381
+ self.pos_emb.weight.data.uniform_(-initrange, initrange)
382
+ self.output_layer.bias.data.fill_(0)
383
+
384
+ def visibility(self, x, device):
385
+ """Mask pad tokens."""
386
+ visibility = (x != self.pad).float()
387
+ visibility = visibility[:, None, :].expand(-1, x.size(1), -1)
388
+ visibility = torch.repeat_interleave(visibility, self.nhead, dim=0)
389
+ return visibility.log()
390
+
391
+ def encode(self, x, pos):
392
+ """Standard transformer encode process."""
393
+ h = self.emb(x)
394
+ if hasattr(self, 'pos_emb'):
395
+ h = h + self.pos_emb(pos)
396
+ h_list = []
397
+ visibility = self.visibility(x, x.device)
398
+
399
+ for i in range(self.nlayers):
400
+ h_list.append(h)
401
+ h = self.layers[i](
402
+ h.transpose(0, 1), key_padding_mask=visibility).transpose(0, 1)
403
+
404
+ output = h
405
+ h_array = torch.stack(h_list, dim=2)
406
+
407
+ return output, h_array
408
+
409
+ def forward(self, x, pos):
410
+ """Pass the input through the encoder layer.
411
+
412
+ Args:
413
+ x: input tokens (required).
414
+ pos: position for each token (optional).
415
+ Returns:
416
+ output: probability distributions for missing tokens.
417
+ state_dict: parsing results and raw output
418
+ """
419
+
420
+ batch_size, length = x.size()
421
+
422
+ raw_output, _ = self.encode(x, pos)
423
+ raw_output = self.norm(raw_output)
424
+ raw_output = self.drop(raw_output)
425
+
426
+ output = self.output_layer(raw_output)
427
+ return output.view(batch_size * length, -1), {'raw_output': raw_output,}
428
+
429
+ class StructFormer(Transformer):
430
+ """StructFormer model."""
431
+
432
+ def __init__(self,
433
+ hidden_size,
434
+ nlayers,
435
+ ntokens,
436
+ nhead=8,
437
+ dropout=0.1,
438
+ dropatt=0.1,
439
+ relative_bias=False,
440
+ pos_emb=False,
441
+ pad=0,
442
+ n_parser_layers=4,
443
+ conv_size=9,
444
+ relations=('head', 'child'),
445
+ weight_act='softmax'):
446
+ """Initialization.
447
+
448
+ Args:
449
+ hidden_size: dimension of inputs and hidden states
450
+ nlayers: number of layers
451
+ ntokens: number of output categories
452
+ nhead: number of self-attention heads
453
+ dropout: dropout rate
454
+ dropatt: drop attention rate
455
+ relative_bias: bool, indicate whether use a relative position based
456
+ attention bias
457
+ pos_emb: bool, indicate whether use a learnable positional embedding
458
+ pad: pad token index
459
+ n_parser_layers: number of parsing layers
460
+ conv_size: convolution kernel size for parser
461
+ relations: relations that are used to compute self attention
462
+ weight_act: relations distribution activation function
463
+ """
464
+
465
+ super(StructFormer, self).__init__(
466
+ hidden_size,
467
+ nlayers,
468
+ ntokens,
469
+ nhead=nhead,
470
+ dropout=dropout,
471
+ dropatt=dropatt,
472
+ relative_bias=relative_bias,
473
+ pos_emb=pos_emb,
474
+ pad=pad)
475
+
476
+ self.parser_layers = nn.ModuleList([
477
+ nn.Sequential(Conv1d(hidden_size, conv_size),
478
+ nn.LayerNorm(hidden_size, elementwise_affine=False),
479
+ nn.Tanh()) for i in range(n_parser_layers)])
480
+
481
+ self.distance_ff = nn.Sequential(
482
+ Conv1d(hidden_size, 2),
483
+ nn.LayerNorm(hidden_size, elementwise_affine=False), nn.Tanh(),
484
+ nn.Linear(hidden_size, 1))
485
+
486
+ self.height_ff = nn.Sequential(
487
+ nn.Linear(hidden_size, hidden_size),
488
+ nn.LayerNorm(hidden_size, elementwise_affine=False), nn.Tanh(),
489
+ nn.Linear(hidden_size, 1))
490
+
491
+ n_rel = len(relations)
492
+ self._rel_weight = nn.Parameter(torch.zeros((nlayers, nhead, n_rel)))
493
+ self._rel_weight.data.normal_(0, 0.1)
494
+
495
+ self._scaler = nn.Parameter(torch.zeros(2))
496
+
497
+ self.n_parse_layers = n_parser_layers
498
+ self.weight_act = weight_act
499
+ self.relations = relations
500
+
501
+ @property
502
+ def scaler(self):
503
+ return self._scaler.exp()
504
+
505
+ @property
506
+ def rel_weight(self):
507
+ if self.weight_act == 'sigmoid':
508
+ return torch.sigmoid(self._rel_weight)
509
+ elif self.weight_act == 'softmax':
510
+ return torch.softmax(self._rel_weight, dim=-1)
511
+
512
+ def parse(self, x, pos):
513
+ """Parse input sentence.
514
+
515
+ Args:
516
+ x: input tokens (required).
517
+ pos: position for each token (optional).
518
+ Returns:
519
+ distance: syntactic distance
520
+ height: syntactic height
521
+ """
522
+
523
+ mask = (x != self.pad)
524
+ mask_shifted = F.pad(mask[:, 1:], (0, 1), value=0)
525
+
526
+ h = self.emb(x)
527
+ for i in range(self.n_parse_layers):
528
+ h = h.masked_fill(~mask[:, :, None], 0)
529
+ h = self.parser_layers[i](h)
530
+
531
+ height = self.height_ff(h).squeeze(-1)
532
+ height.masked_fill_(~mask, -1e9)
533
+
534
+ distance = self.distance_ff(h).squeeze(-1)
535
+ distance.masked_fill_(~mask_shifted, 1e9)
536
+
537
+ # Calbrating the distance and height to the same level
538
+ length = distance.size(1)
539
+ height_max = height[:, None, :].expand(-1, length, -1)
540
+ height_max = torch.cummax(
541
+ height_max.triu(0) - torch.ones_like(height_max).tril(-1) * 1e9,
542
+ dim=-1)[0].triu(0)
543
+
544
+ margin_left = torch.relu(
545
+ F.pad(distance[:, :-1, None], (0, 0, 1, 0), value=1e9) - height_max)
546
+ margin_right = torch.relu(distance[:, None, :] - height_max)
547
+ margin = torch.where(margin_left > margin_right, margin_right,
548
+ margin_left).triu(0)
549
+
550
+ margin_mask = torch.stack([mask_shifted] + [mask] * (length - 1), dim=1)
551
+ margin.masked_fill_(~margin_mask, 0)
552
+ margin = margin.max()
553
+
554
+ distance = distance - margin
555
+
556
+ return distance, height
557
+
558
+ def compute_block(self, distance, height):
559
+ """Compute constituents from distance and height."""
560
+
561
+ beta_logits = (distance[:, None, :] - height[:, :, None]) * self.scaler[0]
562
+
563
+ gamma = torch.sigmoid(-beta_logits)
564
+ ones = torch.ones_like(gamma)
565
+
566
+ block_mask_left = cummin(
567
+ gamma.tril(-1) + ones.triu(0), reverse=True, max_value=1)
568
+ block_mask_left = block_mask_left - F.pad(
569
+ block_mask_left[:, :, :-1], (1, 0), value=0)
570
+ block_mask_left.tril_(0)
571
+
572
+ block_mask_right = cummin(
573
+ gamma.triu(0) + ones.tril(-1), exclusive=True, max_value=1)
574
+ block_mask_right = block_mask_right - F.pad(
575
+ block_mask_right[:, :, 1:], (0, 1), value=0)
576
+ block_mask_right.triu_(0)
577
+
578
+ block_p = block_mask_left[:, :, :, None] * block_mask_right[:, :, None, :]
579
+ block = cumsum(block_mask_left).tril(0) + cumsum(
580
+ block_mask_right, reverse=True).triu(1)
581
+
582
+ return block_p, block
583
+
584
+ def compute_head(self, height):
585
+ """Estimate head for each constituent."""
586
+
587
+ _, length = height.size()
588
+ head_logits = height * self.scaler[1]
589
+ index = torch.arange(length, device=height.device)
590
+
591
+ mask = (index[:, None, None] <= index[None, None, :]) * (
592
+ index[None, None, :] <= index[None, :, None])
593
+ head_logits = head_logits[:, None, None, :].repeat(1, length, length, 1)
594
+ head_logits.masked_fill_(~mask[None, :, :, :], -1e9)
595
+
596
+ head_p = torch.softmax(head_logits, dim=-1)
597
+
598
+ return head_p
599
+
600
+ def generate_mask(self, x, distance, height):
601
+ """Compute head and cibling distribution for each token."""
602
+
603
+ bsz, length = x.size()
604
+
605
+ eye = torch.eye(length, device=x.device, dtype=torch.bool)
606
+ eye = eye[None, :, :].expand((bsz, -1, -1))
607
+
608
+ block_p, block = self.compute_block(distance, height)
609
+ head_p = self.compute_head(height)
610
+ head = torch.einsum('blij,bijh->blh', block_p, head_p)
611
+ head = head.masked_fill(eye, 0)
612
+ child = head.transpose(1, 2)
613
+ cibling = torch.bmm(head, child).masked_fill(eye, 0)
614
+
615
+ rel_list = []
616
+ if 'head' in self.relations:
617
+ rel_list.append(head)
618
+ if 'child' in self.relations:
619
+ rel_list.append(child)
620
+ if 'cibling' in self.relations:
621
+ rel_list.append(cibling)
622
+
623
+ rel = torch.stack(rel_list, dim=1)
624
+
625
+ rel_weight = self.rel_weight
626
+
627
+ dep = torch.einsum('lhr,brij->lbhij', rel_weight, rel)
628
+ att_mask = dep.reshape(self.nlayers, bsz * self.nhead, length, length)
629
+
630
+ return att_mask, cibling, head, block
631
+
632
+ def encode(self, x, pos, att_mask):
633
+ """Structformer encoding process."""
634
+
635
+ visibility = self.visibility(x, x.device)
636
+ h = self.emb(x)
637
+ if hasattr(self, 'pos_emb'):
638
+ assert pos.max() < 500
639
+ h = h + self.pos_emb(pos)
640
+ for i in range(self.nlayers):
641
+ h = self.layers[i](
642
+ h.transpose(0, 1), attn_mask=att_mask[i],
643
+ key_padding_mask=visibility).transpose(0, 1)
644
+ return h
645
+
646
+ def forward(self, x, pos):
647
+ """Pass the input through the encoder layer.
648
+
649
+ Args:
650
+ x: input tokens (required).
651
+ pos: position for each token (optional).
652
+ Returns:
653
+ output: probability distributions for missing tokens.
654
+ state_dict: parsing results and raw output
655
+ """
656
+
657
+ batch_size, length = x.size()
658
+
659
+ distance, height = self.parse(x, pos)
660
+ att_mask, cibling, head, block = self.generate_mask(x, distance, height)
661
+
662
+ raw_output = self.encode(x, pos, att_mask)
663
+ raw_output = self.norm(raw_output)
664
+ raw_output = self.drop(raw_output)
665
+
666
+ output = self.output_layer(raw_output)
667
+
668
+ return output.view(batch_size * length, -1), \
669
+ {'raw_output': raw_output, 'distance': distance, 'height': height,
670
+ 'cibling': cibling, 'head': head, 'block': block}
671
+
672
+
673
+ ##########################################
674
+ # Clasication Head For BabyLM Evaluation Tasks
675
+ ##########################################
676
+ class ClassificationHead(nn.Module):
677
+ """Head for sentence-level classification tasks."""
678
+ def __init__(self, config):
679
+ super(ClassificationHead, self).__init__()
680
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
681
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
682
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
683
+
684
+ def forward(self, features, **kwargs):
685
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
686
+ x = self.dropout(x)
687
+ x = self.dense(x)
688
+ x = torch.tanh(x)
689
+ x = self.dropout(x)
690
+ x = self.out_proj(x)
691
+ return x
692
+
693
+ ##########################################
694
+ # HuggingFace Config
695
+ ##########################################
696
+ class StructFormerConfig(PretrainedConfig):
697
+ model_type = "structformer"
698
+
699
+ def __init__(
700
+ self,
701
+ hidden_size=512,
702
+ nlayers=8,
703
+ ntokens=10_000,
704
+ nhead=8,
705
+ dropout=0.1,
706
+ dropatt=0.1,
707
+ relative_bias=False,
708
+ pos_emb=False,
709
+ pad=0,
710
+ n_parser_layers=4,
711
+ conv_size=9,
712
+ relations=('head', 'child'),
713
+ weight_act='softmax',
714
+ num_labels=1,
715
+ hidden_dropout_prob=0.1,
716
+ initializer_range=0.02,
717
+ **kwargs,
718
+ ):
719
+ self.hidden_size = hidden_size
720
+ self.nlayers = nlayers
721
+ self.ntokens = ntokens
722
+ self.nhead = nhead
723
+ self.dropout = dropout
724
+ self.dropatt = dropatt
725
+ self.relative_bias = relative_bias
726
+ self.pos_emb = pos_emb
727
+ self.pad = pad
728
+ self.n_parser_layers = n_parser_layers
729
+ self.conv_size = conv_size
730
+ self.relations = relations
731
+ self.weight_act = weight_act
732
+ self.num_labels = num_labels
733
+ self.hidden_dropout_prob = hidden_dropout_prob
734
+ self.initializer_range=initializer_range
735
+ super().__init__(**kwargs)
736
+
737
+ ##########################################
738
+ # HuggingFace Model
739
+ ##########################################
740
+ class StructFormerModel(PreTrainedModel):
741
+ config_class = StructFormerConfig
742
+
743
+ def __init__(self, config):
744
+ super().__init__(config)
745
+ self.model = StructFormer(
746
+ hidden_size=config.hidden_size,
747
+ nlayers=config.nlayers,
748
+ ntokens=config.ntokens,
749
+ nhead=config.nhead,
750
+ dropout=config.dropout,
751
+ dropatt=config.dropatt,
752
+ relative_bias=config.relative_bias,
753
+ pos_emb=config.pos_emb,
754
+ pad=config.pad,
755
+ n_parser_layers=config.n_parser_layers,
756
+ conv_size=config.conv_size,
757
+ relations=config.relations,
758
+ weight_act=config.weight_act
759
+ )
760
+ self.config = config
761
+
762
+ def parse(self, input_ids, **kwargs):
763
+ x = input_ids
764
+ batch_size, length = x.size()
765
+ pos = kwargs['position_ids'] if 'position_ids' in kwargs.keys() else torch.arange(length, device=x.device).expand(batch_size, length)
766
+
767
+ sf_output = self.model(x, pos)
768
+
769
+ return sf_output[1]
770
+
771
+ def forward(self, input_ids, labels=None, **kwargs):
772
+ x = input_ids
773
+ batch_size, length = x.size()
774
+ pos = kwargs['position_ids'] if 'position_ids' in kwargs.keys() else torch.arange(length, device=x.device).expand(batch_size, length)
775
+
776
+ sf_output = self.model(x, pos)
777
+
778
+ loss = None
779
+ if labels is not None:
780
+ loss_fct = nn.CrossEntropyLoss()
781
+ loss = loss_fct(sf_output[0], labels.reshape(-1))
782
+
783
+ return MaskedLMOutput(
784
+ loss=loss, # shape: 1
785
+ logits=sf_output[0].view(batch_size, length, -1), # shape: (batch_size, length, ntokens)
786
+ hidden_states=None,
787
+ attentions=None
788
+ )
789
+
790
+ class StructFormerModelForSequenceClassification(PreTrainedModel):
791
+ config_class = StructFormerConfig
792
+
793
+ def __init__(self, config):
794
+ super().__init__(config)
795
+ self.model = StructFormer(
796
+ hidden_size=config.hidden_size,
797
+ nlayers=config.nlayers,
798
+ ntokens=config.ntokens,
799
+ nhead=config.nhead,
800
+ dropout=config.dropout,
801
+ dropatt=config.dropatt,
802
+ relative_bias=config.relative_bias,
803
+ pos_emb=config.pos_emb,
804
+ pad=config.pad,
805
+ n_parser_layers=config.n_parser_layers,
806
+ conv_size=config.conv_size,
807
+ relations=config.relations,
808
+ weight_act=config.weight_act
809
+ )
810
+ self.config = config
811
+ self.num_labels = config.num_labels
812
+ self.model.classifier = ClassificationHead(config)
813
+
814
+ def _init_weights(self, module):
815
+ """Initialize the weights"""
816
+ if isinstance(module, nn.Linear):
817
+ # Slightly different from the TF version which uses truncated_normal for initialization
818
+ # cf https://github.com/pytorch/pytorch/pull/5617
819
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
820
+ if module.bias is not None:
821
+ module.bias.data.zero_()
822
+ elif isinstance(module, nn.Embedding):
823
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
824
+ if module.padding_idx is not None:
825
+ module.weight.data[module.padding_idx].zero_()
826
+ elif isinstance(module, nn.LayerNorm):
827
+ if module.bias is not None:
828
+ module.bias.data.zero_()
829
+ module.weight.data.fill_(1.0)
830
+
831
+ def forward(self, input_ids, labels=None, **kwargs):
832
+ x = input_ids
833
+ batch_size, length = x.size()
834
+ pos = kwargs['position_ids'] if 'position_ids' in kwargs.keys() else torch.arange(length, device=x.device).expand(batch_size, length)
835
+
836
+ sf_output = self.model(x, pos)
837
+
838
+ logits = self.model.classifier(sf_output[1]['raw_output'])
839
+ loss = None
840
+ if labels is not None:
841
+ if self.config.problem_type is None:
842
+ if self.num_labels == 1:
843
+ self.config.problem_type = "regression"
844
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
845
+ self.config.problem_type = "single_label_classification"
846
+ else:
847
+ self.config.problem_type = "multi_label_classification"
848
+
849
+ if self.config.problem_type == "regression":
850
+ loss_fct = nn.MSELoss()
851
+ if self.num_labels == 1:
852
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
853
+ else:
854
+ loss = loss_fct(logits, labels)
855
+ elif self.config.problem_type == "single_label_classification":
856
+ loss_fct = nn.CrossEntropyLoss()
857
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
858
+ elif self.config.problem_type == "multi_label_classification":
859
+ loss_fct = nn.BCEWithLogitsLoss()
860
+ loss = loss_fct(logits, labels)
861
+
862
+ return SequenceClassifierOutput(
863
+ loss=loss,
864
+ logits=logits,
865
+ hidden_states=None,
866
+ attentions=None,
867
+ )
finetune/boolq/tokenizer_config.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "bos_token": {
4
+ "__type": "AddedToken",
5
+ "content": "<s>",
6
+ "lstrip": false,
7
+ "normalized": true,
8
+ "rstrip": false,
9
+ "single_word": false
10
+ },
11
+ "cls_token": {
12
+ "__type": "AddedToken",
13
+ "content": "<s>",
14
+ "lstrip": false,
15
+ "normalized": true,
16
+ "rstrip": false,
17
+ "single_word": false
18
+ },
19
+ "eos_token": {
20
+ "__type": "AddedToken",
21
+ "content": "</s>",
22
+ "lstrip": false,
23
+ "normalized": true,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ },
27
+ "errors": "replace",
28
+ "mask_token": {
29
+ "__type": "AddedToken",
30
+ "content": "<mask>",
31
+ "lstrip": true,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false
35
+ },
36
+ "model_max_length": 512,
37
+ "name_or_path": "omarmomen/sf_babylm_1",
38
+ "pad_token": {
39
+ "__type": "AddedToken",
40
+ "content": "<pad>",
41
+ "lstrip": false,
42
+ "normalized": true,
43
+ "rstrip": false,
44
+ "single_word": false
45
+ },
46
+ "sep_token": {
47
+ "__type": "AddedToken",
48
+ "content": "</s>",
49
+ "lstrip": false,
50
+ "normalized": true,
51
+ "rstrip": false,
52
+ "single_word": false
53
+ },
54
+ "special_tokens_map_file": null,
55
+ "tokenizer_class": "RobertaTokenizer",
56
+ "trim_offsets": true,
57
+ "unk_token": {
58
+ "__type": "AddedToken",
59
+ "content": "<unk>",
60
+ "lstrip": false,
61
+ "normalized": true,
62
+ "rstrip": false,
63
+ "single_word": false
64
+ }
65
+ }
finetune/boolq/train_results.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 10.0,
3
+ "train_loss": 0.3263397216796875,
4
+ "train_runtime": 70.9595,
5
+ "train_samples": 2072,
6
+ "train_samples_per_second": 291.998,
7
+ "train_steps_per_second": 4.651
8
+ }
finetune/boolq/trainer_state.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": 0.7282728272827282,
3
+ "best_model_checkpoint": "omarmomen/sf_babylm_1/finetune/boolq/checkpoint-200",
4
+ "epoch": 10.0,
5
+ "global_step": 330,
6
+ "is_hyper_param_search": false,
7
+ "is_local_process_zero": true,
8
+ "is_world_process_zero": true,
9
+ "log_history": [
10
+ {
11
+ "epoch": 6.06,
12
+ "eval_accuracy": 0.658367931842804,
13
+ "eval_f1": 0.7282728272827282,
14
+ "eval_loss": 0.9740044474601746,
15
+ "eval_mcc": 0.27328046278245693,
16
+ "eval_runtime": 1.2669,
17
+ "eval_samples_per_second": 570.67,
18
+ "eval_steps_per_second": 71.827,
19
+ "step": 200
20
+ },
21
+ {
22
+ "epoch": 10.0,
23
+ "step": 330,
24
+ "total_flos": 530980689469440.0,
25
+ "train_loss": 0.3263397216796875,
26
+ "train_runtime": 70.9595,
27
+ "train_samples_per_second": 291.998,
28
+ "train_steps_per_second": 4.651
29
+ }
30
+ ],
31
+ "max_steps": 330,
32
+ "num_train_epochs": 10,
33
+ "total_flos": 530980689469440.0,
34
+ "trial_name": null,
35
+ "trial_params": null
36
+ }
finetune/boolq/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:553f78e16a096fe90d36b0a7936e92787a1172a9f02cf4e4611e107248227ef4
3
+ size 3960
finetune/boolq/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
finetune/cola/all_results.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 10.0,
3
+ "eval_accuracy": 0.7036309838294983,
4
+ "eval_f1": 0.8219339622641509,
5
+ "eval_loss": 0.6300716400146484,
6
+ "eval_mcc": 0.13076987235140602,
7
+ "eval_runtime": 1.7861,
8
+ "eval_samples": 1019,
9
+ "eval_samples_per_second": 570.517,
10
+ "eval_steps_per_second": 71.665,
11
+ "train_loss": 0.3184558808803558,
12
+ "train_runtime": 219.0841,
13
+ "train_samples": 8164,
14
+ "train_samples_per_second": 372.642,
15
+ "train_steps_per_second": 5.843
16
+ }
finetune/cola/checkpoint-200/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "omarmomen/sf_babylm_1",
3
+ "architectures": [
4
+ "StructFormerModelForSequenceClassification"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "structformer.StructFormerConfig",
8
+ "AutoModelForMaskedLM": "structformer.StructFormerModel",
9
+ "AutoModelForSequenceClassification": "structformer.StructFormerModelForSequenceClassification"
10
+ },
11
+ "conv_size": 9,
12
+ "dropatt": 0.1,
13
+ "dropout": 0.1,
14
+ "hidden_dropout_prob": 0.1,
15
+ "hidden_size": 512,
16
+ "id2label": {
17
+ "0": 0,
18
+ "1": 1
19
+ },
20
+ "initializer_range": 0.02,
21
+ "label2id": {
22
+ "0": 0,
23
+ "1": 1
24
+ },
25
+ "model_type": "structformer",
26
+ "n_parser_layers": 3,
27
+ "nhead": 8,
28
+ "nlayers": 8,
29
+ "ntokens": 16000,
30
+ "pad": 1,
31
+ "pos_emb": true,
32
+ "problem_type": "single_label_classification",
33
+ "relations": [
34
+ "head",
35
+ "child"
36
+ ],
37
+ "relative_bias": false,
38
+ "torch_dtype": "float32",
39
+ "transformers_version": "4.26.1",
40
+ "weight_act": "softmax"
41
+ }
finetune/cola/checkpoint-200/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
finetune/cola/checkpoint-200/optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:64479433f30cd6e1151d4bc028baf56e84cd5d91db9e9a98e4b4a26a4d9f2dd7
3
+ size 334487930
finetune/cola/checkpoint-200/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:782e41676fcfa55bd9f10569a44c812fc36f983ee47f32bd0cafdee7d732ee83
3
+ size 167313902
finetune/cola/checkpoint-200/rng_state.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dcdca2997df87a0fc6c3a6ebc025ec0c13497f4dd53314621d65b6268c45356d
3
+ size 14244
finetune/cola/checkpoint-200/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79d27acb67b7f4c7f14c70b0036e640a0cdc532e992a5af9432f781d3c7ad02e
3
+ size 1064
finetune/cola/checkpoint-200/special_tokens_map.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<s>",
3
+ "cls_token": "<s>",
4
+ "eos_token": "</s>",
5
+ "mask_token": {
6
+ "content": "<mask>",
7
+ "lstrip": true,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "pad_token": "<pad>",
13
+ "sep_token": "</s>",
14
+ "unk_token": "<unk>"
15
+ }
finetune/cola/checkpoint-200/structformer.py ADDED
@@ -0,0 +1,867 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Google Research Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """StructFormer and transformer model."""
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from torch.nn import init
22
+ from transformers import PretrainedConfig, PreTrainedModel
23
+ from transformers.modeling_outputs import MaskedLMOutput, SequenceClassifierOutput
24
+
25
+ def _get_activation_fn(activation):
26
+ """Get specified activation function."""
27
+ if activation == "relu":
28
+ return nn.ReLU()
29
+ elif activation == "gelu":
30
+ return nn.GELU()
31
+ elif activation == "leakyrelu":
32
+ return nn.LeakyReLU()
33
+
34
+ raise RuntimeError(
35
+ "activation should be relu/gelu, not {}".format(activation))
36
+
37
+
38
+ class Conv1d(nn.Module):
39
+ """1D convolution layer."""
40
+
41
+ def __init__(self, hidden_size, kernel_size, dilation=1):
42
+ """Initialization.
43
+
44
+ Args:
45
+ hidden_size: dimension of input embeddings
46
+ kernel_size: convolution kernel size
47
+ dilation: the spacing between the kernel points
48
+ """
49
+ super(Conv1d, self).__init__()
50
+
51
+ if kernel_size % 2 == 0:
52
+ padding = (kernel_size // 2) * dilation
53
+ self.shift = True
54
+ else:
55
+ padding = ((kernel_size - 1) // 2) * dilation
56
+ self.shift = False
57
+ self.conv = nn.Conv1d(
58
+ hidden_size,
59
+ hidden_size,
60
+ kernel_size,
61
+ padding=padding,
62
+ dilation=dilation)
63
+
64
+ def forward(self, x):
65
+ """Compute convolution.
66
+
67
+ Args:
68
+ x: input embeddings
69
+ Returns:
70
+ conv_output: convolution results
71
+ """
72
+
73
+ if self.shift:
74
+ return self.conv(x.transpose(1, 2)).transpose(1, 2)[:, 1:]
75
+ else:
76
+ return self.conv(x.transpose(1, 2)).transpose(1, 2)
77
+
78
+
79
+ class MultiheadAttention(nn.Module):
80
+ """Multi-head self-attention layer."""
81
+
82
+ def __init__(self,
83
+ embed_dim,
84
+ num_heads,
85
+ dropout=0.,
86
+ bias=True,
87
+ v_proj=True,
88
+ out_proj=True,
89
+ relative_bias=True):
90
+ """Initialization.
91
+
92
+ Args:
93
+ embed_dim: dimension of input embeddings
94
+ num_heads: number of self-attention heads
95
+ dropout: dropout rate
96
+ bias: bool, indicate whether include bias for linear transformations
97
+ v_proj: bool, indicate whether project inputs to new values
98
+ out_proj: bool, indicate whether project outputs to new values
99
+ relative_bias: bool, indicate whether use a relative position based
100
+ attention bias
101
+ """
102
+
103
+ super(MultiheadAttention, self).__init__()
104
+ self.embed_dim = embed_dim
105
+
106
+ self.num_heads = num_heads
107
+ self.drop = nn.Dropout(dropout)
108
+ self.head_dim = embed_dim // num_heads
109
+ assert self.head_dim * num_heads == self.embed_dim, ("embed_dim must be "
110
+ "divisible by "
111
+ "num_heads")
112
+
113
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
114
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
115
+ if v_proj:
116
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
117
+ else:
118
+ self.v_proj = nn.Identity()
119
+
120
+ if out_proj:
121
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
122
+ else:
123
+ self.out_proj = nn.Identity()
124
+
125
+ if relative_bias:
126
+ self.relative_bias = nn.Parameter(torch.zeros((self.num_heads, 512)))
127
+ else:
128
+ self.relative_bias = None
129
+
130
+ self._reset_parameters()
131
+
132
+ def _reset_parameters(self):
133
+ """Initialize attention parameters."""
134
+
135
+ init.xavier_uniform_(self.q_proj.weight)
136
+ init.constant_(self.q_proj.bias, 0.)
137
+
138
+ init.xavier_uniform_(self.k_proj.weight)
139
+ init.constant_(self.k_proj.bias, 0.)
140
+
141
+ if isinstance(self.v_proj, nn.Linear):
142
+ init.xavier_uniform_(self.v_proj.weight)
143
+ init.constant_(self.v_proj.bias, 0.)
144
+
145
+ if isinstance(self.out_proj, nn.Linear):
146
+ init.xavier_uniform_(self.out_proj.weight)
147
+ init.constant_(self.out_proj.bias, 0.)
148
+
149
+ def forward(self, query, key_padding_mask=None, attn_mask=None):
150
+ """Compute multi-head self-attention.
151
+
152
+ Args:
153
+ query: input embeddings
154
+ key_padding_mask: 3D mask that prevents attention to certain positions
155
+ attn_mask: 3D mask that rescale the attention weight at each position
156
+ Returns:
157
+ attn_output: self-attention output
158
+ """
159
+
160
+ length, bsz, embed_dim = query.size()
161
+ assert embed_dim == self.embed_dim
162
+
163
+ head_dim = embed_dim // self.num_heads
164
+ assert head_dim * self.num_heads == embed_dim, ("embed_dim must be "
165
+ "divisible by num_heads")
166
+ scaling = float(head_dim)**-0.5
167
+
168
+ q = self.q_proj(query)
169
+ k = self.k_proj(query)
170
+ v = self.v_proj(query)
171
+
172
+ q = q * scaling
173
+
174
+ if attn_mask is not None:
175
+ assert list(attn_mask.size()) == [bsz * self.num_heads,
176
+ query.size(0), query.size(0)]
177
+
178
+ q = q.contiguous().view(length, bsz * self.num_heads,
179
+ head_dim).transpose(0, 1)
180
+ k = k.contiguous().view(length, bsz * self.num_heads,
181
+ head_dim).transpose(0, 1)
182
+ v = v.contiguous().view(length, bsz * self.num_heads,
183
+ head_dim).transpose(0, 1)
184
+
185
+ attn_output_weights = torch.bmm(q, k.transpose(1, 2))
186
+ assert list(
187
+ attn_output_weights.size()) == [bsz * self.num_heads, length, length]
188
+
189
+ if self.relative_bias is not None:
190
+ pos = torch.arange(length, device=query.device)
191
+ relative_pos = torch.abs(pos[:, None] - pos[None, :]) + 256
192
+ relative_pos = relative_pos[None, :, :].expand(bsz * self.num_heads, -1,
193
+ -1)
194
+
195
+ relative_bias = self.relative_bias.repeat_interleave(bsz, dim=0)
196
+ relative_bias = relative_bias[:, None, :].expand(-1, length, -1)
197
+ relative_bias = torch.gather(relative_bias, 2, relative_pos)
198
+ attn_output_weights = attn_output_weights + relative_bias
199
+
200
+ if key_padding_mask is not None:
201
+ attn_output_weights = attn_output_weights + key_padding_mask
202
+
203
+ if attn_mask is None:
204
+ attn_output_weights = torch.softmax(attn_output_weights, dim=-1)
205
+ else:
206
+ attn_output_weights = torch.sigmoid(attn_output_weights) * attn_mask
207
+
208
+ attn_output_weights = self.drop(attn_output_weights)
209
+
210
+ attn_output = torch.bmm(attn_output_weights, v)
211
+
212
+ assert list(attn_output.size()) == [bsz * self.num_heads, length, head_dim]
213
+ attn_output = attn_output.transpose(0, 1).contiguous().view(
214
+ length, bsz, embed_dim)
215
+ attn_output = self.out_proj(attn_output)
216
+
217
+ return attn_output
218
+
219
+
220
+ class TransformerLayer(nn.Module):
221
+ """TransformerEncoderLayer is made up of self-attn and feedforward network."""
222
+
223
+ def __init__(self,
224
+ d_model,
225
+ nhead,
226
+ dim_feedforward=2048,
227
+ dropout=0.1,
228
+ dropatt=0.1,
229
+ activation="leakyrelu",
230
+ relative_bias=True):
231
+ """Initialization.
232
+
233
+ Args:
234
+ d_model: dimension of inputs
235
+ nhead: number of self-attention heads
236
+ dim_feedforward: dimension of hidden layer in feedforward layer
237
+ dropout: dropout rate
238
+ dropatt: drop attention rate
239
+ activation: activation function
240
+ relative_bias: bool, indicate whether use a relative position based
241
+ attention bias
242
+ """
243
+
244
+ super(TransformerLayer, self).__init__()
245
+ self.self_attn = MultiheadAttention(
246
+ d_model, nhead, dropout=dropatt, relative_bias=relative_bias)
247
+ # Implementation of Feedforward model
248
+ self.feedforward = nn.Sequential(
249
+ nn.LayerNorm(d_model), nn.Linear(d_model, dim_feedforward),
250
+ _get_activation_fn(activation), nn.Dropout(dropout),
251
+ nn.Linear(dim_feedforward, d_model))
252
+
253
+ self.norm = nn.LayerNorm(d_model)
254
+ self.dropout1 = nn.Dropout(dropout)
255
+ self.dropout2 = nn.Dropout(dropout)
256
+
257
+ self.nhead = nhead
258
+
259
+ def forward(self, src, attn_mask=None, key_padding_mask=None):
260
+ """Pass the input through the encoder layer.
261
+
262
+ Args:
263
+ src: the sequence to the encoder layer (required).
264
+ attn_mask: the mask for the src sequence (optional).
265
+ key_padding_mask: the mask for the src keys per batch (optional).
266
+ Returns:
267
+ src3: the output of transformer layer, share the same shape as src.
268
+ """
269
+ src2 = self.self_attn(
270
+ self.norm(src), attn_mask=attn_mask, key_padding_mask=key_padding_mask)
271
+ src2 = src + self.dropout1(src2)
272
+ src3 = self.feedforward(src2)
273
+ src3 = src2 + self.dropout2(src3)
274
+
275
+ return src3
276
+
277
+
278
+ def cumprod(x, reverse=False, exclusive=False):
279
+ """cumulative product."""
280
+ if reverse:
281
+ x = x.flip([-1])
282
+
283
+ if exclusive:
284
+ x = F.pad(x[:, :, :-1], (1, 0), value=1)
285
+
286
+ cx = x.cumprod(-1)
287
+
288
+ if reverse:
289
+ cx = cx.flip([-1])
290
+ return cx
291
+
292
+ def cumsum(x, reverse=False, exclusive=False):
293
+ """cumulative sum."""
294
+ bsz, _, length = x.size()
295
+ device = x.device
296
+ if reverse:
297
+ if exclusive:
298
+ w = torch.ones([bsz, length, length], device=device).tril(-1)
299
+ else:
300
+ w = torch.ones([bsz, length, length], device=device).tril(0)
301
+ cx = torch.bmm(x, w)
302
+ else:
303
+ if exclusive:
304
+ w = torch.ones([bsz, length, length], device=device).triu(1)
305
+ else:
306
+ w = torch.ones([bsz, length, length], device=device).triu(0)
307
+ cx = torch.bmm(x, w)
308
+ return cx
309
+
310
+ def cummin(x, reverse=False, exclusive=False, max_value=1e9):
311
+ """cumulative min."""
312
+ if reverse:
313
+ if exclusive:
314
+ x = F.pad(x[:, :, 1:], (0, 1), value=max_value)
315
+ x = x.flip([-1]).cummin(-1)[0].flip([-1])
316
+ else:
317
+ if exclusive:
318
+ x = F.pad(x[:, :, :-1], (1, 0), value=max_value)
319
+ x = x.cummin(-1)[0]
320
+ return x
321
+
322
+ class Transformer(nn.Module):
323
+ """Transformer model."""
324
+
325
+ def __init__(self,
326
+ hidden_size,
327
+ nlayers,
328
+ ntokens,
329
+ nhead=8,
330
+ dropout=0.1,
331
+ dropatt=0.1,
332
+ relative_bias=True,
333
+ pos_emb=False,
334
+ pad=0):
335
+ """Initialization.
336
+
337
+ Args:
338
+ hidden_size: dimension of inputs and hidden states
339
+ nlayers: number of layers
340
+ ntokens: number of output categories
341
+ nhead: number of self-attention heads
342
+ dropout: dropout rate
343
+ dropatt: drop attention rate
344
+ relative_bias: bool, indicate whether use a relative position based
345
+ attention bias
346
+ pos_emb: bool, indicate whether use a learnable positional embedding
347
+ pad: pad token index
348
+ """
349
+
350
+ super(Transformer, self).__init__()
351
+
352
+ self.drop = nn.Dropout(dropout)
353
+
354
+ self.emb = nn.Embedding(ntokens, hidden_size)
355
+ if pos_emb:
356
+ self.pos_emb = nn.Embedding(500, hidden_size)
357
+
358
+ self.layers = nn.ModuleList([
359
+ TransformerLayer(hidden_size, nhead, hidden_size * 4, dropout,
360
+ dropatt=dropatt, relative_bias=relative_bias)
361
+ for _ in range(nlayers)])
362
+
363
+ self.norm = nn.LayerNorm(hidden_size)
364
+
365
+ self.output_layer = nn.Linear(hidden_size, ntokens)
366
+ self.output_layer.weight = self.emb.weight
367
+
368
+ self.init_weights()
369
+
370
+ self.nlayers = nlayers
371
+ self.nhead = nhead
372
+ self.ntokens = ntokens
373
+ self.hidden_size = hidden_size
374
+ self.pad = pad
375
+
376
+ def init_weights(self):
377
+ """Initialize token embedding and output bias."""
378
+ initrange = 0.1
379
+ self.emb.weight.data.uniform_(-initrange, initrange)
380
+ if hasattr(self, 'pos_emb'):
381
+ self.pos_emb.weight.data.uniform_(-initrange, initrange)
382
+ self.output_layer.bias.data.fill_(0)
383
+
384
+ def visibility(self, x, device):
385
+ """Mask pad tokens."""
386
+ visibility = (x != self.pad).float()
387
+ visibility = visibility[:, None, :].expand(-1, x.size(1), -1)
388
+ visibility = torch.repeat_interleave(visibility, self.nhead, dim=0)
389
+ return visibility.log()
390
+
391
+ def encode(self, x, pos):
392
+ """Standard transformer encode process."""
393
+ h = self.emb(x)
394
+ if hasattr(self, 'pos_emb'):
395
+ h = h + self.pos_emb(pos)
396
+ h_list = []
397
+ visibility = self.visibility(x, x.device)
398
+
399
+ for i in range(self.nlayers):
400
+ h_list.append(h)
401
+ h = self.layers[i](
402
+ h.transpose(0, 1), key_padding_mask=visibility).transpose(0, 1)
403
+
404
+ output = h
405
+ h_array = torch.stack(h_list, dim=2)
406
+
407
+ return output, h_array
408
+
409
+ def forward(self, x, pos):
410
+ """Pass the input through the encoder layer.
411
+
412
+ Args:
413
+ x: input tokens (required).
414
+ pos: position for each token (optional).
415
+ Returns:
416
+ output: probability distributions for missing tokens.
417
+ state_dict: parsing results and raw output
418
+ """
419
+
420
+ batch_size, length = x.size()
421
+
422
+ raw_output, _ = self.encode(x, pos)
423
+ raw_output = self.norm(raw_output)
424
+ raw_output = self.drop(raw_output)
425
+
426
+ output = self.output_layer(raw_output)
427
+ return output.view(batch_size * length, -1), {'raw_output': raw_output,}
428
+
429
+ class StructFormer(Transformer):
430
+ """StructFormer model."""
431
+
432
+ def __init__(self,
433
+ hidden_size,
434
+ nlayers,
435
+ ntokens,
436
+ nhead=8,
437
+ dropout=0.1,
438
+ dropatt=0.1,
439
+ relative_bias=False,
440
+ pos_emb=False,
441
+ pad=0,
442
+ n_parser_layers=4,
443
+ conv_size=9,
444
+ relations=('head', 'child'),
445
+ weight_act='softmax'):
446
+ """Initialization.
447
+
448
+ Args:
449
+ hidden_size: dimension of inputs and hidden states
450
+ nlayers: number of layers
451
+ ntokens: number of output categories
452
+ nhead: number of self-attention heads
453
+ dropout: dropout rate
454
+ dropatt: drop attention rate
455
+ relative_bias: bool, indicate whether use a relative position based
456
+ attention bias
457
+ pos_emb: bool, indicate whether use a learnable positional embedding
458
+ pad: pad token index
459
+ n_parser_layers: number of parsing layers
460
+ conv_size: convolution kernel size for parser
461
+ relations: relations that are used to compute self attention
462
+ weight_act: relations distribution activation function
463
+ """
464
+
465
+ super(StructFormer, self).__init__(
466
+ hidden_size,
467
+ nlayers,
468
+ ntokens,
469
+ nhead=nhead,
470
+ dropout=dropout,
471
+ dropatt=dropatt,
472
+ relative_bias=relative_bias,
473
+ pos_emb=pos_emb,
474
+ pad=pad)
475
+
476
+ self.parser_layers = nn.ModuleList([
477
+ nn.Sequential(Conv1d(hidden_size, conv_size),
478
+ nn.LayerNorm(hidden_size, elementwise_affine=False),
479
+ nn.Tanh()) for i in range(n_parser_layers)])
480
+
481
+ self.distance_ff = nn.Sequential(
482
+ Conv1d(hidden_size, 2),
483
+ nn.LayerNorm(hidden_size, elementwise_affine=False), nn.Tanh(),
484
+ nn.Linear(hidden_size, 1))
485
+
486
+ self.height_ff = nn.Sequential(
487
+ nn.Linear(hidden_size, hidden_size),
488
+ nn.LayerNorm(hidden_size, elementwise_affine=False), nn.Tanh(),
489
+ nn.Linear(hidden_size, 1))
490
+
491
+ n_rel = len(relations)
492
+ self._rel_weight = nn.Parameter(torch.zeros((nlayers, nhead, n_rel)))
493
+ self._rel_weight.data.normal_(0, 0.1)
494
+
495
+ self._scaler = nn.Parameter(torch.zeros(2))
496
+
497
+ self.n_parse_layers = n_parser_layers
498
+ self.weight_act = weight_act
499
+ self.relations = relations
500
+
501
+ @property
502
+ def scaler(self):
503
+ return self._scaler.exp()
504
+
505
+ @property
506
+ def rel_weight(self):
507
+ if self.weight_act == 'sigmoid':
508
+ return torch.sigmoid(self._rel_weight)
509
+ elif self.weight_act == 'softmax':
510
+ return torch.softmax(self._rel_weight, dim=-1)
511
+
512
+ def parse(self, x, pos):
513
+ """Parse input sentence.
514
+
515
+ Args:
516
+ x: input tokens (required).
517
+ pos: position for each token (optional).
518
+ Returns:
519
+ distance: syntactic distance
520
+ height: syntactic height
521
+ """
522
+
523
+ mask = (x != self.pad)
524
+ mask_shifted = F.pad(mask[:, 1:], (0, 1), value=0)
525
+
526
+ h = self.emb(x)
527
+ for i in range(self.n_parse_layers):
528
+ h = h.masked_fill(~mask[:, :, None], 0)
529
+ h = self.parser_layers[i](h)
530
+
531
+ height = self.height_ff(h).squeeze(-1)
532
+ height.masked_fill_(~mask, -1e9)
533
+
534
+ distance = self.distance_ff(h).squeeze(-1)
535
+ distance.masked_fill_(~mask_shifted, 1e9)
536
+
537
+ # Calbrating the distance and height to the same level
538
+ length = distance.size(1)
539
+ height_max = height[:, None, :].expand(-1, length, -1)
540
+ height_max = torch.cummax(
541
+ height_max.triu(0) - torch.ones_like(height_max).tril(-1) * 1e9,
542
+ dim=-1)[0].triu(0)
543
+
544
+ margin_left = torch.relu(
545
+ F.pad(distance[:, :-1, None], (0, 0, 1, 0), value=1e9) - height_max)
546
+ margin_right = torch.relu(distance[:, None, :] - height_max)
547
+ margin = torch.where(margin_left > margin_right, margin_right,
548
+ margin_left).triu(0)
549
+
550
+ margin_mask = torch.stack([mask_shifted] + [mask] * (length - 1), dim=1)
551
+ margin.masked_fill_(~margin_mask, 0)
552
+ margin = margin.max()
553
+
554
+ distance = distance - margin
555
+
556
+ return distance, height
557
+
558
+ def compute_block(self, distance, height):
559
+ """Compute constituents from distance and height."""
560
+
561
+ beta_logits = (distance[:, None, :] - height[:, :, None]) * self.scaler[0]
562
+
563
+ gamma = torch.sigmoid(-beta_logits)
564
+ ones = torch.ones_like(gamma)
565
+
566
+ block_mask_left = cummin(
567
+ gamma.tril(-1) + ones.triu(0), reverse=True, max_value=1)
568
+ block_mask_left = block_mask_left - F.pad(
569
+ block_mask_left[:, :, :-1], (1, 0), value=0)
570
+ block_mask_left.tril_(0)
571
+
572
+ block_mask_right = cummin(
573
+ gamma.triu(0) + ones.tril(-1), exclusive=True, max_value=1)
574
+ block_mask_right = block_mask_right - F.pad(
575
+ block_mask_right[:, :, 1:], (0, 1), value=0)
576
+ block_mask_right.triu_(0)
577
+
578
+ block_p = block_mask_left[:, :, :, None] * block_mask_right[:, :, None, :]
579
+ block = cumsum(block_mask_left).tril(0) + cumsum(
580
+ block_mask_right, reverse=True).triu(1)
581
+
582
+ return block_p, block
583
+
584
+ def compute_head(self, height):
585
+ """Estimate head for each constituent."""
586
+
587
+ _, length = height.size()
588
+ head_logits = height * self.scaler[1]
589
+ index = torch.arange(length, device=height.device)
590
+
591
+ mask = (index[:, None, None] <= index[None, None, :]) * (
592
+ index[None, None, :] <= index[None, :, None])
593
+ head_logits = head_logits[:, None, None, :].repeat(1, length, length, 1)
594
+ head_logits.masked_fill_(~mask[None, :, :, :], -1e9)
595
+
596
+ head_p = torch.softmax(head_logits, dim=-1)
597
+
598
+ return head_p
599
+
600
+ def generate_mask(self, x, distance, height):
601
+ """Compute head and cibling distribution for each token."""
602
+
603
+ bsz, length = x.size()
604
+
605
+ eye = torch.eye(length, device=x.device, dtype=torch.bool)
606
+ eye = eye[None, :, :].expand((bsz, -1, -1))
607
+
608
+ block_p, block = self.compute_block(distance, height)
609
+ head_p = self.compute_head(height)
610
+ head = torch.einsum('blij,bijh->blh', block_p, head_p)
611
+ head = head.masked_fill(eye, 0)
612
+ child = head.transpose(1, 2)
613
+ cibling = torch.bmm(head, child).masked_fill(eye, 0)
614
+
615
+ rel_list = []
616
+ if 'head' in self.relations:
617
+ rel_list.append(head)
618
+ if 'child' in self.relations:
619
+ rel_list.append(child)
620
+ if 'cibling' in self.relations:
621
+ rel_list.append(cibling)
622
+
623
+ rel = torch.stack(rel_list, dim=1)
624
+
625
+ rel_weight = self.rel_weight
626
+
627
+ dep = torch.einsum('lhr,brij->lbhij', rel_weight, rel)
628
+ att_mask = dep.reshape(self.nlayers, bsz * self.nhead, length, length)
629
+
630
+ return att_mask, cibling, head, block
631
+
632
+ def encode(self, x, pos, att_mask):
633
+ """Structformer encoding process."""
634
+
635
+ visibility = self.visibility(x, x.device)
636
+ h = self.emb(x)
637
+ if hasattr(self, 'pos_emb'):
638
+ assert pos.max() < 500
639
+ h = h + self.pos_emb(pos)
640
+ for i in range(self.nlayers):
641
+ h = self.layers[i](
642
+ h.transpose(0, 1), attn_mask=att_mask[i],
643
+ key_padding_mask=visibility).transpose(0, 1)
644
+ return h
645
+
646
+ def forward(self, x, pos):
647
+ """Pass the input through the encoder layer.
648
+
649
+ Args:
650
+ x: input tokens (required).
651
+ pos: position for each token (optional).
652
+ Returns:
653
+ output: probability distributions for missing tokens.
654
+ state_dict: parsing results and raw output
655
+ """
656
+
657
+ batch_size, length = x.size()
658
+
659
+ distance, height = self.parse(x, pos)
660
+ att_mask, cibling, head, block = self.generate_mask(x, distance, height)
661
+
662
+ raw_output = self.encode(x, pos, att_mask)
663
+ raw_output = self.norm(raw_output)
664
+ raw_output = self.drop(raw_output)
665
+
666
+ output = self.output_layer(raw_output)
667
+
668
+ return output.view(batch_size * length, -1), \
669
+ {'raw_output': raw_output, 'distance': distance, 'height': height,
670
+ 'cibling': cibling, 'head': head, 'block': block}
671
+
672
+
673
+ ##########################################
674
+ # Clasication Head For BabyLM Evaluation Tasks
675
+ ##########################################
676
+ class ClassificationHead(nn.Module):
677
+ """Head for sentence-level classification tasks."""
678
+ def __init__(self, config):
679
+ super(ClassificationHead, self).__init__()
680
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
681
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
682
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
683
+
684
+ def forward(self, features, **kwargs):
685
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
686
+ x = self.dropout(x)
687
+ x = self.dense(x)
688
+ x = torch.tanh(x)
689
+ x = self.dropout(x)
690
+ x = self.out_proj(x)
691
+ return x
692
+
693
+ ##########################################
694
+ # HuggingFace Config
695
+ ##########################################
696
+ class StructFormerConfig(PretrainedConfig):
697
+ model_type = "structformer"
698
+
699
+ def __init__(
700
+ self,
701
+ hidden_size=512,
702
+ nlayers=8,
703
+ ntokens=10_000,
704
+ nhead=8,
705
+ dropout=0.1,
706
+ dropatt=0.1,
707
+ relative_bias=False,
708
+ pos_emb=False,
709
+ pad=0,
710
+ n_parser_layers=4,
711
+ conv_size=9,
712
+ relations=('head', 'child'),
713
+ weight_act='softmax',
714
+ num_labels=1,
715
+ hidden_dropout_prob=0.1,
716
+ initializer_range=0.02,
717
+ **kwargs,
718
+ ):
719
+ self.hidden_size = hidden_size
720
+ self.nlayers = nlayers
721
+ self.ntokens = ntokens
722
+ self.nhead = nhead
723
+ self.dropout = dropout
724
+ self.dropatt = dropatt
725
+ self.relative_bias = relative_bias
726
+ self.pos_emb = pos_emb
727
+ self.pad = pad
728
+ self.n_parser_layers = n_parser_layers
729
+ self.conv_size = conv_size
730
+ self.relations = relations
731
+ self.weight_act = weight_act
732
+ self.num_labels = num_labels
733
+ self.hidden_dropout_prob = hidden_dropout_prob
734
+ self.initializer_range=initializer_range
735
+ super().__init__(**kwargs)
736
+
737
+ ##########################################
738
+ # HuggingFace Model
739
+ ##########################################
740
+ class StructFormerModel(PreTrainedModel):
741
+ config_class = StructFormerConfig
742
+
743
+ def __init__(self, config):
744
+ super().__init__(config)
745
+ self.model = StructFormer(
746
+ hidden_size=config.hidden_size,
747
+ nlayers=config.nlayers,
748
+ ntokens=config.ntokens,
749
+ nhead=config.nhead,
750
+ dropout=config.dropout,
751
+ dropatt=config.dropatt,
752
+ relative_bias=config.relative_bias,
753
+ pos_emb=config.pos_emb,
754
+ pad=config.pad,
755
+ n_parser_layers=config.n_parser_layers,
756
+ conv_size=config.conv_size,
757
+ relations=config.relations,
758
+ weight_act=config.weight_act
759
+ )
760
+ self.config = config
761
+
762
+ def parse(self, input_ids, **kwargs):
763
+ x = input_ids
764
+ batch_size, length = x.size()
765
+ pos = kwargs['position_ids'] if 'position_ids' in kwargs.keys() else torch.arange(length, device=x.device).expand(batch_size, length)
766
+
767
+ sf_output = self.model(x, pos)
768
+
769
+ return sf_output[1]
770
+
771
+ def forward(self, input_ids, labels=None, **kwargs):
772
+ x = input_ids
773
+ batch_size, length = x.size()
774
+ pos = kwargs['position_ids'] if 'position_ids' in kwargs.keys() else torch.arange(length, device=x.device).expand(batch_size, length)
775
+
776
+ sf_output = self.model(x, pos)
777
+
778
+ loss = None
779
+ if labels is not None:
780
+ loss_fct = nn.CrossEntropyLoss()
781
+ loss = loss_fct(sf_output[0], labels.reshape(-1))
782
+
783
+ return MaskedLMOutput(
784
+ loss=loss, # shape: 1
785
+ logits=sf_output[0].view(batch_size, length, -1), # shape: (batch_size, length, ntokens)
786
+ hidden_states=None,
787
+ attentions=None
788
+ )
789
+
790
+ class StructFormerModelForSequenceClassification(PreTrainedModel):
791
+ config_class = StructFormerConfig
792
+
793
+ def __init__(self, config):
794
+ super().__init__(config)
795
+ self.model = StructFormer(
796
+ hidden_size=config.hidden_size,
797
+ nlayers=config.nlayers,
798
+ ntokens=config.ntokens,
799
+ nhead=config.nhead,
800
+ dropout=config.dropout,
801
+ dropatt=config.dropatt,
802
+ relative_bias=config.relative_bias,
803
+ pos_emb=config.pos_emb,
804
+ pad=config.pad,
805
+ n_parser_layers=config.n_parser_layers,
806
+ conv_size=config.conv_size,
807
+ relations=config.relations,
808
+ weight_act=config.weight_act
809
+ )
810
+ self.config = config
811
+ self.num_labels = config.num_labels
812
+ self.model.classifier = ClassificationHead(config)
813
+
814
+ def _init_weights(self, module):
815
+ """Initialize the weights"""
816
+ if isinstance(module, nn.Linear):
817
+ # Slightly different from the TF version which uses truncated_normal for initialization
818
+ # cf https://github.com/pytorch/pytorch/pull/5617
819
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
820
+ if module.bias is not None:
821
+ module.bias.data.zero_()
822
+ elif isinstance(module, nn.Embedding):
823
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
824
+ if module.padding_idx is not None:
825
+ module.weight.data[module.padding_idx].zero_()
826
+ elif isinstance(module, nn.LayerNorm):
827
+ if module.bias is not None:
828
+ module.bias.data.zero_()
829
+ module.weight.data.fill_(1.0)
830
+
831
+ def forward(self, input_ids, labels=None, **kwargs):
832
+ x = input_ids
833
+ batch_size, length = x.size()
834
+ pos = kwargs['position_ids'] if 'position_ids' in kwargs.keys() else torch.arange(length, device=x.device).expand(batch_size, length)
835
+
836
+ sf_output = self.model(x, pos)
837
+
838
+ logits = self.model.classifier(sf_output[1]['raw_output'])
839
+ loss = None
840
+ if labels is not None:
841
+ if self.config.problem_type is None:
842
+ if self.num_labels == 1:
843
+ self.config.problem_type = "regression"
844
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
845
+ self.config.problem_type = "single_label_classification"
846
+ else:
847
+ self.config.problem_type = "multi_label_classification"
848
+
849
+ if self.config.problem_type == "regression":
850
+ loss_fct = nn.MSELoss()
851
+ if self.num_labels == 1:
852
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
853
+ else:
854
+ loss = loss_fct(logits, labels)
855
+ elif self.config.problem_type == "single_label_classification":
856
+ loss_fct = nn.CrossEntropyLoss()
857
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
858
+ elif self.config.problem_type == "multi_label_classification":
859
+ loss_fct = nn.BCEWithLogitsLoss()
860
+ loss = loss_fct(logits, labels)
861
+
862
+ return SequenceClassifierOutput(
863
+ loss=loss,
864
+ logits=logits,
865
+ hidden_states=None,
866
+ attentions=None,
867
+ )
finetune/cola/checkpoint-200/tokenizer_config.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "bos_token": {
4
+ "__type": "AddedToken",
5
+ "content": "<s>",
6
+ "lstrip": false,
7
+ "normalized": true,
8
+ "rstrip": false,
9
+ "single_word": false
10
+ },
11
+ "cls_token": {
12
+ "__type": "AddedToken",
13
+ "content": "<s>",
14
+ "lstrip": false,
15
+ "normalized": true,
16
+ "rstrip": false,
17
+ "single_word": false
18
+ },
19
+ "eos_token": {
20
+ "__type": "AddedToken",
21
+ "content": "</s>",
22
+ "lstrip": false,
23
+ "normalized": true,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ },
27
+ "errors": "replace",
28
+ "mask_token": {
29
+ "__type": "AddedToken",
30
+ "content": "<mask>",
31
+ "lstrip": true,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false
35
+ },
36
+ "model_max_length": 512,
37
+ "name_or_path": "omarmomen/sf_babylm_1",
38
+ "pad_token": {
39
+ "__type": "AddedToken",
40
+ "content": "<pad>",
41
+ "lstrip": false,
42
+ "normalized": true,
43
+ "rstrip": false,
44
+ "single_word": false
45
+ },
46
+ "sep_token": {
47
+ "__type": "AddedToken",
48
+ "content": "</s>",
49
+ "lstrip": false,
50
+ "normalized": true,
51
+ "rstrip": false,
52
+ "single_word": false
53
+ },
54
+ "special_tokens_map_file": null,
55
+ "tokenizer_class": "RobertaTokenizer",
56
+ "trim_offsets": true,
57
+ "unk_token": {
58
+ "__type": "AddedToken",
59
+ "content": "<unk>",
60
+ "lstrip": false,
61
+ "normalized": true,
62
+ "rstrip": false,
63
+ "single_word": false
64
+ }
65
+ }
finetune/cola/checkpoint-200/trainer_state.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": 0.8219339622641509,
3
+ "best_model_checkpoint": "omarmomen/sf_babylm_1/finetune/cola/checkpoint-200",
4
+ "epoch": 1.5625,
5
+ "global_step": 200,
6
+ "is_hyper_param_search": false,
7
+ "is_local_process_zero": true,
8
+ "is_world_process_zero": true,
9
+ "log_history": [
10
+ {
11
+ "epoch": 1.56,
12
+ "eval_accuracy": 0.7036309838294983,
13
+ "eval_f1": 0.8219339622641509,
14
+ "eval_loss": 0.6300716400146484,
15
+ "eval_mcc": 0.13076987235140602,
16
+ "eval_runtime": 1.2993,
17
+ "eval_samples_per_second": 784.268,
18
+ "eval_steps_per_second": 98.515,
19
+ "step": 200
20
+ }
21
+ ],
22
+ "max_steps": 1280,
23
+ "num_train_epochs": 10,
24
+ "total_flos": 327301417273344.0,
25
+ "trial_name": null,
26
+ "trial_params": null
27
+ }
finetune/cola/checkpoint-200/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c43ff5a8741c4285a95db833f1cab13594ae1c36859759e5123678abf6a7eba3
3
+ size 3960
finetune/cola/checkpoint-200/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
finetune/cola/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "omarmomen/sf_babylm_1",
3
+ "architectures": [
4
+ "StructFormerModelForSequenceClassification"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "structformer.StructFormerConfig",
8
+ "AutoModelForMaskedLM": "structformer.StructFormerModel",
9
+ "AutoModelForSequenceClassification": "structformer.StructFormerModelForSequenceClassification"
10
+ },
11
+ "conv_size": 9,
12
+ "dropatt": 0.1,
13
+ "dropout": 0.1,
14
+ "hidden_dropout_prob": 0.1,
15
+ "hidden_size": 512,
16
+ "id2label": {
17
+ "0": 0,
18
+ "1": 1
19
+ },
20
+ "initializer_range": 0.02,
21
+ "label2id": {
22
+ "0": 0,
23
+ "1": 1
24
+ },
25
+ "model_type": "structformer",
26
+ "n_parser_layers": 3,
27
+ "nhead": 8,
28
+ "nlayers": 8,
29
+ "ntokens": 16000,
30
+ "pad": 1,
31
+ "pos_emb": true,
32
+ "problem_type": "single_label_classification",
33
+ "relations": [
34
+ "head",
35
+ "child"
36
+ ],
37
+ "relative_bias": false,
38
+ "torch_dtype": "float32",
39
+ "transformers_version": "4.26.1",
40
+ "weight_act": "softmax"
41
+ }
finetune/cola/eval_results.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 10.0,
3
+ "eval_accuracy": 0.7036309838294983,
4
+ "eval_f1": 0.8219339622641509,
5
+ "eval_loss": 0.6300716400146484,
6
+ "eval_mcc": 0.13076987235140602,
7
+ "eval_runtime": 1.7861,
8
+ "eval_samples": 1019,
9
+ "eval_samples_per_second": 570.517,
10
+ "eval_steps_per_second": 71.665
11
+ }
finetune/cola/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
finetune/cola/predict_results.txt ADDED
@@ -0,0 +1,1020 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ index prediction
2
+ 0 1
3
+ 1 1
4
+ 2 1
5
+ 3 1
6
+ 4 1
7
+ 5 1
8
+ 6 1
9
+ 7 1
10
+ 8 1
11
+ 9 1
12
+ 10 0
13
+ 11 1
14
+ 12 1
15
+ 13 1
16
+ 14 1
17
+ 15 1
18
+ 16 1
19
+ 17 1
20
+ 18 1
21
+ 19 1
22
+ 20 1
23
+ 21 1
24
+ 22 1
25
+ 23 1
26
+ 24 1
27
+ 25 1
28
+ 26 1
29
+ 27 1
30
+ 28 1
31
+ 29 1
32
+ 30 1
33
+ 31 1
34
+ 32 1
35
+ 33 1
36
+ 34 1
37
+ 35 1
38
+ 36 1
39
+ 37 1
40
+ 38 1
41
+ 39 1
42
+ 40 1
43
+ 41 0
44
+ 42 1
45
+ 43 1
46
+ 44 1
47
+ 45 1
48
+ 46 1
49
+ 47 1
50
+ 48 1
51
+ 49 1
52
+ 50 1
53
+ 51 1
54
+ 52 1
55
+ 53 1
56
+ 54 1
57
+ 55 1
58
+ 56 1
59
+ 57 1
60
+ 58 1
61
+ 59 1
62
+ 60 1
63
+ 61 1
64
+ 62 1
65
+ 63 1
66
+ 64 1
67
+ 65 1
68
+ 66 1
69
+ 67 1
70
+ 68 1
71
+ 69 1
72
+ 70 1
73
+ 71 1
74
+ 72 1
75
+ 73 1
76
+ 74 1
77
+ 75 1
78
+ 76 1
79
+ 77 1
80
+ 78 1
81
+ 79 1
82
+ 80 0
83
+ 81 1
84
+ 82 1
85
+ 83 1
86
+ 84 1
87
+ 85 1
88
+ 86 1
89
+ 87 1
90
+ 88 1
91
+ 89 1
92
+ 90 1
93
+ 91 1
94
+ 92 1
95
+ 93 1
96
+ 94 1
97
+ 95 1
98
+ 96 1
99
+ 97 1
100
+ 98 1
101
+ 99 1
102
+ 100 1
103
+ 101 1
104
+ 102 1
105
+ 103 1
106
+ 104 1
107
+ 105 1
108
+ 106 1
109
+ 107 1
110
+ 108 1
111
+ 109 1
112
+ 110 1
113
+ 111 1
114
+ 112 1
115
+ 113 1
116
+ 114 1
117
+ 115 1
118
+ 116 1
119
+ 117 1
120
+ 118 1
121
+ 119 1
122
+ 120 1
123
+ 121 1
124
+ 122 1
125
+ 123 1
126
+ 124 1
127
+ 125 1
128
+ 126 1
129
+ 127 1
130
+ 128 1
131
+ 129 1
132
+ 130 1
133
+ 131 1
134
+ 132 1
135
+ 133 1
136
+ 134 1
137
+ 135 1
138
+ 136 1
139
+ 137 1
140
+ 138 1
141
+ 139 1
142
+ 140 1
143
+ 141 0
144
+ 142 1
145
+ 143 1
146
+ 144 1
147
+ 145 1
148
+ 146 1
149
+ 147 1
150
+ 148 1
151
+ 149 1
152
+ 150 1
153
+ 151 1
154
+ 152 1
155
+ 153 1
156
+ 154 1
157
+ 155 1
158
+ 156 1
159
+ 157 1
160
+ 158 1
161
+ 159 1
162
+ 160 1
163
+ 161 1
164
+ 162 1
165
+ 163 1
166
+ 164 1
167
+ 165 1
168
+ 166 0
169
+ 167 1
170
+ 168 0
171
+ 169 1
172
+ 170 1
173
+ 171 0
174
+ 172 1
175
+ 173 1
176
+ 174 1
177
+ 175 1
178
+ 176 1
179
+ 177 1
180
+ 178 1
181
+ 179 1
182
+ 180 1
183
+ 181 1
184
+ 182 1
185
+ 183 1
186
+ 184 1
187
+ 185 1
188
+ 186 1
189
+ 187 1
190
+ 188 1
191
+ 189 1
192
+ 190 1
193
+ 191 1
194
+ 192 1
195
+ 193 1
196
+ 194 1
197
+ 195 1
198
+ 196 1
199
+ 197 1
200
+ 198 1
201
+ 199 1
202
+ 200 1
203
+ 201 1
204
+ 202 1
205
+ 203 1
206
+ 204 1
207
+ 205 1
208
+ 206 1
209
+ 207 1
210
+ 208 1
211
+ 209 1
212
+ 210 1
213
+ 211 1
214
+ 212 1
215
+ 213 1
216
+ 214 1
217
+ 215 1
218
+ 216 1
219
+ 217 1
220
+ 218 1
221
+ 219 1
222
+ 220 1
223
+ 221 1
224
+ 222 1
225
+ 223 1
226
+ 224 1
227
+ 225 1
228
+ 226 1
229
+ 227 1
230
+ 228 1
231
+ 229 1
232
+ 230 1
233
+ 231 1
234
+ 232 0
235
+ 233 1
236
+ 234 1
237
+ 235 1
238
+ 236 1
239
+ 237 1
240
+ 238 1
241
+ 239 1
242
+ 240 1
243
+ 241 1
244
+ 242 0
245
+ 243 1
246
+ 244 1
247
+ 245 1
248
+ 246 1
249
+ 247 1
250
+ 248 0
251
+ 249 1
252
+ 250 1
253
+ 251 1
254
+ 252 1
255
+ 253 1
256
+ 254 1
257
+ 255 1
258
+ 256 1
259
+ 257 1
260
+ 258 1
261
+ 259 1
262
+ 260 1
263
+ 261 1
264
+ 262 1
265
+ 263 1
266
+ 264 1
267
+ 265 1
268
+ 266 1
269
+ 267 1
270
+ 268 1
271
+ 269 1
272
+ 270 1
273
+ 271 1
274
+ 272 0
275
+ 273 1
276
+ 274 1
277
+ 275 1
278
+ 276 1
279
+ 277 1
280
+ 278 1
281
+ 279 1
282
+ 280 1
283
+ 281 1
284
+ 282 1
285
+ 283 1
286
+ 284 1
287
+ 285 1
288
+ 286 0
289
+ 287 1
290
+ 288 1
291
+ 289 1
292
+ 290 1
293
+ 291 1
294
+ 292 1
295
+ 293 0
296
+ 294 1
297
+ 295 1
298
+ 296 0
299
+ 297 1
300
+ 298 1
301
+ 299 1
302
+ 300 0
303
+ 301 1
304
+ 302 1
305
+ 303 1
306
+ 304 1
307
+ 305 1
308
+ 306 1
309
+ 307 1
310
+ 308 1
311
+ 309 1
312
+ 310 1
313
+ 311 1
314
+ 312 1
315
+ 313 1
316
+ 314 1
317
+ 315 1
318
+ 316 1
319
+ 317 1
320
+ 318 1
321
+ 319 1
322
+ 320 1
323
+ 321 1
324
+ 322 1
325
+ 323 0
326
+ 324 1
327
+ 325 1
328
+ 326 1
329
+ 327 1
330
+ 328 1
331
+ 329 1
332
+ 330 1
333
+ 331 1
334
+ 332 0
335
+ 333 1
336
+ 334 1
337
+ 335 1
338
+ 336 1
339
+ 337 1
340
+ 338 1
341
+ 339 1
342
+ 340 1
343
+ 341 1
344
+ 342 1
345
+ 343 1
346
+ 344 1
347
+ 345 1
348
+ 346 1
349
+ 347 1
350
+ 348 1
351
+ 349 1
352
+ 350 1
353
+ 351 1
354
+ 352 1
355
+ 353 1
356
+ 354 1
357
+ 355 1
358
+ 356 1
359
+ 357 1
360
+ 358 1
361
+ 359 1
362
+ 360 1
363
+ 361 1
364
+ 362 1
365
+ 363 1
366
+ 364 1
367
+ 365 1
368
+ 366 1
369
+ 367 1
370
+ 368 1
371
+ 369 1
372
+ 370 1
373
+ 371 1
374
+ 372 1
375
+ 373 1
376
+ 374 1
377
+ 375 1
378
+ 376 1
379
+ 377 1
380
+ 378 1
381
+ 379 1
382
+ 380 1
383
+ 381 1
384
+ 382 1
385
+ 383 1
386
+ 384 1
387
+ 385 1
388
+ 386 1
389
+ 387 1
390
+ 388 1
391
+ 389 1
392
+ 390 1
393
+ 391 1
394
+ 392 0
395
+ 393 1
396
+ 394 1
397
+ 395 1
398
+ 396 1
399
+ 397 1
400
+ 398 1
401
+ 399 1
402
+ 400 1
403
+ 401 1
404
+ 402 1
405
+ 403 1
406
+ 404 1
407
+ 405 1
408
+ 406 1
409
+ 407 1
410
+ 408 1
411
+ 409 1
412
+ 410 1
413
+ 411 1
414
+ 412 1
415
+ 413 1
416
+ 414 1
417
+ 415 1
418
+ 416 1
419
+ 417 1
420
+ 418 1
421
+ 419 1
422
+ 420 1
423
+ 421 1
424
+ 422 1
425
+ 423 1
426
+ 424 1
427
+ 425 1
428
+ 426 1
429
+ 427 1
430
+ 428 1
431
+ 429 1
432
+ 430 1
433
+ 431 1
434
+ 432 1
435
+ 433 1
436
+ 434 1
437
+ 435 1
438
+ 436 1
439
+ 437 1
440
+ 438 1
441
+ 439 1
442
+ 440 1
443
+ 441 1
444
+ 442 1
445
+ 443 1
446
+ 444 1
447
+ 445 1
448
+ 446 1
449
+ 447 1
450
+ 448 1
451
+ 449 1
452
+ 450 1
453
+ 451 1
454
+ 452 1
455
+ 453 1
456
+ 454 1
457
+ 455 1
458
+ 456 1
459
+ 457 1
460
+ 458 1
461
+ 459 1
462
+ 460 1
463
+ 461 1
464
+ 462 1
465
+ 463 1
466
+ 464 1
467
+ 465 1
468
+ 466 1
469
+ 467 1
470
+ 468 1
471
+ 469 1
472
+ 470 1
473
+ 471 1
474
+ 472 1
475
+ 473 1
476
+ 474 1
477
+ 475 1
478
+ 476 1
479
+ 477 1
480
+ 478 1
481
+ 479 1
482
+ 480 1
483
+ 481 1
484
+ 482 1
485
+ 483 1
486
+ 484 1
487
+ 485 1
488
+ 486 1
489
+ 487 1
490
+ 488 1
491
+ 489 1
492
+ 490 1
493
+ 491 1
494
+ 492 1
495
+ 493 1
496
+ 494 1
497
+ 495 1
498
+ 496 1
499
+ 497 1
500
+ 498 1
501
+ 499 1
502
+ 500 1
503
+ 501 1
504
+ 502 1
505
+ 503 1
506
+ 504 1
507
+ 505 1
508
+ 506 1
509
+ 507 1
510
+ 508 0
511
+ 509 1
512
+ 510 1
513
+ 511 1
514
+ 512 1
515
+ 513 1
516
+ 514 1
517
+ 515 1
518
+ 516 1
519
+ 517 1
520
+ 518 1
521
+ 519 1
522
+ 520 1
523
+ 521 1
524
+ 522 1
525
+ 523 1
526
+ 524 1
527
+ 525 1
528
+ 526 1
529
+ 527 1
530
+ 528 1
531
+ 529 1
532
+ 530 1
533
+ 531 1
534
+ 532 1
535
+ 533 1
536
+ 534 1
537
+ 535 1
538
+ 536 1
539
+ 537 1
540
+ 538 1
541
+ 539 1
542
+ 540 1
543
+ 541 1
544
+ 542 1
545
+ 543 1
546
+ 544 1
547
+ 545 0
548
+ 546 1
549
+ 547 1
550
+ 548 1
551
+ 549 1
552
+ 550 1
553
+ 551 1
554
+ 552 1
555
+ 553 1
556
+ 554 1
557
+ 555 1
558
+ 556 1
559
+ 557 1
560
+ 558 1
561
+ 559 1
562
+ 560 1
563
+ 561 1
564
+ 562 1
565
+ 563 1
566
+ 564 1
567
+ 565 1
568
+ 566 1
569
+ 567 1
570
+ 568 1
571
+ 569 1
572
+ 570 1
573
+ 571 1
574
+ 572 1
575
+ 573 1
576
+ 574 1
577
+ 575 1
578
+ 576 1
579
+ 577 1
580
+ 578 1
581
+ 579 1
582
+ 580 1
583
+ 581 1
584
+ 582 1
585
+ 583 1
586
+ 584 1
587
+ 585 1
588
+ 586 1
589
+ 587 1
590
+ 588 1
591
+ 589 1
592
+ 590 1
593
+ 591 1
594
+ 592 1
595
+ 593 0
596
+ 594 1
597
+ 595 1
598
+ 596 1
599
+ 597 1
600
+ 598 1
601
+ 599 0
602
+ 600 1
603
+ 601 1
604
+ 602 1
605
+ 603 0
606
+ 604 0
607
+ 605 0
608
+ 606 1
609
+ 607 1
610
+ 608 1
611
+ 609 1
612
+ 610 1
613
+ 611 1
614
+ 612 1
615
+ 613 1
616
+ 614 1
617
+ 615 1
618
+ 616 1
619
+ 617 1
620
+ 618 1
621
+ 619 1
622
+ 620 1
623
+ 621 1
624
+ 622 1
625
+ 623 1
626
+ 624 1
627
+ 625 1
628
+ 626 1
629
+ 627 1
630
+ 628 1
631
+ 629 1
632
+ 630 1
633
+ 631 1
634
+ 632 1
635
+ 633 1
636
+ 634 1
637
+ 635 1
638
+ 636 1
639
+ 637 1
640
+ 638 1
641
+ 639 1
642
+ 640 1
643
+ 641 1
644
+ 642 1
645
+ 643 1
646
+ 644 1
647
+ 645 1
648
+ 646 1
649
+ 647 1
650
+ 648 1
651
+ 649 1
652
+ 650 1
653
+ 651 1
654
+ 652 1
655
+ 653 1
656
+ 654 1
657
+ 655 1
658
+ 656 1
659
+ 657 1
660
+ 658 1
661
+ 659 1
662
+ 660 1
663
+ 661 1
664
+ 662 1
665
+ 663 1
666
+ 664 1
667
+ 665 1
668
+ 666 1
669
+ 667 1
670
+ 668 1
671
+ 669 1
672
+ 670 1
673
+ 671 1
674
+ 672 1
675
+ 673 1
676
+ 674 1
677
+ 675 1
678
+ 676 1
679
+ 677 1
680
+ 678 1
681
+ 679 1
682
+ 680 1
683
+ 681 1
684
+ 682 1
685
+ 683 1
686
+ 684 1
687
+ 685 1
688
+ 686 1
689
+ 687 1
690
+ 688 1
691
+ 689 1
692
+ 690 1
693
+ 691 1
694
+ 692 1
695
+ 693 1
696
+ 694 1
697
+ 695 1
698
+ 696 1
699
+ 697 1
700
+ 698 1
701
+ 699 1
702
+ 700 1
703
+ 701 1
704
+ 702 1
705
+ 703 1
706
+ 704 1
707
+ 705 1
708
+ 706 1
709
+ 707 1
710
+ 708 1
711
+ 709 1
712
+ 710 1
713
+ 711 1
714
+ 712 1
715
+ 713 1
716
+ 714 1
717
+ 715 1
718
+ 716 1
719
+ 717 1
720
+ 718 1
721
+ 719 1
722
+ 720 1
723
+ 721 1
724
+ 722 1
725
+ 723 1
726
+ 724 1
727
+ 725 1
728
+ 726 1
729
+ 727 1
730
+ 728 1
731
+ 729 1
732
+ 730 1
733
+ 731 1
734
+ 732 1
735
+ 733 1
736
+ 734 1
737
+ 735 1
738
+ 736 1
739
+ 737 1
740
+ 738 1
741
+ 739 1
742
+ 740 1
743
+ 741 1
744
+ 742 1
745
+ 743 1
746
+ 744 1
747
+ 745 1
748
+ 746 1
749
+ 747 1
750
+ 748 1
751
+ 749 1
752
+ 750 1
753
+ 751 1
754
+ 752 1
755
+ 753 1
756
+ 754 1
757
+ 755 1
758
+ 756 1
759
+ 757 1
760
+ 758 1
761
+ 759 1
762
+ 760 1
763
+ 761 1
764
+ 762 1
765
+ 763 1
766
+ 764 1
767
+ 765 1
768
+ 766 1
769
+ 767 1
770
+ 768 1
771
+ 769 1
772
+ 770 1
773
+ 771 1
774
+ 772 1
775
+ 773 1
776
+ 774 1
777
+ 775 1
778
+ 776 1
779
+ 777 1
780
+ 778 1
781
+ 779 1
782
+ 780 1
783
+ 781 1
784
+ 782 1
785
+ 783 1
786
+ 784 1
787
+ 785 1
788
+ 786 1
789
+ 787 1
790
+ 788 1
791
+ 789 1
792
+ 790 1
793
+ 791 1
794
+ 792 1
795
+ 793 1
796
+ 794 0
797
+ 795 0
798
+ 796 1
799
+ 797 1
800
+ 798 1
801
+ 799 1
802
+ 800 1
803
+ 801 1
804
+ 802 1
805
+ 803 1
806
+ 804 1
807
+ 805 1
808
+ 806 1
809
+ 807 1
810
+ 808 1
811
+ 809 1
812
+ 810 1
813
+ 811 1
814
+ 812 1
815
+ 813 0
816
+ 814 1
817
+ 815 1
818
+ 816 1
819
+ 817 1
820
+ 818 1
821
+ 819 1
822
+ 820 1
823
+ 821 1
824
+ 822 1
825
+ 823 1
826
+ 824 1
827
+ 825 1
828
+ 826 1
829
+ 827 1
830
+ 828 1
831
+ 829 1
832
+ 830 1
833
+ 831 1
834
+ 832 1
835
+ 833 1
836
+ 834 1
837
+ 835 1
838
+ 836 1
839
+ 837 1
840
+ 838 1
841
+ 839 1
842
+ 840 1
843
+ 841 1
844
+ 842 1
845
+ 843 1
846
+ 844 1
847
+ 845 1
848
+ 846 1
849
+ 847 1
850
+ 848 1
851
+ 849 1
852
+ 850 1
853
+ 851 1
854
+ 852 1
855
+ 853 1
856
+ 854 1
857
+ 855 1
858
+ 856 1
859
+ 857 1
860
+ 858 1
861
+ 859 1
862
+ 860 1
863
+ 861 1
864
+ 862 1
865
+ 863 1
866
+ 864 1
867
+ 865 1
868
+ 866 1
869
+ 867 1
870
+ 868 1
871
+ 869 1
872
+ 870 1
873
+ 871 1
874
+ 872 1
875
+ 873 1
876
+ 874 1
877
+ 875 1
878
+ 876 1
879
+ 877 1
880
+ 878 1
881
+ 879 1
882
+ 880 1
883
+ 881 1
884
+ 882 1
885
+ 883 1
886
+ 884 1
887
+ 885 1
888
+ 886 1
889
+ 887 1
890
+ 888 1
891
+ 889 1
892
+ 890 1
893
+ 891 1
894
+ 892 1
895
+ 893 1
896
+ 894 1
897
+ 895 1
898
+ 896 1
899
+ 897 1
900
+ 898 1
901
+ 899 1
902
+ 900 1
903
+ 901 1
904
+ 902 0
905
+ 903 1
906
+ 904 1
907
+ 905 1
908
+ 906 1
909
+ 907 1
910
+ 908 1
911
+ 909 1
912
+ 910 1
913
+ 911 1
914
+ 912 1
915
+ 913 1
916
+ 914 1
917
+ 915 1
918
+ 916 1
919
+ 917 1
920
+ 918 1
921
+ 919 1
922
+ 920 1
923
+ 921 1
924
+ 922 1
925
+ 923 1
926
+ 924 1
927
+ 925 1
928
+ 926 1
929
+ 927 1
930
+ 928 1
931
+ 929 1
932
+ 930 1
933
+ 931 1
934
+ 932 1
935
+ 933 1
936
+ 934 1
937
+ 935 1
938
+ 936 1
939
+ 937 1
940
+ 938 1
941
+ 939 1
942
+ 940 1
943
+ 941 1
944
+ 942 1
945
+ 943 1
946
+ 944 1
947
+ 945 1
948
+ 946 1
949
+ 947 1
950
+ 948 1
951
+ 949 1
952
+ 950 1
953
+ 951 1
954
+ 952 1
955
+ 953 1
956
+ 954 1
957
+ 955 1
958
+ 956 1
959
+ 957 1
960
+ 958 1
961
+ 959 1
962
+ 960 1
963
+ 961 1
964
+ 962 1
965
+ 963 1
966
+ 964 1
967
+ 965 1
968
+ 966 1
969
+ 967 1
970
+ 968 1
971
+ 969 1
972
+ 970 1
973
+ 971 1
974
+ 972 1
975
+ 973 1
976
+ 974 1
977
+ 975 1
978
+ 976 1
979
+ 977 1
980
+ 978 0
981
+ 979 1
982
+ 980 1
983
+ 981 1
984
+ 982 1
985
+ 983 1
986
+ 984 1
987
+ 985 1
988
+ 986 1
989
+ 987 1
990
+ 988 1
991
+ 989 1
992
+ 990 1
993
+ 991 1
994
+ 992 1
995
+ 993 1
996
+ 994 1
997
+ 995 1
998
+ 996 0
999
+ 997 1
1000
+ 998 1
1001
+ 999 1
1002
+ 1000 1
1003
+ 1001 1
1004
+ 1002 1
1005
+ 1003 1
1006
+ 1004 1
1007
+ 1005 1
1008
+ 1006 1
1009
+ 1007 1
1010
+ 1008 1
1011
+ 1009 1
1012
+ 1010 1
1013
+ 1011 1
1014
+ 1012 1
1015
+ 1013 1
1016
+ 1014 1
1017
+ 1015 1
1018
+ 1016 1
1019
+ 1017 1
1020
+ 1018 1
finetune/cola/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:782e41676fcfa55bd9f10569a44c812fc36f983ee47f32bd0cafdee7d732ee83
3
+ size 167313902
finetune/cola/special_tokens_map.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<s>",
3
+ "cls_token": "<s>",
4
+ "eos_token": "</s>",
5
+ "mask_token": {
6
+ "content": "<mask>",
7
+ "lstrip": true,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "pad_token": "<pad>",
13
+ "sep_token": "</s>",
14
+ "unk_token": "<unk>"
15
+ }
finetune/cola/structformer.py ADDED
@@ -0,0 +1,867 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Google Research Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """StructFormer and transformer model."""
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from torch.nn import init
22
+ from transformers import PretrainedConfig, PreTrainedModel
23
+ from transformers.modeling_outputs import MaskedLMOutput, SequenceClassifierOutput
24
+
25
+ def _get_activation_fn(activation):
26
+ """Get specified activation function."""
27
+ if activation == "relu":
28
+ return nn.ReLU()
29
+ elif activation == "gelu":
30
+ return nn.GELU()
31
+ elif activation == "leakyrelu":
32
+ return nn.LeakyReLU()
33
+
34
+ raise RuntimeError(
35
+ "activation should be relu/gelu, not {}".format(activation))
36
+
37
+
38
+ class Conv1d(nn.Module):
39
+ """1D convolution layer."""
40
+
41
+ def __init__(self, hidden_size, kernel_size, dilation=1):
42
+ """Initialization.
43
+
44
+ Args:
45
+ hidden_size: dimension of input embeddings
46
+ kernel_size: convolution kernel size
47
+ dilation: the spacing between the kernel points
48
+ """
49
+ super(Conv1d, self).__init__()
50
+
51
+ if kernel_size % 2 == 0:
52
+ padding = (kernel_size // 2) * dilation
53
+ self.shift = True
54
+ else:
55
+ padding = ((kernel_size - 1) // 2) * dilation
56
+ self.shift = False
57
+ self.conv = nn.Conv1d(
58
+ hidden_size,
59
+ hidden_size,
60
+ kernel_size,
61
+ padding=padding,
62
+ dilation=dilation)
63
+
64
+ def forward(self, x):
65
+ """Compute convolution.
66
+
67
+ Args:
68
+ x: input embeddings
69
+ Returns:
70
+ conv_output: convolution results
71
+ """
72
+
73
+ if self.shift:
74
+ return self.conv(x.transpose(1, 2)).transpose(1, 2)[:, 1:]
75
+ else:
76
+ return self.conv(x.transpose(1, 2)).transpose(1, 2)
77
+
78
+
79
+ class MultiheadAttention(nn.Module):
80
+ """Multi-head self-attention layer."""
81
+
82
+ def __init__(self,
83
+ embed_dim,
84
+ num_heads,
85
+ dropout=0.,
86
+ bias=True,
87
+ v_proj=True,
88
+ out_proj=True,
89
+ relative_bias=True):
90
+ """Initialization.
91
+
92
+ Args:
93
+ embed_dim: dimension of input embeddings
94
+ num_heads: number of self-attention heads
95
+ dropout: dropout rate
96
+ bias: bool, indicate whether include bias for linear transformations
97
+ v_proj: bool, indicate whether project inputs to new values
98
+ out_proj: bool, indicate whether project outputs to new values
99
+ relative_bias: bool, indicate whether use a relative position based
100
+ attention bias
101
+ """
102
+
103
+ super(MultiheadAttention, self).__init__()
104
+ self.embed_dim = embed_dim
105
+
106
+ self.num_heads = num_heads
107
+ self.drop = nn.Dropout(dropout)
108
+ self.head_dim = embed_dim // num_heads
109
+ assert self.head_dim * num_heads == self.embed_dim, ("embed_dim must be "
110
+ "divisible by "
111
+ "num_heads")
112
+
113
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
114
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
115
+ if v_proj:
116
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
117
+ else:
118
+ self.v_proj = nn.Identity()
119
+
120
+ if out_proj:
121
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
122
+ else:
123
+ self.out_proj = nn.Identity()
124
+
125
+ if relative_bias:
126
+ self.relative_bias = nn.Parameter(torch.zeros((self.num_heads, 512)))
127
+ else:
128
+ self.relative_bias = None
129
+
130
+ self._reset_parameters()
131
+
132
+ def _reset_parameters(self):
133
+ """Initialize attention parameters."""
134
+
135
+ init.xavier_uniform_(self.q_proj.weight)
136
+ init.constant_(self.q_proj.bias, 0.)
137
+
138
+ init.xavier_uniform_(self.k_proj.weight)
139
+ init.constant_(self.k_proj.bias, 0.)
140
+
141
+ if isinstance(self.v_proj, nn.Linear):
142
+ init.xavier_uniform_(self.v_proj.weight)
143
+ init.constant_(self.v_proj.bias, 0.)
144
+
145
+ if isinstance(self.out_proj, nn.Linear):
146
+ init.xavier_uniform_(self.out_proj.weight)
147
+ init.constant_(self.out_proj.bias, 0.)
148
+
149
+ def forward(self, query, key_padding_mask=None, attn_mask=None):
150
+ """Compute multi-head self-attention.
151
+
152
+ Args:
153
+ query: input embeddings
154
+ key_padding_mask: 3D mask that prevents attention to certain positions
155
+ attn_mask: 3D mask that rescale the attention weight at each position
156
+ Returns:
157
+ attn_output: self-attention output
158
+ """
159
+
160
+ length, bsz, embed_dim = query.size()
161
+ assert embed_dim == self.embed_dim
162
+
163
+ head_dim = embed_dim // self.num_heads
164
+ assert head_dim * self.num_heads == embed_dim, ("embed_dim must be "
165
+ "divisible by num_heads")
166
+ scaling = float(head_dim)**-0.5
167
+
168
+ q = self.q_proj(query)
169
+ k = self.k_proj(query)
170
+ v = self.v_proj(query)
171
+
172
+ q = q * scaling
173
+
174
+ if attn_mask is not None:
175
+ assert list(attn_mask.size()) == [bsz * self.num_heads,
176
+ query.size(0), query.size(0)]
177
+
178
+ q = q.contiguous().view(length, bsz * self.num_heads,
179
+ head_dim).transpose(0, 1)
180
+ k = k.contiguous().view(length, bsz * self.num_heads,
181
+ head_dim).transpose(0, 1)
182
+ v = v.contiguous().view(length, bsz * self.num_heads,
183
+ head_dim).transpose(0, 1)
184
+
185
+ attn_output_weights = torch.bmm(q, k.transpose(1, 2))
186
+ assert list(
187
+ attn_output_weights.size()) == [bsz * self.num_heads, length, length]
188
+
189
+ if self.relative_bias is not None:
190
+ pos = torch.arange(length, device=query.device)
191
+ relative_pos = torch.abs(pos[:, None] - pos[None, :]) + 256
192
+ relative_pos = relative_pos[None, :, :].expand(bsz * self.num_heads, -1,
193
+ -1)
194
+
195
+ relative_bias = self.relative_bias.repeat_interleave(bsz, dim=0)
196
+ relative_bias = relative_bias[:, None, :].expand(-1, length, -1)
197
+ relative_bias = torch.gather(relative_bias, 2, relative_pos)
198
+ attn_output_weights = attn_output_weights + relative_bias
199
+
200
+ if key_padding_mask is not None:
201
+ attn_output_weights = attn_output_weights + key_padding_mask
202
+
203
+ if attn_mask is None:
204
+ attn_output_weights = torch.softmax(attn_output_weights, dim=-1)
205
+ else:
206
+ attn_output_weights = torch.sigmoid(attn_output_weights) * attn_mask
207
+
208
+ attn_output_weights = self.drop(attn_output_weights)
209
+
210
+ attn_output = torch.bmm(attn_output_weights, v)
211
+
212
+ assert list(attn_output.size()) == [bsz * self.num_heads, length, head_dim]
213
+ attn_output = attn_output.transpose(0, 1).contiguous().view(
214
+ length, bsz, embed_dim)
215
+ attn_output = self.out_proj(attn_output)
216
+
217
+ return attn_output
218
+
219
+
220
+ class TransformerLayer(nn.Module):
221
+ """TransformerEncoderLayer is made up of self-attn and feedforward network."""
222
+
223
+ def __init__(self,
224
+ d_model,
225
+ nhead,
226
+ dim_feedforward=2048,
227
+ dropout=0.1,
228
+ dropatt=0.1,
229
+ activation="leakyrelu",
230
+ relative_bias=True):
231
+ """Initialization.
232
+
233
+ Args:
234
+ d_model: dimension of inputs
235
+ nhead: number of self-attention heads
236
+ dim_feedforward: dimension of hidden layer in feedforward layer
237
+ dropout: dropout rate
238
+ dropatt: drop attention rate
239
+ activation: activation function
240
+ relative_bias: bool, indicate whether use a relative position based
241
+ attention bias
242
+ """
243
+
244
+ super(TransformerLayer, self).__init__()
245
+ self.self_attn = MultiheadAttention(
246
+ d_model, nhead, dropout=dropatt, relative_bias=relative_bias)
247
+ # Implementation of Feedforward model
248
+ self.feedforward = nn.Sequential(
249
+ nn.LayerNorm(d_model), nn.Linear(d_model, dim_feedforward),
250
+ _get_activation_fn(activation), nn.Dropout(dropout),
251
+ nn.Linear(dim_feedforward, d_model))
252
+
253
+ self.norm = nn.LayerNorm(d_model)
254
+ self.dropout1 = nn.Dropout(dropout)
255
+ self.dropout2 = nn.Dropout(dropout)
256
+
257
+ self.nhead = nhead
258
+
259
+ def forward(self, src, attn_mask=None, key_padding_mask=None):
260
+ """Pass the input through the encoder layer.
261
+
262
+ Args:
263
+ src: the sequence to the encoder layer (required).
264
+ attn_mask: the mask for the src sequence (optional).
265
+ key_padding_mask: the mask for the src keys per batch (optional).
266
+ Returns:
267
+ src3: the output of transformer layer, share the same shape as src.
268
+ """
269
+ src2 = self.self_attn(
270
+ self.norm(src), attn_mask=attn_mask, key_padding_mask=key_padding_mask)
271
+ src2 = src + self.dropout1(src2)
272
+ src3 = self.feedforward(src2)
273
+ src3 = src2 + self.dropout2(src3)
274
+
275
+ return src3
276
+
277
+
278
+ def cumprod(x, reverse=False, exclusive=False):
279
+ """cumulative product."""
280
+ if reverse:
281
+ x = x.flip([-1])
282
+
283
+ if exclusive:
284
+ x = F.pad(x[:, :, :-1], (1, 0), value=1)
285
+
286
+ cx = x.cumprod(-1)
287
+
288
+ if reverse:
289
+ cx = cx.flip([-1])
290
+ return cx
291
+
292
+ def cumsum(x, reverse=False, exclusive=False):
293
+ """cumulative sum."""
294
+ bsz, _, length = x.size()
295
+ device = x.device
296
+ if reverse:
297
+ if exclusive:
298
+ w = torch.ones([bsz, length, length], device=device).tril(-1)
299
+ else:
300
+ w = torch.ones([bsz, length, length], device=device).tril(0)
301
+ cx = torch.bmm(x, w)
302
+ else:
303
+ if exclusive:
304
+ w = torch.ones([bsz, length, length], device=device).triu(1)
305
+ else:
306
+ w = torch.ones([bsz, length, length], device=device).triu(0)
307
+ cx = torch.bmm(x, w)
308
+ return cx
309
+
310
+ def cummin(x, reverse=False, exclusive=False, max_value=1e9):
311
+ """cumulative min."""
312
+ if reverse:
313
+ if exclusive:
314
+ x = F.pad(x[:, :, 1:], (0, 1), value=max_value)
315
+ x = x.flip([-1]).cummin(-1)[0].flip([-1])
316
+ else:
317
+ if exclusive:
318
+ x = F.pad(x[:, :, :-1], (1, 0), value=max_value)
319
+ x = x.cummin(-1)[0]
320
+ return x
321
+
322
+ class Transformer(nn.Module):
323
+ """Transformer model."""
324
+
325
+ def __init__(self,
326
+ hidden_size,
327
+ nlayers,
328
+ ntokens,
329
+ nhead=8,
330
+ dropout=0.1,
331
+ dropatt=0.1,
332
+ relative_bias=True,
333
+ pos_emb=False,
334
+ pad=0):
335
+ """Initialization.
336
+
337
+ Args:
338
+ hidden_size: dimension of inputs and hidden states
339
+ nlayers: number of layers
340
+ ntokens: number of output categories
341
+ nhead: number of self-attention heads
342
+ dropout: dropout rate
343
+ dropatt: drop attention rate
344
+ relative_bias: bool, indicate whether use a relative position based
345
+ attention bias
346
+ pos_emb: bool, indicate whether use a learnable positional embedding
347
+ pad: pad token index
348
+ """
349
+
350
+ super(Transformer, self).__init__()
351
+
352
+ self.drop = nn.Dropout(dropout)
353
+
354
+ self.emb = nn.Embedding(ntokens, hidden_size)
355
+ if pos_emb:
356
+ self.pos_emb = nn.Embedding(500, hidden_size)
357
+
358
+ self.layers = nn.ModuleList([
359
+ TransformerLayer(hidden_size, nhead, hidden_size * 4, dropout,
360
+ dropatt=dropatt, relative_bias=relative_bias)
361
+ for _ in range(nlayers)])
362
+
363
+ self.norm = nn.LayerNorm(hidden_size)
364
+
365
+ self.output_layer = nn.Linear(hidden_size, ntokens)
366
+ self.output_layer.weight = self.emb.weight
367
+
368
+ self.init_weights()
369
+
370
+ self.nlayers = nlayers
371
+ self.nhead = nhead
372
+ self.ntokens = ntokens
373
+ self.hidden_size = hidden_size
374
+ self.pad = pad
375
+
376
+ def init_weights(self):
377
+ """Initialize token embedding and output bias."""
378
+ initrange = 0.1
379
+ self.emb.weight.data.uniform_(-initrange, initrange)
380
+ if hasattr(self, 'pos_emb'):
381
+ self.pos_emb.weight.data.uniform_(-initrange, initrange)
382
+ self.output_layer.bias.data.fill_(0)
383
+
384
+ def visibility(self, x, device):
385
+ """Mask pad tokens."""
386
+ visibility = (x != self.pad).float()
387
+ visibility = visibility[:, None, :].expand(-1, x.size(1), -1)
388
+ visibility = torch.repeat_interleave(visibility, self.nhead, dim=0)
389
+ return visibility.log()
390
+
391
+ def encode(self, x, pos):
392
+ """Standard transformer encode process."""
393
+ h = self.emb(x)
394
+ if hasattr(self, 'pos_emb'):
395
+ h = h + self.pos_emb(pos)
396
+ h_list = []
397
+ visibility = self.visibility(x, x.device)
398
+
399
+ for i in range(self.nlayers):
400
+ h_list.append(h)
401
+ h = self.layers[i](
402
+ h.transpose(0, 1), key_padding_mask=visibility).transpose(0, 1)
403
+
404
+ output = h
405
+ h_array = torch.stack(h_list, dim=2)
406
+
407
+ return output, h_array
408
+
409
+ def forward(self, x, pos):
410
+ """Pass the input through the encoder layer.
411
+
412
+ Args:
413
+ x: input tokens (required).
414
+ pos: position for each token (optional).
415
+ Returns:
416
+ output: probability distributions for missing tokens.
417
+ state_dict: parsing results and raw output
418
+ """
419
+
420
+ batch_size, length = x.size()
421
+
422
+ raw_output, _ = self.encode(x, pos)
423
+ raw_output = self.norm(raw_output)
424
+ raw_output = self.drop(raw_output)
425
+
426
+ output = self.output_layer(raw_output)
427
+ return output.view(batch_size * length, -1), {'raw_output': raw_output,}
428
+
429
+ class StructFormer(Transformer):
430
+ """StructFormer model."""
431
+
432
+ def __init__(self,
433
+ hidden_size,
434
+ nlayers,
435
+ ntokens,
436
+ nhead=8,
437
+ dropout=0.1,
438
+ dropatt=0.1,
439
+ relative_bias=False,
440
+ pos_emb=False,
441
+ pad=0,
442
+ n_parser_layers=4,
443
+ conv_size=9,
444
+ relations=('head', 'child'),
445
+ weight_act='softmax'):
446
+ """Initialization.
447
+
448
+ Args:
449
+ hidden_size: dimension of inputs and hidden states
450
+ nlayers: number of layers
451
+ ntokens: number of output categories
452
+ nhead: number of self-attention heads
453
+ dropout: dropout rate
454
+ dropatt: drop attention rate
455
+ relative_bias: bool, indicate whether use a relative position based
456
+ attention bias
457
+ pos_emb: bool, indicate whether use a learnable positional embedding
458
+ pad: pad token index
459
+ n_parser_layers: number of parsing layers
460
+ conv_size: convolution kernel size for parser
461
+ relations: relations that are used to compute self attention
462
+ weight_act: relations distribution activation function
463
+ """
464
+
465
+ super(StructFormer, self).__init__(
466
+ hidden_size,
467
+ nlayers,
468
+ ntokens,
469
+ nhead=nhead,
470
+ dropout=dropout,
471
+ dropatt=dropatt,
472
+ relative_bias=relative_bias,
473
+ pos_emb=pos_emb,
474
+ pad=pad)
475
+
476
+ self.parser_layers = nn.ModuleList([
477
+ nn.Sequential(Conv1d(hidden_size, conv_size),
478
+ nn.LayerNorm(hidden_size, elementwise_affine=False),
479
+ nn.Tanh()) for i in range(n_parser_layers)])
480
+
481
+ self.distance_ff = nn.Sequential(
482
+ Conv1d(hidden_size, 2),
483
+ nn.LayerNorm(hidden_size, elementwise_affine=False), nn.Tanh(),
484
+ nn.Linear(hidden_size, 1))
485
+
486
+ self.height_ff = nn.Sequential(
487
+ nn.Linear(hidden_size, hidden_size),
488
+ nn.LayerNorm(hidden_size, elementwise_affine=False), nn.Tanh(),
489
+ nn.Linear(hidden_size, 1))
490
+
491
+ n_rel = len(relations)
492
+ self._rel_weight = nn.Parameter(torch.zeros((nlayers, nhead, n_rel)))
493
+ self._rel_weight.data.normal_(0, 0.1)
494
+
495
+ self._scaler = nn.Parameter(torch.zeros(2))
496
+
497
+ self.n_parse_layers = n_parser_layers
498
+ self.weight_act = weight_act
499
+ self.relations = relations
500
+
501
+ @property
502
+ def scaler(self):
503
+ return self._scaler.exp()
504
+
505
+ @property
506
+ def rel_weight(self):
507
+ if self.weight_act == 'sigmoid':
508
+ return torch.sigmoid(self._rel_weight)
509
+ elif self.weight_act == 'softmax':
510
+ return torch.softmax(self._rel_weight, dim=-1)
511
+
512
+ def parse(self, x, pos):
513
+ """Parse input sentence.
514
+
515
+ Args:
516
+ x: input tokens (required).
517
+ pos: position for each token (optional).
518
+ Returns:
519
+ distance: syntactic distance
520
+ height: syntactic height
521
+ """
522
+
523
+ mask = (x != self.pad)
524
+ mask_shifted = F.pad(mask[:, 1:], (0, 1), value=0)
525
+
526
+ h = self.emb(x)
527
+ for i in range(self.n_parse_layers):
528
+ h = h.masked_fill(~mask[:, :, None], 0)
529
+ h = self.parser_layers[i](h)
530
+
531
+ height = self.height_ff(h).squeeze(-1)
532
+ height.masked_fill_(~mask, -1e9)
533
+
534
+ distance = self.distance_ff(h).squeeze(-1)
535
+ distance.masked_fill_(~mask_shifted, 1e9)
536
+
537
+ # Calbrating the distance and height to the same level
538
+ length = distance.size(1)
539
+ height_max = height[:, None, :].expand(-1, length, -1)
540
+ height_max = torch.cummax(
541
+ height_max.triu(0) - torch.ones_like(height_max).tril(-1) * 1e9,
542
+ dim=-1)[0].triu(0)
543
+
544
+ margin_left = torch.relu(
545
+ F.pad(distance[:, :-1, None], (0, 0, 1, 0), value=1e9) - height_max)
546
+ margin_right = torch.relu(distance[:, None, :] - height_max)
547
+ margin = torch.where(margin_left > margin_right, margin_right,
548
+ margin_left).triu(0)
549
+
550
+ margin_mask = torch.stack([mask_shifted] + [mask] * (length - 1), dim=1)
551
+ margin.masked_fill_(~margin_mask, 0)
552
+ margin = margin.max()
553
+
554
+ distance = distance - margin
555
+
556
+ return distance, height
557
+
558
+ def compute_block(self, distance, height):
559
+ """Compute constituents from distance and height."""
560
+
561
+ beta_logits = (distance[:, None, :] - height[:, :, None]) * self.scaler[0]
562
+
563
+ gamma = torch.sigmoid(-beta_logits)
564
+ ones = torch.ones_like(gamma)
565
+
566
+ block_mask_left = cummin(
567
+ gamma.tril(-1) + ones.triu(0), reverse=True, max_value=1)
568
+ block_mask_left = block_mask_left - F.pad(
569
+ block_mask_left[:, :, :-1], (1, 0), value=0)
570
+ block_mask_left.tril_(0)
571
+
572
+ block_mask_right = cummin(
573
+ gamma.triu(0) + ones.tril(-1), exclusive=True, max_value=1)
574
+ block_mask_right = block_mask_right - F.pad(
575
+ block_mask_right[:, :, 1:], (0, 1), value=0)
576
+ block_mask_right.triu_(0)
577
+
578
+ block_p = block_mask_left[:, :, :, None] * block_mask_right[:, :, None, :]
579
+ block = cumsum(block_mask_left).tril(0) + cumsum(
580
+ block_mask_right, reverse=True).triu(1)
581
+
582
+ return block_p, block
583
+
584
+ def compute_head(self, height):
585
+ """Estimate head for each constituent."""
586
+
587
+ _, length = height.size()
588
+ head_logits = height * self.scaler[1]
589
+ index = torch.arange(length, device=height.device)
590
+
591
+ mask = (index[:, None, None] <= index[None, None, :]) * (
592
+ index[None, None, :] <= index[None, :, None])
593
+ head_logits = head_logits[:, None, None, :].repeat(1, length, length, 1)
594
+ head_logits.masked_fill_(~mask[None, :, :, :], -1e9)
595
+
596
+ head_p = torch.softmax(head_logits, dim=-1)
597
+
598
+ return head_p
599
+
600
+ def generate_mask(self, x, distance, height):
601
+ """Compute head and cibling distribution for each token."""
602
+
603
+ bsz, length = x.size()
604
+
605
+ eye = torch.eye(length, device=x.device, dtype=torch.bool)
606
+ eye = eye[None, :, :].expand((bsz, -1, -1))
607
+
608
+ block_p, block = self.compute_block(distance, height)
609
+ head_p = self.compute_head(height)
610
+ head = torch.einsum('blij,bijh->blh', block_p, head_p)
611
+ head = head.masked_fill(eye, 0)
612
+ child = head.transpose(1, 2)
613
+ cibling = torch.bmm(head, child).masked_fill(eye, 0)
614
+
615
+ rel_list = []
616
+ if 'head' in self.relations:
617
+ rel_list.append(head)
618
+ if 'child' in self.relations:
619
+ rel_list.append(child)
620
+ if 'cibling' in self.relations:
621
+ rel_list.append(cibling)
622
+
623
+ rel = torch.stack(rel_list, dim=1)
624
+
625
+ rel_weight = self.rel_weight
626
+
627
+ dep = torch.einsum('lhr,brij->lbhij', rel_weight, rel)
628
+ att_mask = dep.reshape(self.nlayers, bsz * self.nhead, length, length)
629
+
630
+ return att_mask, cibling, head, block
631
+
632
+ def encode(self, x, pos, att_mask):
633
+ """Structformer encoding process."""
634
+
635
+ visibility = self.visibility(x, x.device)
636
+ h = self.emb(x)
637
+ if hasattr(self, 'pos_emb'):
638
+ assert pos.max() < 500
639
+ h = h + self.pos_emb(pos)
640
+ for i in range(self.nlayers):
641
+ h = self.layers[i](
642
+ h.transpose(0, 1), attn_mask=att_mask[i],
643
+ key_padding_mask=visibility).transpose(0, 1)
644
+ return h
645
+
646
+ def forward(self, x, pos):
647
+ """Pass the input through the encoder layer.
648
+
649
+ Args:
650
+ x: input tokens (required).
651
+ pos: position for each token (optional).
652
+ Returns:
653
+ output: probability distributions for missing tokens.
654
+ state_dict: parsing results and raw output
655
+ """
656
+
657
+ batch_size, length = x.size()
658
+
659
+ distance, height = self.parse(x, pos)
660
+ att_mask, cibling, head, block = self.generate_mask(x, distance, height)
661
+
662
+ raw_output = self.encode(x, pos, att_mask)
663
+ raw_output = self.norm(raw_output)
664
+ raw_output = self.drop(raw_output)
665
+
666
+ output = self.output_layer(raw_output)
667
+
668
+ return output.view(batch_size * length, -1), \
669
+ {'raw_output': raw_output, 'distance': distance, 'height': height,
670
+ 'cibling': cibling, 'head': head, 'block': block}
671
+
672
+
673
+ ##########################################
674
+ # Clasication Head For BabyLM Evaluation Tasks
675
+ ##########################################
676
+ class ClassificationHead(nn.Module):
677
+ """Head for sentence-level classification tasks."""
678
+ def __init__(self, config):
679
+ super(ClassificationHead, self).__init__()
680
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
681
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
682
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
683
+
684
+ def forward(self, features, **kwargs):
685
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
686
+ x = self.dropout(x)
687
+ x = self.dense(x)
688
+ x = torch.tanh(x)
689
+ x = self.dropout(x)
690
+ x = self.out_proj(x)
691
+ return x
692
+
693
+ ##########################################
694
+ # HuggingFace Config
695
+ ##########################################
696
+ class StructFormerConfig(PretrainedConfig):
697
+ model_type = "structformer"
698
+
699
+ def __init__(
700
+ self,
701
+ hidden_size=512,
702
+ nlayers=8,
703
+ ntokens=10_000,
704
+ nhead=8,
705
+ dropout=0.1,
706
+ dropatt=0.1,
707
+ relative_bias=False,
708
+ pos_emb=False,
709
+ pad=0,
710
+ n_parser_layers=4,
711
+ conv_size=9,
712
+ relations=('head', 'child'),
713
+ weight_act='softmax',
714
+ num_labels=1,
715
+ hidden_dropout_prob=0.1,
716
+ initializer_range=0.02,
717
+ **kwargs,
718
+ ):
719
+ self.hidden_size = hidden_size
720
+ self.nlayers = nlayers
721
+ self.ntokens = ntokens
722
+ self.nhead = nhead
723
+ self.dropout = dropout
724
+ self.dropatt = dropatt
725
+ self.relative_bias = relative_bias
726
+ self.pos_emb = pos_emb
727
+ self.pad = pad
728
+ self.n_parser_layers = n_parser_layers
729
+ self.conv_size = conv_size
730
+ self.relations = relations
731
+ self.weight_act = weight_act
732
+ self.num_labels = num_labels
733
+ self.hidden_dropout_prob = hidden_dropout_prob
734
+ self.initializer_range=initializer_range
735
+ super().__init__(**kwargs)
736
+
737
+ ##########################################
738
+ # HuggingFace Model
739
+ ##########################################
740
+ class StructFormerModel(PreTrainedModel):
741
+ config_class = StructFormerConfig
742
+
743
+ def __init__(self, config):
744
+ super().__init__(config)
745
+ self.model = StructFormer(
746
+ hidden_size=config.hidden_size,
747
+ nlayers=config.nlayers,
748
+ ntokens=config.ntokens,
749
+ nhead=config.nhead,
750
+ dropout=config.dropout,
751
+ dropatt=config.dropatt,
752
+ relative_bias=config.relative_bias,
753
+ pos_emb=config.pos_emb,
754
+ pad=config.pad,
755
+ n_parser_layers=config.n_parser_layers,
756
+ conv_size=config.conv_size,
757
+ relations=config.relations,
758
+ weight_act=config.weight_act
759
+ )
760
+ self.config = config
761
+
762
+ def parse(self, input_ids, **kwargs):
763
+ x = input_ids
764
+ batch_size, length = x.size()
765
+ pos = kwargs['position_ids'] if 'position_ids' in kwargs.keys() else torch.arange(length, device=x.device).expand(batch_size, length)
766
+
767
+ sf_output = self.model(x, pos)
768
+
769
+ return sf_output[1]
770
+
771
+ def forward(self, input_ids, labels=None, **kwargs):
772
+ x = input_ids
773
+ batch_size, length = x.size()
774
+ pos = kwargs['position_ids'] if 'position_ids' in kwargs.keys() else torch.arange(length, device=x.device).expand(batch_size, length)
775
+
776
+ sf_output = self.model(x, pos)
777
+
778
+ loss = None
779
+ if labels is not None:
780
+ loss_fct = nn.CrossEntropyLoss()
781
+ loss = loss_fct(sf_output[0], labels.reshape(-1))
782
+
783
+ return MaskedLMOutput(
784
+ loss=loss, # shape: 1
785
+ logits=sf_output[0].view(batch_size, length, -1), # shape: (batch_size, length, ntokens)
786
+ hidden_states=None,
787
+ attentions=None
788
+ )
789
+
790
+ class StructFormerModelForSequenceClassification(PreTrainedModel):
791
+ config_class = StructFormerConfig
792
+
793
+ def __init__(self, config):
794
+ super().__init__(config)
795
+ self.model = StructFormer(
796
+ hidden_size=config.hidden_size,
797
+ nlayers=config.nlayers,
798
+ ntokens=config.ntokens,
799
+ nhead=config.nhead,
800
+ dropout=config.dropout,
801
+ dropatt=config.dropatt,
802
+ relative_bias=config.relative_bias,
803
+ pos_emb=config.pos_emb,
804
+ pad=config.pad,
805
+ n_parser_layers=config.n_parser_layers,
806
+ conv_size=config.conv_size,
807
+ relations=config.relations,
808
+ weight_act=config.weight_act
809
+ )
810
+ self.config = config
811
+ self.num_labels = config.num_labels
812
+ self.model.classifier = ClassificationHead(config)
813
+
814
+ def _init_weights(self, module):
815
+ """Initialize the weights"""
816
+ if isinstance(module, nn.Linear):
817
+ # Slightly different from the TF version which uses truncated_normal for initialization
818
+ # cf https://github.com/pytorch/pytorch/pull/5617
819
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
820
+ if module.bias is not None:
821
+ module.bias.data.zero_()
822
+ elif isinstance(module, nn.Embedding):
823
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
824
+ if module.padding_idx is not None:
825
+ module.weight.data[module.padding_idx].zero_()
826
+ elif isinstance(module, nn.LayerNorm):
827
+ if module.bias is not None:
828
+ module.bias.data.zero_()
829
+ module.weight.data.fill_(1.0)
830
+
831
+ def forward(self, input_ids, labels=None, **kwargs):
832
+ x = input_ids
833
+ batch_size, length = x.size()
834
+ pos = kwargs['position_ids'] if 'position_ids' in kwargs.keys() else torch.arange(length, device=x.device).expand(batch_size, length)
835
+
836
+ sf_output = self.model(x, pos)
837
+
838
+ logits = self.model.classifier(sf_output[1]['raw_output'])
839
+ loss = None
840
+ if labels is not None:
841
+ if self.config.problem_type is None:
842
+ if self.num_labels == 1:
843
+ self.config.problem_type = "regression"
844
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
845
+ self.config.problem_type = "single_label_classification"
846
+ else:
847
+ self.config.problem_type = "multi_label_classification"
848
+
849
+ if self.config.problem_type == "regression":
850
+ loss_fct = nn.MSELoss()
851
+ if self.num_labels == 1:
852
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
853
+ else:
854
+ loss = loss_fct(logits, labels)
855
+ elif self.config.problem_type == "single_label_classification":
856
+ loss_fct = nn.CrossEntropyLoss()
857
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
858
+ elif self.config.problem_type == "multi_label_classification":
859
+ loss_fct = nn.BCEWithLogitsLoss()
860
+ loss = loss_fct(logits, labels)
861
+
862
+ return SequenceClassifierOutput(
863
+ loss=loss,
864
+ logits=logits,
865
+ hidden_states=None,
866
+ attentions=None,
867
+ )
finetune/cola/tokenizer_config.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "bos_token": {
4
+ "__type": "AddedToken",
5
+ "content": "<s>",
6
+ "lstrip": false,
7
+ "normalized": true,
8
+ "rstrip": false,
9
+ "single_word": false
10
+ },
11
+ "cls_token": {
12
+ "__type": "AddedToken",
13
+ "content": "<s>",
14
+ "lstrip": false,
15
+ "normalized": true,
16
+ "rstrip": false,
17
+ "single_word": false
18
+ },
19
+ "eos_token": {
20
+ "__type": "AddedToken",
21
+ "content": "</s>",
22
+ "lstrip": false,
23
+ "normalized": true,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ },
27
+ "errors": "replace",
28
+ "mask_token": {
29
+ "__type": "AddedToken",
30
+ "content": "<mask>",
31
+ "lstrip": true,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false
35
+ },
36
+ "model_max_length": 512,
37
+ "name_or_path": "omarmomen/sf_babylm_1",
38
+ "pad_token": {
39
+ "__type": "AddedToken",
40
+ "content": "<pad>",
41
+ "lstrip": false,
42
+ "normalized": true,
43
+ "rstrip": false,
44
+ "single_word": false
45
+ },
46
+ "sep_token": {
47
+ "__type": "AddedToken",
48
+ "content": "</s>",
49
+ "lstrip": false,
50
+ "normalized": true,
51
+ "rstrip": false,
52
+ "single_word": false
53
+ },
54
+ "special_tokens_map_file": null,
55
+ "tokenizer_class": "RobertaTokenizer",
56
+ "trim_offsets": true,
57
+ "unk_token": {
58
+ "__type": "AddedToken",
59
+ "content": "<unk>",
60
+ "lstrip": false,
61
+ "normalized": true,
62
+ "rstrip": false,
63
+ "single_word": false
64
+ }
65
+ }
finetune/cola/train_results.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 10.0,
3
+ "train_loss": 0.3184558808803558,
4
+ "train_runtime": 219.0841,
5
+ "train_samples": 8164,
6
+ "train_samples_per_second": 372.642,
7
+ "train_steps_per_second": 5.843
8
+ }
finetune/cola/trainer_state.json ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": 0.8219339622641509,
3
+ "best_model_checkpoint": "omarmomen/sf_babylm_1/finetune/cola/checkpoint-200",
4
+ "epoch": 10.0,
5
+ "global_step": 1280,
6
+ "is_hyper_param_search": false,
7
+ "is_local_process_zero": true,
8
+ "is_world_process_zero": true,
9
+ "log_history": [
10
+ {
11
+ "epoch": 1.56,
12
+ "eval_accuracy": 0.7036309838294983,
13
+ "eval_f1": 0.8219339622641509,
14
+ "eval_loss": 0.6300716400146484,
15
+ "eval_mcc": 0.13076987235140602,
16
+ "eval_runtime": 1.2993,
17
+ "eval_samples_per_second": 784.268,
18
+ "eval_steps_per_second": 98.515,
19
+ "step": 200
20
+ },
21
+ {
22
+ "epoch": 3.12,
23
+ "eval_accuracy": 0.6997056007385254,
24
+ "eval_f1": 0.8048469387755102,
25
+ "eval_loss": 0.6442329287528992,
26
+ "eval_mcc": 0.19657323093149748,
27
+ "eval_runtime": 1.4161,
28
+ "eval_samples_per_second": 719.591,
29
+ "eval_steps_per_second": 90.39,
30
+ "step": 400
31
+ },
32
+ {
33
+ "epoch": 3.91,
34
+ "learning_rate": 3.0468750000000002e-05,
35
+ "loss": 0.511,
36
+ "step": 500
37
+ },
38
+ {
39
+ "epoch": 4.69,
40
+ "eval_accuracy": 0.708537757396698,
41
+ "eval_f1": 0.8109484404837684,
42
+ "eval_loss": 0.8354039192199707,
43
+ "eval_mcc": 0.22128351240839433,
44
+ "eval_runtime": 1.3442,
45
+ "eval_samples_per_second": 758.05,
46
+ "eval_steps_per_second": 95.221,
47
+ "step": 600
48
+ },
49
+ {
50
+ "epoch": 6.25,
51
+ "eval_accuracy": 0.7144259214401245,
52
+ "eval_f1": 0.8138195777351248,
53
+ "eval_loss": 1.0478105545043945,
54
+ "eval_mcc": 0.2432614865937686,
55
+ "eval_runtime": 1.3221,
56
+ "eval_samples_per_second": 770.731,
57
+ "eval_steps_per_second": 96.814,
58
+ "step": 800
59
+ },
60
+ {
61
+ "epoch": 7.81,
62
+ "learning_rate": 1.09375e-05,
63
+ "loss": 0.2308,
64
+ "step": 1000
65
+ },
66
+ {
67
+ "epoch": 7.81,
68
+ "eval_accuracy": 0.7095191478729248,
69
+ "eval_f1": 0.8097686375321337,
70
+ "eval_loss": 1.1782832145690918,
71
+ "eval_mcc": 0.23273105838579872,
72
+ "eval_runtime": 1.3212,
73
+ "eval_samples_per_second": 771.289,
74
+ "eval_steps_per_second": 96.884,
75
+ "step": 1000
76
+ },
77
+ {
78
+ "epoch": 9.38,
79
+ "eval_accuracy": 0.7144259214401245,
80
+ "eval_f1": 0.8135810377962844,
81
+ "eval_loss": 1.2869043350219727,
82
+ "eval_mcc": 0.24432326576634322,
83
+ "eval_runtime": 1.3121,
84
+ "eval_samples_per_second": 776.633,
85
+ "eval_steps_per_second": 97.555,
86
+ "step": 1200
87
+ },
88
+ {
89
+ "epoch": 10.0,
90
+ "step": 1280,
91
+ "total_flos": 2092145921249280.0,
92
+ "train_loss": 0.3184558808803558,
93
+ "train_runtime": 219.0841,
94
+ "train_samples_per_second": 372.642,
95
+ "train_steps_per_second": 5.843
96
+ }
97
+ ],
98
+ "max_steps": 1280,
99
+ "num_train_epochs": 10,
100
+ "total_flos": 2092145921249280.0,
101
+ "trial_name": null,
102
+ "trial_params": null
103
+ }
finetune/cola/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c43ff5a8741c4285a95db833f1cab13594ae1c36859759e5123678abf6a7eba3
3
+ size 3960
finetune/cola/vocab.json ADDED
The diff for this file is too large to render. See raw diff