comprehensive-arithmetic-problems-carries / comprehensive-arithmetic-problems-carries.py
garrethlee's picture
garrethlee HF staff
Update comprehensive-arithmetic-problems-carries.py
9b5dcef verified
raw
history blame
14.1 kB
## 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,
with_carry: bool,
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.with_carry = with_carry
self.kwargs = kwargs
class ArithmeticProblemsDataset(GeneratorBasedBuilder):
BUILDER_CONFIG_CLASS = ArithmeticProblemsConfig
FLOAT_ANSWER_ROUNDING_PRECISION = 4
BUILDER_CONFIGS = [
ArithmeticProblemsConfig(
name=f"{i}-digit{'-with-carry' if with_carry else ''}",
num_problems=5000,
min_exponent=i-1,
max_exponent=i,
max_rounding_precision=max(i-1, 10),
with_carry=with_carry,
) for i in range(1, 21) for with_carry in [False, True]
]
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],
with_carry: 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,
)
# for testing addition
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:
if with_carry:
while True:
try:
operand1 = self._generate_number(
min_val=min_value,
max_val=max_value,
is_float=is_float1,
max_rounding_precision=max_rounding_precision,
)
# for testing addition
operand2 = self._generate_number(
min_val=max_value - operand1 ,
max_val=max_value,
is_float=is_float2,
max_rounding_precision=max_rounding_precision,
)
except Exception:
continue
break
else:
while True:
try:
operand1 = self._generate_number(
min_val=min_value,
max_val=max_value,
is_float=is_float1,
max_rounding_precision=max_rounding_precision,
)
# for testing addition
operand2 = self._generate_number(
min_val=min_value,
max_val=max_value - operand1 - 1,
is_float=is_float2,
max_rounding_precision=max_rounding_precision,
)
except Exception:
continue
break
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,
"with_carry": self.config.with_carry,
},
)
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,
"with_carry": self.config.with_carry,
},
)
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,
with_carry,
):
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),
with_carry=with_carry,
max_rounding_precision=max_rounding_precision,
),
)