garrethlee commited on
Commit
b62a43a
·
verified ·
1 Parent(s): 4e95c35

Delete loading script

Browse files
comprehensive-arithmetic-problems-carries.py DELETED
@@ -1,404 +0,0 @@
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
- # for testing addition
200
- operand2 = self._generate_number(
201
- min_val=min_value,
202
- max_val=max_value,
203
- is_float=is_float2,
204
- max_rounding_precision=max_rounding_precision,
205
- )
206
-
207
- if operator == Operator.SUBTRACT:
208
- result = operand1 - operand2
209
- elif operator == Operator.ADD:
210
- if with_carry:
211
- while True:
212
- try:
213
- operand1 = self._generate_number(
214
- min_val=min_value,
215
- max_val=max_value,
216
- is_float=is_float1,
217
- max_rounding_precision=max_rounding_precision,
218
- )
219
- # for testing addition
220
- operand2 = self._generate_number(
221
- min_val=max_value - operand1 ,
222
- max_val=max_value,
223
- is_float=is_float2,
224
- max_rounding_precision=max_rounding_precision,
225
- )
226
- except Exception:
227
- continue
228
- break
229
- else:
230
- while True:
231
- try:
232
- operand1 = self._generate_number(
233
- min_val=min_value,
234
- max_val=max_value,
235
- is_float=is_float1,
236
- max_rounding_precision=max_rounding_precision,
237
- )
238
- # for testing addition
239
- operand2 = self._generate_number(
240
- min_val=min_value,
241
- max_val=max_value - operand1 - 1,
242
- is_float=is_float2,
243
- max_rounding_precision=max_rounding_precision,
244
- )
245
- except Exception:
246
- continue
247
- break
248
- result = operand1 + operand2
249
- elif operator == Operator.MULTIPLY:
250
- result = operand1 * operand2
251
- else:
252
- # this prevents a lot of "0" answers from being generated
253
- if operand1 < operand2 or random.random() < 0.01:
254
- operand1, operand2 = operand2, operand1
255
-
256
- if operation_type == OperationType.INT_INT:
257
- tmp = operand1 / operand2
258
-
259
- # we scale the temp result up to prevent a lot of "small divisions"
260
- if tmp < 10:
261
- tmp *= DIVISION_RESULT_MULTIPLIER
262
- if max_value > 999:
263
- tmp *= random.randint(2, 4)
264
-
265
- # prevents zero division
266
- operand1 = int(round(tmp)) * operand2
267
- result = int(operand1 / operand2)
268
-
269
- elif operation_type == OperationType.INT_FLOAT:
270
- operand2 = int(operand2)
271
- tmp = round(
272
- operand1 / operand2,
273
- random.randint(1, max_rounding_precision),
274
- )
275
-
276
- # we scale the temp result up to prevent a lot of "small divisions"
277
- if tmp < 10:
278
- tmp = float(
279
- Decimal(str(tmp)) * Decimal(str(DIVISION_RESULT_MULTIPLIER))
280
- )
281
-
282
- # deals with Python's decimal multiplication precision issue
283
- operand1 = float(Decimal(str(tmp)) * Decimal(str(operand2)))
284
- result = tmp
285
-
286
- else:
287
- tmp = round(
288
- operand1 / operand2, random.randint(1, max_rounding_precision)
289
- )
290
-
291
- # we scale the temp result up to prevent a lot of "small divisions"
292
- if tmp < 10:
293
- tmp = float(
294
- Decimal(str(tmp)) * Decimal(str(DIVISION_RESULT_MULTIPLIER))
295
- )
296
-
297
- # deals with Python's decimal multiplication precision issue
298
- operand1 = float(Decimal(str(tmp)) * Decimal(str(operand2)))
299
- result = tmp
300
-
301
- result = round(result, self.FLOAT_ANSWER_ROUNDING_PRECISION)
302
-
303
- question = self._construct_equation(
304
- operand1=operand1,
305
- operand2=operand2,
306
- operator=operator,
307
- use_commas=use_commas,
308
- )
309
- answer = self._format_number(result, use_commas)
310
-
311
- return {"question": question, "answer": answer, "operator": operator}
312
-
313
- def _split_generators(self, dl_manager, **kwargs) -> list[SplitGenerator]:
314
- generators = []
315
-
316
- for operator in Operator.OPERATORS:
317
- # Create separate splits for each type of number
318
- for type in ("int", "float"):
319
- split_name = f"{type}_{Operator.operator_to_name(operator)}"
320
-
321
- train_generator = SplitGenerator(
322
- name=split_name + "_train",
323
- gen_kwargs={
324
- "num_problems": int(self.config.num_problems * (1 - TEST_SIZE)),
325
- "min_value": 10**self.config.min_exponent,
326
- "max_value": 10**self.config.max_exponent,
327
- "max_rounding_precision": self.config.max_rounding_precision
328
- if type == "float"
329
- else None,
330
- "use_commas": self.config.use_commas,
331
- "operator": operator,
332
- "with_carry": self.config.with_carry,
333
- },
334
- )
335
-
336
- test_generator = SplitGenerator(
337
- name=split_name + "_test",
338
- gen_kwargs={
339
- "num_problems": int(self.config.num_problems * TEST_SIZE),
340
- "min_value": 10**self.config.min_exponent,
341
- "max_value": 10**self.config.max_exponent,
342
- "max_rounding_precision": self.config.max_rounding_precision
343
- if type == "float"
344
- else None,
345
- "use_commas": self.config.use_commas,
346
- "operator": operator,
347
- "with_carry": self.config.with_carry,
348
- },
349
- )
350
-
351
- generators.append(train_generator)
352
- generators.append(test_generator)
353
-
354
- return generators
355
-
356
- def _generate_examples(
357
- self,
358
- num_problems,
359
- min_value,
360
- max_value,
361
- max_rounding_precision,
362
- use_commas,
363
- operator,
364
- with_carry,
365
- ):
366
- def _get_operation_type(current_idx: int):
367
- # If max_rounding_precision is None, generate only integer problems
368
- """
369
- Determines the type of operation (integer-integer, float-float, or integer-float)
370
- to generate based on the current index and the proportion of float problems.
371
-
372
- Args:
373
- current_idx: The current index of the problem being generated.
374
- num_problems: The total number of problems to generate.
375
- max_rounding_precision: The maximum rounding precision to use when generating float problems.
376
-
377
- Returns:
378
- An OperationType indicating the type of operation to generate.
379
- """
380
- if max_rounding_precision is None:
381
- return OperationType.INT_INT
382
-
383
- # Otherwise, if the current index is less than the float problem proportion,
384
- elif current_idx < num_problems * FLOAT_FLOAT_PROBLEM_PROPORTION:
385
- return OperationType.FLOAT_FLOAT
386
-
387
- else:
388
- return OperationType.INT_FLOAT
389
-
390
- random.seed(SEED)
391
-
392
- for i in range(num_problems):
393
- yield (
394
- str(i),
395
- self.create_question_answer_pair(
396
- min_value=min_value,
397
- max_value=max_value,
398
- operator=operator,
399
- use_commas=use_commas,
400
- operation_type=_get_operation_type(i),
401
- with_carry=with_carry,
402
- max_rounding_precision=max_rounding_precision,
403
- ),
404
- )