garrethlee HF staff commited on
Commit
28084d9
1 Parent(s): 6a7eee7

Create comprehensive-arithmetic-problems-carries.py

Browse files
comprehensive-arithmetic-problems-carries.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Adapted from https://github.com/maxwbuckley/r2ltokenizing/blob/main/llmarithmetic.py; with modifications
2
+ import random
3
+ from datasets import (
4
+ BuilderConfig,
5
+ SplitGenerator,
6
+ GeneratorBasedBuilder,
7
+ DatasetInfo,
8
+ Value,
9
+ Features,
10
+ )
11
+ from decimal import Decimal
12
+ import yaml
13
+
14
+ SEED = 42
15
+ TEST_SIZE = 0.2
16
+ DIVISION_RESULT_MULTIPLIER = 4
17
+ FLOAT_FLOAT_PROBLEM_PROPORTION = 0.3
18
+
19
+ _CITATION = """\
20
+ @misc{lee2024arithmeticproblemsdataset,
21
+ title = {Arithmetic Problems},
22
+ author={Garreth Lee},
23
+ year={2024}
24
+ }
25
+ """
26
+
27
+
28
+
29
+ class Operator:
30
+ ADD = "+"
31
+ SUBTRACT = "-"
32
+ MULTIPLY = "*"
33
+ DIVIDE = "/"
34
+
35
+ OPERATORS = [ADD, SUBTRACT, MULTIPLY, DIVIDE]
36
+
37
+ @classmethod
38
+ def is_operator(cls, value):
39
+ return value in cls.OPERATORS
40
+
41
+ @classmethod
42
+ def operator_to_name(cls, value):
43
+ if value == cls.ADD:
44
+ return "add"
45
+ elif value == cls.SUBTRACT:
46
+ return "subtract"
47
+ elif value == cls.MULTIPLY:
48
+ return "multiply"
49
+ elif value == cls.DIVIDE:
50
+ return "divide"
51
+ else:
52
+ raise ValueError(f"Invalid operator: {value}")
53
+
54
+
55
+ class OperationType:
56
+ INT_INT = [False, False]
57
+ INT_FLOAT = [True, False]
58
+ FLOAT_FLOAT = [True, True]
59
+
60
+ class ArithmeticProblemsConfig(BuilderConfig):
61
+ def __init__(
62
+ self,
63
+ name: str,
64
+ num_problems: int,
65
+ min_exponent: int,
66
+ max_exponent: int,
67
+ max_rounding_precision: int,
68
+ with_carry: bool,
69
+ use_commas: bool = False,
70
+ **kwargs,
71
+ ):
72
+ super().__init__(name=name)
73
+ self.num_problems = num_problems
74
+ self.min_exponent = min_exponent
75
+ self.max_exponent = max_exponent
76
+ self.max_rounding_precision = max_rounding_precision
77
+ self.use_commas = use_commas
78
+ self.with_carry = with_carry
79
+ self.kwargs = kwargs
80
+
81
+
82
+ class ArithmeticProblemsDataset(GeneratorBasedBuilder):
83
+ BUILDER_CONFIG_CLASS = ArithmeticProblemsConfig
84
+ FLOAT_ANSWER_ROUNDING_PRECISION = 4
85
+
86
+ BUILDER_CONFIGS = [
87
+ ArithmeticProblemsConfig(
88
+ name=f"{i}-digit{'-with-carry' if with_carry else ''}",
89
+ num_problems=5000,
90
+ min_exponent=i-1,
91
+ max_exponent=i,
92
+ max_rounding_precision=max(i-1, 10),
93
+ with_carry=with_carry,
94
+ ) for i in range(1, 21) for with_carry in [False, True]
95
+ ]
96
+
97
+ VERSION = "1.0.0"
98
+
99
+ def _info(self):
100
+ return DatasetInfo(
101
+ description="Generate arithmetic problems for use in math tokenization",
102
+ features=Features(
103
+ {
104
+ "question": Value("string"),
105
+ "answer": Value("string"),
106
+ "operator": Value("string"),
107
+ }
108
+ ),
109
+ citation=_CITATION,
110
+ )
111
+
112
+ def _generate_number(
113
+ self, min_val: int, max_val: int, is_float: bool, max_rounding_precision: int
114
+ ) -> float | int:
115
+ """
116
+ Generates a random number within a specified range, either as an integer or float.
117
+
118
+ Args:
119
+ min_val: The minimum value of the range.
120
+ max_val: The maximum value of the range.
121
+ is_float: If true, generates a float
122
+ max_rounding_precision: The maximum precision to use when rounding the number.
123
+
124
+ Returns:
125
+ A random number within the specified range, either as an int or a float.
126
+ """
127
+ if is_float:
128
+ # Round to a random precision between 0 and max_rounding_precision
129
+ return round(
130
+ random.uniform(min_val, max_val),
131
+ random.choice(range(1, max_rounding_precision + 1)),
132
+ )
133
+ else:
134
+ return random.randint(min_val, max_val)
135
+
136
+ def _format_number(self, number: int | float, use_commas: bool = False) -> str:
137
+ """
138
+ Rounds a number to a specified precision, and then formats it as a string.
139
+
140
+ Args:
141
+ number: The number to be formatted.
142
+ use_commas: Whether to include commas as thousand separators.
143
+
144
+ Returns:
145
+ A string representation of the input number, rounded to the specified precision.
146
+ """
147
+ if use_commas:
148
+ return "{:,}".format(number)
149
+ else:
150
+ return str(number)
151
+
152
+ def _construct_equation(
153
+ self,
154
+ operand1: int | float,
155
+ operand2: int | float,
156
+ operator: str,
157
+ use_commas: bool = False,
158
+ ) -> str:
159
+ """Helper function for constructing the string equations."""
160
+
161
+ return "%s %s %s = " % (
162
+ self._format_number(operand1, use_commas),
163
+ operator,
164
+ self._format_number(operand2, use_commas),
165
+ )
166
+
167
+ def create_question_answer_pair(
168
+ self,
169
+ min_value: int,
170
+ max_value: int,
171
+ operator: str,
172
+ use_commas: bool,
173
+ operation_type: list[bool],
174
+ with_carry: bool,
175
+ max_rounding_precision: int | None,
176
+ ) -> dict[str, str]:
177
+ """Creates a random question and correct answer pair.
178
+
179
+ Args:
180
+ min_value: The lowest possible random value.
181
+ max_value: The highest possible random value.
182
+ include_decimals: Whether to include float numbers in the generated problems.
183
+ operator: The mathematical operator to use.
184
+ use_commas: Whether to use commas to separate numbers right-to-left.
185
+
186
+ Returns:
187
+ A dictionary containing the equation string and the expected answer.
188
+ """
189
+ if not Operator.is_operator(operator):
190
+ raise ValueError(f"Invalid operator: {operator}")
191
+
192
+ is_float1, is_float2 = operation_type
193
+ operand1 = self._generate_number(
194
+ min_val=min_value,
195
+ max_val=max_value,
196
+ is_float=is_float1,
197
+ max_rounding_precision=max_rounding_precision,
198
+ )
199
+ if with_carry:
200
+ # for testing addition
201
+ operand2 = self._generate_number(
202
+ min_val=min_value,
203
+ max_val=max_value - operand1 - 1,
204
+ is_float=is_float2,
205
+ max_rounding_precision=max_rounding_precision,
206
+ )
207
+
208
+ if operator == Operator.SUBTRACT:
209
+ result = operand1 - operand2
210
+ elif operator == Operator.ADD:
211
+ result = operand1 + operand2
212
+ elif operator == Operator.MULTIPLY:
213
+ result = operand1 * operand2
214
+ else:
215
+ # this prevents a lot of "0" answers from being generated
216
+ if operand1 < operand2 or random.random() < 0.01:
217
+ operand1, operand2 = operand2, operand1
218
+
219
+ if operation_type == OperationType.INT_INT:
220
+ tmp = operand1 / operand2
221
+
222
+ # we scale the temp result up to prevent a lot of "small divisions"
223
+ if tmp < 10:
224
+ tmp *= DIVISION_RESULT_MULTIPLIER
225
+ if max_value > 999:
226
+ tmp *= random.randint(2, 4)
227
+
228
+ # prevents zero division
229
+ operand1 = int(round(tmp)) * operand2
230
+ result = int(operand1 / operand2)
231
+
232
+ elif operation_type == OperationType.INT_FLOAT:
233
+ operand2 = int(operand2)
234
+ tmp = round(
235
+ operand1 / operand2,
236
+ random.randint(1, max_rounding_precision),
237
+ )
238
+
239
+ # we scale the temp result up to prevent a lot of "small divisions"
240
+ if tmp < 10:
241
+ tmp = float(
242
+ Decimal(str(tmp)) * Decimal(str(DIVISION_RESULT_MULTIPLIER))
243
+ )
244
+
245
+ # deals with Python's decimal multiplication precision issue
246
+ operand1 = float(Decimal(str(tmp)) * Decimal(str(operand2)))
247
+ result = tmp
248
+
249
+ else:
250
+ tmp = round(
251
+ operand1 / operand2, random.randint(1, max_rounding_precision)
252
+ )
253
+
254
+ # we scale the temp result up to prevent a lot of "small divisions"
255
+ if tmp < 10:
256
+ tmp = float(
257
+ Decimal(str(tmp)) * Decimal(str(DIVISION_RESULT_MULTIPLIER))
258
+ )
259
+
260
+ # deals with Python's decimal multiplication precision issue
261
+ operand1 = float(Decimal(str(tmp)) * Decimal(str(operand2)))
262
+ result = tmp
263
+
264
+ result = round(result, self.FLOAT_ANSWER_ROUNDING_PRECISION)
265
+
266
+ question = self._construct_equation(
267
+ operand1=operand1,
268
+ operand2=operand2,
269
+ operator=operator,
270
+ use_commas=use_commas,
271
+ )
272
+ answer = self._format_number(result, use_commas)
273
+
274
+ return {"question": question, "answer": answer, "operator": operator}
275
+
276
+ def _split_generators(self, dl_manager, **kwargs) -> list[SplitGenerator]:
277
+ generators = []
278
+
279
+ for operator in Operator.OPERATORS:
280
+ # Create separate splits for each type of number
281
+ for type in ("int", "float"):
282
+ split_name = f"{type}_{Operator.operator_to_name(operator)}"
283
+
284
+ train_generator = SplitGenerator(
285
+ name=split_name + "_train",
286
+ gen_kwargs={
287
+ "num_problems": int(self.config.num_problems * (1 - TEST_SIZE)),
288
+ "min_value": 10**self.config.min_exponent,
289
+ "max_value": 10**self.config.max_exponent,
290
+ "max_rounding_precision": self.config.max_rounding_precision
291
+ if type == "float"
292
+ else None,
293
+ "use_commas": self.config.use_commas,
294
+ "operator": operator,
295
+ "with_carry": self.config.with_carry,
296
+ },
297
+ )
298
+
299
+ test_generator = SplitGenerator(
300
+ name=split_name + "_test",
301
+ gen_kwargs={
302
+ "num_problems": int(self.config.num_problems * TEST_SIZE),
303
+ "min_value": 10**self.config.min_exponent,
304
+ "max_value": 10**self.config.max_exponent,
305
+ "max_rounding_precision": self.config.max_rounding_precision
306
+ if type == "float"
307
+ else None,
308
+ "use_commas": self.config.use_commas,
309
+ "operator": operator,
310
+ "with_carry": self.config.with_carry,
311
+ },
312
+ )
313
+
314
+ generators.append(train_generator)
315
+ generators.append(test_generator)
316
+
317
+ return generators
318
+
319
+ def _generate_examples(
320
+ self,
321
+ num_problems,
322
+ min_value,
323
+ max_value,
324
+ max_rounding_precision,
325
+ use_commas,
326
+ operator,
327
+ with_carry,
328
+ ):
329
+ def _get_operation_type(current_idx: int):
330
+ # If max_rounding_precision is None, generate only integer problems
331
+ """
332
+ Determines the type of operation (integer-integer, float-float, or integer-float)
333
+ to generate based on the current index and the proportion of float problems.
334
+
335
+ Args:
336
+ current_idx: The current index of the problem being generated.
337
+ num_problems: The total number of problems to generate.
338
+ max_rounding_precision: The maximum rounding precision to use when generating float problems.
339
+
340
+ Returns:
341
+ An OperationType indicating the type of operation to generate.
342
+ """
343
+ if max_rounding_precision is None:
344
+ return OperationType.INT_INT
345
+
346
+ # Otherwise, if the current index is less than the float problem proportion,
347
+ elif current_idx < num_problems * FLOAT_FLOAT_PROBLEM_PROPORTION:
348
+ return OperationType.FLOAT_FLOAT
349
+
350
+ else:
351
+ return OperationType.INT_FLOAT
352
+
353
+ random.seed(SEED)
354
+
355
+ for i in range(num_problems):
356
+ yield (
357
+ str(i),
358
+ self.create_question_answer_pair(
359
+ min_value=min_value,
360
+ max_value=max_value,
361
+ operator=operator,
362
+ use_commas=use_commas,
363
+ operation_type=_get_operation_type(i),
364
+ with_carry=with_carry,
365
+ max_rounding_precision=max_rounding_precision,
366
+ ),
367
+ )