garrethlee HF staff commited on
Commit
895108f
1 Parent(s): 4366e11

Delete loading script

Browse files
Files changed (1) hide show
  1. comprehensive-arithmetic-problems.py +0 -360
comprehensive-arithmetic-problems.py DELETED
@@ -1,360 +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
- use_commas: bool = False,
69
- **kwargs,
70
- ):
71
- super().__init__(name=name)
72
- self.num_problems = num_problems
73
- self.min_exponent = min_exponent
74
- self.max_exponent = max_exponent
75
- self.max_rounding_precision = max_rounding_precision
76
- self.use_commas = use_commas
77
- self.kwargs = kwargs
78
-
79
-
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{'-use-commas' if use_commas else ''}",
89
- num_problems=5000,
90
- min_exponent=i-1,
91
- max_exponent=i,
92
- max_rounding_precision=max(i-1, 10),
93
- use_commas = use_commas,
94
- ) for i in range(1, 21) for use_commas in (True, False)
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
- max_rounding_precision: int | None,
175
- ) -> dict[str, str]:
176
- """Creates a random question and correct answer pair.
177
-
178
- Args:
179
- min_value: The lowest possible random value.
180
- max_value: The highest possible random value.
181
- include_decimals: Whether to include float numbers in the generated problems.
182
- operator: The mathematical operator to use.
183
- use_commas: Whether to use commas to separate numbers right-to-left.
184
-
185
- Returns:
186
- A dictionary containing the equation string and the expected answer.
187
- """
188
- if not Operator.is_operator(operator):
189
- raise ValueError(f"Invalid operator: {operator}")
190
-
191
- is_float1, is_float2 = operation_type
192
- operand1 = self._generate_number(
193
- min_val=min_value,
194
- max_val=max_value,
195
- is_float=is_float1,
196
- max_rounding_precision=max_rounding_precision,
197
- )
198
- operand2 = self._generate_number(
199
- min_val=min_value,
200
- max_val=max_value,
201
- is_float=is_float2,
202
- max_rounding_precision=max_rounding_precision,
203
- )
204
-
205
- if operator == Operator.SUBTRACT:
206
- result = operand1 - operand2
207
- elif operator == Operator.ADD:
208
- result = operand1 + operand2
209
- elif operator == Operator.MULTIPLY:
210
- result = operand1 * operand2
211
- else:
212
- # this prevents a lot of "0" answers from being generated
213
- if operand1 < operand2 or random.random() < 0.01:
214
- operand1, operand2 = operand2, operand1
215
-
216
- if operation_type == OperationType.INT_INT:
217
- tmp = operand1 / operand2
218
-
219
- # we scale the temp result up to prevent a lot of "small divisions"
220
- if tmp < 10:
221
- tmp *= DIVISION_RESULT_MULTIPLIER
222
- if max_value > 999:
223
- tmp *= random.randint(2, 4)
224
-
225
- # prevents zero division
226
- operand1 = int(round(tmp)) * operand2
227
- result = int(operand1 / operand2)
228
-
229
- elif operation_type == OperationType.INT_FLOAT:
230
- operand2 = int(operand2)
231
- tmp = round(
232
- operand1 / operand2,
233
- random.randint(1, max_rounding_precision),
234
- )
235
-
236
- # we scale the temp result up to prevent a lot of "small divisions"
237
- if tmp < 10:
238
- tmp = float(
239
- Decimal(str(tmp)) * Decimal(str(DIVISION_RESULT_MULTIPLIER))
240
- )
241
-
242
- # deals with Python's decimal multiplication precision issue
243
- operand1 = float(Decimal(str(tmp)) * Decimal(str(operand2)))
244
- result = tmp
245
-
246
- else:
247
- tmp = round(
248
- operand1 / operand2, random.randint(1, max_rounding_precision)
249
- )
250
-
251
- # we scale the temp result up to prevent a lot of "small divisions"
252
- if tmp < 10:
253
- tmp = float(
254
- Decimal(str(tmp)) * Decimal(str(DIVISION_RESULT_MULTIPLIER))
255
- )
256
-
257
- # deals with Python's decimal multiplication precision issue
258
- operand1 = float(Decimal(str(tmp)) * Decimal(str(operand2)))
259
- result = tmp
260
-
261
- result = round(result, self.FLOAT_ANSWER_ROUNDING_PRECISION)
262
-
263
- question = self._construct_equation(
264
- operand1=operand1,
265
- operand2=operand2,
266
- operator=operator,
267
- use_commas=use_commas,
268
- )
269
- answer = self._format_number(result, use_commas)
270
-
271
- return {"question": question, "answer": answer, "operator": operator}
272
-
273
- def _split_generators(self, dl_manager, **kwargs) -> list[SplitGenerator]:
274
- generators = []
275
-
276
- for operator in Operator.OPERATORS:
277
- # Create separate splits for each type of number
278
- for type in ("int", "float"):
279
- split_name = f"{type}_{Operator.operator_to_name(operator)}"
280
-
281
- train_generator = SplitGenerator(
282
- name=split_name + "_train",
283
- gen_kwargs={
284
- "num_problems": int(self.config.num_problems * (1 - TEST_SIZE)),
285
- "min_value": 10**self.config.min_exponent,
286
- "max_value": 10**self.config.max_exponent,
287
- "max_rounding_precision": self.config.max_rounding_precision
288
- if type == "float"
289
- else None,
290
- "use_commas": self.config.use_commas,
291
- "operator": operator,
292
- },
293
- )
294
-
295
- test_generator = SplitGenerator(
296
- name=split_name + "_test",
297
- gen_kwargs={
298
- "num_problems": int(self.config.num_problems * TEST_SIZE),
299
- "min_value": 10**self.config.min_exponent,
300
- "max_value": 10**self.config.max_exponent,
301
- "max_rounding_precision": self.config.max_rounding_precision
302
- if type == "float"
303
- else None,
304
- "use_commas": self.config.use_commas,
305
- "operator": operator,
306
- },
307
- )
308
-
309
- generators.append(train_generator)
310
- generators.append(test_generator)
311
-
312
- return generators
313
-
314
- def _generate_examples(
315
- self,
316
- num_problems,
317
- min_value,
318
- max_value,
319
- max_rounding_precision,
320
- use_commas,
321
- operator,
322
- ):
323
- def _get_operation_type(current_idx: int):
324
- # If max_rounding_precision is None, generate only integer problems
325
- """
326
- Determines the type of operation (integer-integer, float-float, or integer-float)
327
- to generate based on the current index and the proportion of float problems.
328
-
329
- Args:
330
- current_idx: The current index of the problem being generated.
331
- num_problems: The total number of problems to generate.
332
- max_rounding_precision: The maximum rounding precision to use when generating float problems.
333
-
334
- Returns:
335
- An OperationType indicating the type of operation to generate.
336
- """
337
- if max_rounding_precision is None:
338
- return OperationType.INT_INT
339
-
340
- # Otherwise, if the current index is less than the float problem proportion,
341
- elif current_idx < num_problems * FLOAT_FLOAT_PROBLEM_PROPORTION:
342
- return OperationType.FLOAT_FLOAT
343
-
344
- else:
345
- return OperationType.INT_FLOAT
346
-
347
- random.seed(SEED)
348
-
349
- for i in range(num_problems):
350
- yield (
351
- str(i),
352
- self.create_question_answer_pair(
353
- min_value=min_value,
354
- max_value=max_value,
355
- operator=operator,
356
- use_commas=use_commas,
357
- operation_type=_get_operation_type(i),
358
- max_rounding_precision=max_rounding_precision,
359
- ),
360
- )