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
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import torch
from transformers.models.bert.modeling_bert import BertModel, BertPreTrainedModel
from torch import nn
from itertools import chain
from torch.nn import MSELoss, CrossEntropyLoss
from cleantext import clean
from num2words import num2words
import re
import string

punct_chars = list((set(string.punctuation) | {'’', '‘', '–', '—', '~', '|', '“', '”', '…', "'", "`", '_'}))
punct_chars.sort()
punctuation = ''.join(punct_chars)
replace = re.compile('[%s]' % re.escape(punctuation))

MATH_PREFIXES = [ 
    "sum",
    "arc",
    "mass",
    "digit",
    "graph",
    "liter",
    "gram",
    "add",
    "angle",
    "scale",
    "data",
    "array",
    "ruler",
    "meter",
    "total",
    "unit",
    "prism",
    "median",
    "ratio",
    "area",
]

MATH_WORDS = [
    "absolute value",
    "algebra",
    "area",
    "average",
    "base of",
    "box plot",
    "categorical",
    "coefficient",
    "common factor",
    "common multiple",
    "compose",
    "coordinate",
    "cubed",
    "decompose",
    "dependent variable",
    "distribution",
    "dot plot",
    "double number line diagram",
    "equivalent",
    "equivalent expression",
    "ratio",
    "exponent",
    "frequency",
    "greatest common factor",
    "gcd",
    "height of",
    "histogram",
    "independent variable",
    "integer",
    "interquartile range",
    "iqr",
    "least common multiple",
    "long division",
    "mean absolute deviation",
    "median",
    "negative number",
    "opposite vertex",
    "parallelogram",
    "percent",
    "polygon",
    "polyhedron",
    "positive number",
    "prism",
    "pyramid",
    "quadrant",
    "quadrilateral",
    "quartile",
    "rational number",
    "reciprocal",
    "equality",
    "inequality",
    "squared",
    "statistic",
    "surface area",
    "identity property",
    "addend",
    "unit",
    "number sentence",
    "make ten",
    "take from ten",
    "number bond",
    "total",
    "estimate",
    "hashmark",
    "meter",
    "number line",
    "ruler",
    "centimeter",
    "base ten",
    "expanded form",
    "hundred",
    "thousand",
    "place value",
    "number disk",
    "standard form",
    "unit form",
    "word form",
    "tens place",
    "algorithm",
    "equation",
    "simplif",
    "addition",
    "subtract",
    "array",
    "even number",
    "odd number",
    "repeated addition",
    "tessellat",
    "whole number",
    "number path",
    "rectangle",
    "square",
    "bar graph",
    "data",
    "degree",
    "line plot",
    "picture graph",
    "scale",
    "survey",
    "thermometer",
    "estimat",
    "tape diagram",
    "value",
    "analog",
    "angle",
    "parallel",
    "partition",
    "pentagon",
    "right angle",
    "cube",
    "digital",
    "quarter of",
    "tangram",
    "circle",
    "hexagon",
    "half circle",
    "half-circle",
    "quarter circle",
    "quarter-circle",
    "semicircle",
    "semi-circle",
    "rectang",
    "rhombus",
    "trapezoid",
    "triangle",
    "commutative",
    "equal group",
    "distributive",
    "divide",
    "division",
    "multipl",
    "parentheses",
    "quotient",
    "rotate",
    "unknown",
    "add",
    "capacity",
    "continuous",
    "endpoint",
    "gram",
    "interval",
    "kilogram",
    "volume",
    "liter",
    "milliliter",
    "approximate",
    "area model",
    "square unit",
    "unit square",
    "geometr",
    "equivalent fraction",
    "fraction form",
    "fractional unit",
    "unit fraction",
    "unit interval",
    "measur",
    "graph",
    "scaled graph",
    "diagonal",
    "perimeter",
    "regular polygon",
    "tessellate",
    "tetromino",
    "heptagon",
    "octagon",
    "digit",
    "expression",
    "sum",
    "kilometer",
    "mass",
    "mixed unit",
    "length",
    "measure",
    "simplify",
    "associative",
    "composite",
    "divisible",
    "divisor",
    "partial product",
    "prime number",
    "remainder",
    "acute",
    "arc",
    "collinear",
    "equilateral",
    "intersect",
    "isosceles",
    "symmetry",
    "line segment",
    "line",
    "obtuse",
    "perpendicular",
    "protractor",
    "scalene",
    "straight angle",
    "supplementary angle",
    "vertex",
    "common denominator",
    "denominator",
    "fraction",
    "mixed number",
    "numerator",
    "whole",
    "decimal expanded form",
    "decimal",
    "hundredth",
    "tenth",
    "customary system of measurement",
    "customary unit",
    "gallon",
    "metric",
    "metric unit",
    "ounce",
    "pint",
    "quart",
    "convert",
    "distance",
    "millimeter",
    "thousandth",
    "hundredths",
    "conversion factor",
    "decimal fraction",
    "multiplier",
    "equivalence",
    "multiple",
    "product",
    "benchmark fraction",
    "cup",
    "pound",
    "yard",
    "whole unit",
    "decimal divisor",
    "factors",
    "bisect",
    "cubic units",
    "hierarchy",
    "unit cube",
    "attribute",
    "kite",
    "bisector",
    "solid figure",
    "square units",
    "dimension",
    "axis",
    "ordered pair",
    "angle measure",
    "horizontal",
    "vertical",
    "categorical data",
    "lcm",
    "measure of center",
    "meters per second",
    "numerical",
    "solution",
    "unit price",
    "unit rate",
    "variability",
    "variable",
]

def get_num_words(text):
    if not isinstance(text, str):
        print("%s is not a string" % text)
    text = replace.sub(' ', text)
    text = re.sub(r'\s+', ' ', text)
    text = text.strip()
    text = re.sub(r'\[.+\]', " ", text)
    return len(text.split())

def number_to_words(num):
    try:
        return num2words(re.sub(",", "", num))
    except:
        return num


clean_str = lambda s: clean(s,
                            fix_unicode=True,  # fix various unicode errors
                            to_ascii=True,  # transliterate to closest ASCII representation
                            lower=True,  # lowercase text
                            no_line_breaks=True,  # fully strip line breaks as opposed to only normalizing them
                            no_urls=True,  # replace all URLs with a special token
                            no_emails=True,  # replace all email addresses with a special token
                            no_phone_numbers=True,  # replace all phone numbers with a special token
                            no_numbers=True,  # replace all numbers with a special token
                            no_digits=False,  # replace all digits with a special token
                            no_currency_symbols=False,  # replace all currency symbols with a special token
                            no_punct=False,  # fully remove punctuation
                            replace_with_url="<URL>",
                            replace_with_email="<EMAIL>",
                            replace_with_phone_number="<PHONE>",
                            replace_with_number=lambda m: number_to_words(m.group()),
                            replace_with_digit="0",
                            replace_with_currency_symbol="<CUR>",
                            lang="en"
                            )

clean_str_nopunct = lambda s: clean(s,
                            fix_unicode=True,  # fix various unicode errors
                            to_ascii=True,  # transliterate to closest ASCII representation
                            lower=True,  # lowercase text
                            no_line_breaks=True,  # fully strip line breaks as opposed to only normalizing them
                            no_urls=True,  # replace all URLs with a special token
                            no_emails=True,  # replace all email addresses with a special token
                            no_phone_numbers=True,  # replace all phone numbers with a special token
                            no_numbers=True,  # replace all numbers with a special token
                            no_digits=False,  # replace all digits with a special token
                            no_currency_symbols=False,  # replace all currency symbols with a special token
                            no_punct=True,  # fully remove punctuation
                            replace_with_url="<URL>",
                            replace_with_email="<EMAIL>",
                            replace_with_phone_number="<PHONE>",
                            replace_with_number=lambda m: number_to_words(m.group()),
                            replace_with_digit="0",
                            replace_with_currency_symbol="<CUR>",
                            lang="en"
                            )



class MultiHeadModel(BertPreTrainedModel):
  """Pre-trained BERT model that uses our loss functions"""

  def __init__(self, config, head2size):
    super(MultiHeadModel, self).__init__(config, head2size)
    config.num_labels = 1
    self.bert = BertModel(config)
    self.dropout = nn.Dropout(config.hidden_dropout_prob)
    module_dict = {}
    for head_name, num_labels in head2size.items():
      module_dict[head_name] = nn.Linear(config.hidden_size, num_labels)
    self.heads = nn.ModuleDict(module_dict)

    self.init_weights()

  def forward(self, input_ids, token_type_ids=None, attention_mask=None,
              head2labels=None, return_pooler_output=False, head2mask=None,
              nsp_loss_weights=None):

    device = "cuda" if torch.cuda.is_available() else "cpu"

    # Get logits
    output = self.bert(
      input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask,
      output_attentions=False, output_hidden_states=False, return_dict=True)
    pooled_output = self.dropout(output["pooler_output"]).to(device)

    head2logits = {}
    return_dict = {}
    for head_name, head in self.heads.items():
      head2logits[head_name] = self.heads[head_name](pooled_output)
      head2logits[head_name] = head2logits[head_name].float()
      return_dict[head_name + "_logits"] = head2logits[head_name]


    if head2labels is not None:
      for head_name, labels in head2labels.items():
        num_classes = head2logits[head_name].shape[1]

        # Regression (e.g. for politeness)
        if num_classes == 1:

          # Only consider positive examples
          if head2mask is not None and head_name in head2mask:
            num_positives = head2labels[head2mask[head_name]].sum()  # use certain labels as mask
            if num_positives == 0:
              return_dict[head_name + "_loss"] = torch.tensor([0]).to(device)
            else:
              loss_fct = MSELoss(reduction='none')
              loss = loss_fct(head2logits[head_name].view(-1), labels.float().view(-1))
              return_dict[head_name + "_loss"] = loss.dot(head2labels[head2mask[head_name]].float().view(-1)) / num_positives
          else:
            loss_fct = MSELoss()
            return_dict[head_name + "_loss"] = loss_fct(head2logits[head_name].view(-1), labels.float().view(-1))
        else:
          loss_fct = CrossEntropyLoss(weight=nsp_loss_weights.float())
          return_dict[head_name + "_loss"] = loss_fct(head2logits[head_name], labels.view(-1))


    if return_pooler_output:
      return_dict["pooler_output"] = output["pooler_output"]

    return return_dict

class InputBuilder(object):
  """Base class for building inputs from segments."""

  def __init__(self, tokenizer):
      self.tokenizer = tokenizer
      self.mask = [tokenizer.mask_token_id]

  def build_inputs(self, history, reply, max_length):
      raise NotImplementedError

  def mask_seq(self, sequence, seq_id):
      sequence[seq_id] = self.mask
      return sequence

  @classmethod
  def _combine_sequence(self, history, reply, max_length, flipped=False):
      # Trim all inputs to max_length
      history = [s[:max_length] for s in history]
      reply = reply[:max_length]
      if flipped:
          return [reply] + history
      return history + [reply]


class BertInputBuilder(InputBuilder):
  """Processor for BERT inputs"""

  def __init__(self, tokenizer):
      InputBuilder.__init__(self, tokenizer)
      self.cls = [tokenizer.cls_token_id]
      self.sep = [tokenizer.sep_token_id]
      self.model_inputs = ["input_ids", "token_type_ids", "attention_mask"]
      self.padded_inputs = ["input_ids", "token_type_ids"]
      self.flipped = False


  def build_inputs(self, history, reply, max_length, input_str=True):
    """See base class."""
    if input_str:
        history = [self.tokenizer.convert_tokens_to_ids(self.tokenizer.tokenize(t)) for t in history]
        reply = self.tokenizer.convert_tokens_to_ids(self.tokenizer.tokenize(reply))
    sequence = self._combine_sequence(history, reply, max_length, self.flipped)
    sequence = [s + self.sep for s in sequence]
    sequence[0] = self.cls + sequence[0]

    instance = {}
    instance["input_ids"] = list(chain(*sequence))
    last_speaker = 0
    other_speaker = 1
    seq_length = len(sequence)
    instance["token_type_ids"] = [last_speaker if ((seq_length - i) % 2 == 1) else other_speaker
                                  for i, s in enumerate(sequence) for _ in s]
    return instance