File size: 12,119 Bytes
94e3dda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
## Adapted from https://github.com/maxwbuckley/r2ltokenizing/blob/main/llmarithmetic.py; with modifications
import random
from datasets import (
    BuilderConfig,
    SplitGenerator,
    GeneratorBasedBuilder,
    DatasetInfo,
    Value,
    Features,
)
from decimal import Decimal
import yaml

SEED = 42
TEST_SIZE = 0.2
DIVISION_RESULT_MULTIPLIER = 4
FLOAT_FLOAT_PROBLEM_PROPORTION = 0.3

_CITATION = """\
@misc{lee2024arithmeticproblemsdataset,
title = {Arithmetic Problems},
author={Garreth Lee},
year={2024}
}
"""



class Operator:
    ADD = "+"
    SUBTRACT = "-"
    MULTIPLY = "*"
    DIVIDE = "/"

    OPERATORS = [ADD, SUBTRACT, MULTIPLY, DIVIDE]

    @classmethod
    def is_operator(cls, value):
        return value in cls.OPERATORS

    @classmethod
    def operator_to_name(cls, value):
        if value == cls.ADD:
            return "add"
        elif value == cls.SUBTRACT:
            return "subtract"
        elif value == cls.MULTIPLY:
            return "multiply"
        elif value == cls.DIVIDE:
            return "divide"
        else:
            raise ValueError(f"Invalid operator: {value}")


class OperationType:
    INT_INT = [False, False]
    INT_FLOAT = [True, False]
    FLOAT_FLOAT = [True, True]

class ArithmeticProblemsConfig(BuilderConfig):
    def __init__(
        self,
        name: str,
        num_problems: int,
        min_exponent: int,
        max_exponent: int,
        max_rounding_precision: int,
        use_commas: bool = False,
        **kwargs,
    ):
        super().__init__(name=name)
        self.num_problems = num_problems
        self.min_exponent = min_exponent
        self.max_exponent = max_exponent
        self.max_rounding_precision = max_rounding_precision
        self.use_commas = use_commas
        self.kwargs = kwargs




class ArithmeticProblemsDataset(GeneratorBasedBuilder):
    BUILDER_CONFIG_CLASS = ArithmeticProblemsConfig
    FLOAT_ANSWER_ROUNDING_PRECISION = 4

    BUILDER_CONFIGS = [
        ArithmeticProblemsConfig(
            name=f"{i}-digit{'-use-commas' if use_commas else ''}",
            num_problems=5000,
            min_exponent=i-1,
            max_exponent=i,
            max_rounding_precision=max(i-1, 10),
            use_commas = use_commas,
        ) for i in range(1, 21) for use_commas in (True, False)
    ]

    VERSION = "1.0.0"

    def _info(self):
        return DatasetInfo(
            description="Generate arithmetic problems for use in math tokenization",
            features=Features(
                {
                    "question": Value("string"),
                    "answer": Value("string"),
                    "operator": Value("string"),
                }
            ),
            citation=_CITATION,
        )

    def _generate_number(
        self, min_val: int, max_val: int, is_float: bool, max_rounding_precision: int
    ) -> float | int:
        """
        Generates a random number within a specified range, either as an integer or float.

        Args:
        min_val: The minimum value of the range.
        max_val: The maximum value of the range.
        is_float: If true, generates a float
        max_rounding_precision: The maximum precision to use when rounding the number.

        Returns:
        A random number within the specified range, either as an int or a float.
        """
        if is_float:
            # Round to a random precision between 0 and max_rounding_precision
            return round(
                random.uniform(min_val, max_val),
                random.choice(range(1, max_rounding_precision + 1)),
            )
        else:
            return random.randint(min_val, max_val)

    def _format_number(self, number: int | float, use_commas: bool = False) -> str:
        """
        Rounds a number to a specified precision, and then formats it as a string.

        Args:
        number: The number to be formatted.
        use_commas: Whether to include commas as thousand separators.

        Returns:
        A string representation of the input number, rounded to the specified precision.
        """
        if use_commas:
            return "{:,}".format(number)
        else:
            return str(number)

    def _construct_equation(
        self,
        operand1: int | float,
        operand2: int | float,
        operator: str,
        use_commas: bool = False,
    ) -> str:
        """Helper function for constructing the string equations."""

        return "%s %s %s = " % (
            self._format_number(operand1, use_commas),
            operator,
            self._format_number(operand2, use_commas),
        )

    def create_question_answer_pair(
        self,
        min_value: int,
        max_value: int,
        operator: str,
        use_commas: bool,
        operation_type: list[bool],
        max_rounding_precision: int | None,
    ) -> dict[str, str]:
        """Creates a random question and correct answer pair.

        Args:
        min_value: The lowest possible random value.
        max_value: The highest possible random value.
        include_decimals: Whether to include float numbers in the generated problems.
        operator: The mathematical operator to use.
        use_commas: Whether to use commas to separate numbers right-to-left.

        Returns:
        A dictionary containing the equation string and the expected answer.
        """
        if not Operator.is_operator(operator):
            raise ValueError(f"Invalid operator: {operator}")

        is_float1, is_float2 = operation_type
        operand1 = self._generate_number(
            min_val=min_value,
            max_val=max_value,
            is_float=is_float1,
            max_rounding_precision=max_rounding_precision,
        )
        operand2 = self._generate_number(
            min_val=min_value,
            max_val=max_value,
            is_float=is_float2,
            max_rounding_precision=max_rounding_precision,
        )

        if operator == Operator.SUBTRACT:
            result = operand1 - operand2
        elif operator == Operator.ADD:
            result = operand1 + operand2
        elif operator == Operator.MULTIPLY:
            result = operand1 * operand2
        else:
            # this prevents a lot of "0" answers from being generated
            if operand1 < operand2 or random.random() < 0.01:
                operand1, operand2 = operand2, operand1

            if operation_type == OperationType.INT_INT:
                tmp = operand1 / operand2

                # we scale the temp result up to prevent a lot of "small divisions"
                if tmp < 10:
                    tmp *= DIVISION_RESULT_MULTIPLIER
                if max_value > 999:
                    tmp *= random.randint(2, 4)

                # prevents zero division
                operand1 = int(round(tmp)) * operand2
                result = int(operand1 / operand2)

            elif operation_type == OperationType.INT_FLOAT:
                operand2 = int(operand2)
                tmp = round(
                    operand1 / operand2,
                    random.randint(1, max_rounding_precision),
                )

                # we scale the temp result up to prevent a lot of "small divisions"
                if tmp < 10:
                    tmp = float(
                        Decimal(str(tmp)) * Decimal(str(DIVISION_RESULT_MULTIPLIER))
                    )

                # deals with Python's decimal multiplication precision issue
                operand1 = float(Decimal(str(tmp)) * Decimal(str(operand2)))
                result = tmp

            else:
                tmp = round(
                    operand1 / operand2, random.randint(1, max_rounding_precision)
                )

                # we scale the temp result up to prevent a lot of "small divisions"
                if tmp < 10:
                    tmp = float(
                        Decimal(str(tmp)) * Decimal(str(DIVISION_RESULT_MULTIPLIER))
                    )

                # deals with Python's decimal multiplication precision issue
                operand1 = float(Decimal(str(tmp)) * Decimal(str(operand2)))
                result = tmp

        result = round(result, self.FLOAT_ANSWER_ROUNDING_PRECISION)

        question = self._construct_equation(
            operand1=operand1,
            operand2=operand2,
            operator=operator,
            use_commas=use_commas,
        )
        answer = self._format_number(result, use_commas)

        return {"question": question, "answer": answer, "operator": operator}

    def _split_generators(self, dl_manager, **kwargs) -> list[SplitGenerator]:
        generators = []

        for operator in Operator.OPERATORS:
            # Create separate splits for each type of number
            for type in ("int", "float"):
                split_name = f"{type}_{Operator.operator_to_name(operator)}"

                train_generator = SplitGenerator(
                    name=split_name + "_train",
                    gen_kwargs={
                        "num_problems": int(self.config.num_problems * (1 - TEST_SIZE)),
                        "min_value": 10**self.config.min_exponent,
                        "max_value": 10**self.config.max_exponent,
                        "max_rounding_precision": self.config.max_rounding_precision
                        if type == "float"
                        else None,
                        "use_commas": self.config.use_commas,
                        "operator": operator,
                    },
                )

                test_generator = SplitGenerator(
                    name=split_name + "_test",
                    gen_kwargs={
                        "num_problems": int(self.config.num_problems * TEST_SIZE),
                        "min_value": 10**self.config.min_exponent,
                        "max_value": 10**self.config.max_exponent,
                        "max_rounding_precision": self.config.max_rounding_precision
                        if type == "float"
                        else None,
                        "use_commas": self.config.use_commas,
                        "operator": operator,
                    },
                )

                generators.append(train_generator)
                generators.append(test_generator)

        return generators

    def _generate_examples(
        self,
        num_problems,
        min_value,
        max_value,
        max_rounding_precision,
        use_commas,
        operator,
    ):
        def _get_operation_type(current_idx: int):
            # If max_rounding_precision is None, generate only integer problems
            """
            Determines the type of operation (integer-integer, float-float, or integer-float)
            to generate based on the current index and the proportion of float problems.

            Args:
                current_idx: The current index of the problem being generated.
                num_problems: The total number of problems to generate.
                max_rounding_precision: The maximum rounding precision to use when generating float problems.

            Returns:
                An OperationType indicating the type of operation to generate.
            """
            if max_rounding_precision is None:
                return OperationType.INT_INT

            # Otherwise, if the current index is less than the float problem proportion,
            elif current_idx < num_problems * FLOAT_FLOAT_PROBLEM_PROPORTION:
                return OperationType.FLOAT_FLOAT

            else:
                return OperationType.INT_FLOAT

        random.seed(SEED)

        for i in range(num_problems):
            yield (
                str(i),
                self.create_question_answer_pair(
                    min_value=min_value,
                    max_value=max_value,
                    operator=operator,
                    use_commas=use_commas,
                    operation_type=_get_operation_type(i),
                    max_rounding_precision=max_rounding_precision,
                ),
            )