Mathy
repository·master·Indexed 40 days ago
https://github.com/justindujardin/mathyA framework for solving mathematical problems step-by-step by integrating machine learning and planning algorithms. It includes mathy_core for expression parsing and transformation via BaseRule, and Mathy Envs for Reinforcement Learning (RL) environments. The system provides a CLI for simplifying polynomial expressions and generating problem sets.
What's inside Mathy
- Mathy is a tool designed to solve mathematical problems step-by-step using machine learning and planning algorithms. It leverages expression parsing and Reinforcement Learning (RL) environments to approach problem-solving as a sequential process.
Overview of mathy features
masterMathy is a mathematical toolset with several core capabilities:
- Computer Algebra System (CAS): Parses text into expression trees for manipulation and evaluation. It allows transforming trees using user-defined rules that preserve the expression's value.
- Learning Environments: Supports built-in or custom environments. You can define custom logic for actions, problems, timestep rewards, episode rewards, and win conditions.
- Expression Visualization: Provides APIs to visualize binary trees in a compact layout without branch overlaps to help understand problem structures and rule transformations.
- Python Integration: Built with type hints to support rich autocompletion and linting in modern IDEs.
Untitled record
masterThe Fractal Monte Carlo (FMC) algorithm is provided by the
mathy.fragilemodule. It uses a swarm of walkers to explore environments and find optimal paths to solutions, making it useful for navigating large, sparse action spaces without full model training.Key components for an FMC implementation include:
mathy.fragile.env.DiscreteEnv: The base class for discrete environments.mathy.fragile.models.DiscreteModel: The base class for action selection models.mathy.fragile.states.StatesEnv,StatesModel, andStatesWalkers: Classes managing environment, model, and walker states.mathy.fragile.swarm.Swarm: The main orchestrator for the swarm planning process.mathy.fragile.distributed_env.ParallelEnv: A wrapper to enable multiprocessing for the swarm.
How the Actor-Critic module works
masterThe
ActorCriticmodule implements the dual-structure learning mechanism essential for PPO:- Actor: Responsible for choosing actions. It outputs action probabilities using a
Softmaxlayer. It supports optional action masking via theuse_masked_actionsflag, which is useful when the action space is sparse or contains many invalid actions. - Critic: Evaluates the actor's actions by estimating the value of the current state.
Key methods:
act(state): Returns the sampledaction, itsaction_logprob, and thestate_val(critic's estimate).evaluate(state, action): Used during the update phase to calculateaction_logprobs,state_values, anddist_entropyfor the current policy.
import torch.nn as nn from torch.distributions import Categorical class ActorCritic(nn.Module): def __init__(self, state_dim, action_dim): # ... initialization of actor and critic networks ... def act(self, state): # ... returns action.detach(), action_logprob.detach(), state_val.detach() ... def evaluate(self, state, action): # ... returns action_logprobs, state_values, dist_entropy ...- Actor: Responsible for choosing actions. It outputs action probabilities using a
How mathy_envs work in Reinforcement Learning
masterMathy environments are reinforcement learning environments designed for manipulating math trees using a rules system. They follow these core mechanics:
- Problem Generation: Each environment generates math problem texts and tracks whether the current expression is "solved."
- Interaction: Users or models interact via "episodes," where they attempt to solve problems using a provided set of rules and environment-specific logic.
- Outputs: The environment outputs are used either as training data for machine learning models or as demonstrations of step-by-step problem solving.
Environments are implemented via a base interface and wrapped in classes compatible with
gymorgymnasiumlibraries.How the RolloutBuffer works in PPO
masterThe
RolloutBufferis a storage mechanism used during a single policy iteration in Proximal Policy Optimization (PPO). It collects trajectories generated by the agent's interaction with the environment, specifically storing:actions: The actions taken.states: The states encountered.logprobs: The log probabilities of the actions under the current policy.rewards: The rewards received.state_values: The estimated values of the states.is_terminals: Boolean flags indicating if a state is terminal.
Once the policy is updated using the data in the buffer, the buffer must be cleared using the
.clear()method to prepare for the next iteration.class RolloutBuffer: def __init__(self): self.actions = [] self.states = [] self.logprobs = [] self.rewards = [] self.state_values = [] self.is_terminals = [] def clear(self): del self.actions[:] del self.states[:] del self.logprobs[:] del self.rewards[:] del self.state_values[:] del self.is_terminals[:]Solve tasks using the swarm-planning algorithm
masterMathy can solve problems using a swarm-planning algorithm from the
fragilelibrary. This algorithm does not require a pre-trained model; instead, it simulates many different possible actions simultaneously and selects the most rewarding one to execute. This approach can be applied to any task exposed by Mathy to achieve decent results without the need for training.To use this, you can implement a swarm-planning loop that interacts with a Mathy environment by sampling actions and evaluating their rewards.
# Note: The specific implementation details are contained in the snippet # ./snippets/examples/swarm_random_task.pyInstall mathy_core and thinc
masterTo follow the examples in this notebook, you need to install
thincandmathy_corevia pip.!pip install "thinc>=8.0.0a0" mathy_coreUntitled record
masterTo maximize efficiency in FMC, implement a batch-capable environment wrapper. This wrapper should implement a
step_batchmethod to allow the swarm to interact with multiple environment instances simultaneously, rather than stepping them one by one.An implementation typically involves:
- A
PlanningEnvironmentthat wraps a standardgymenvironment and supports state-based stepping (set_stateandget_state). - A
step_batchmethod that iterates through actions and states to return arrays ofnew_states,observs,rewards,terminals, andinfos. - An
FMCEnvironment(inheriting fromDiscreteEnv) that uses thePlanningEnvironmentand implementsmake_transitionsto map the batch results to the format expected bymathy.fragile.
- A
Count like terms in a MathExpression
masterYou can programmatically identify and count 'like terms' in a math expression by parsing it with
ExpressionParserand usingget_termsandget_term_exfrommathy_core.Workflow:
- Parse the string into a
MathExpressionusingExpressionParser().parse(text). - Retrieve all term nodes using
get_terms(expression). - For each term, use
get_term_ex(term_node)to extract the variable and exponent. - Group terms by their variable/exponent signature (using
mathy_term_string) to identify which are 'like'.
Example logic:
from mathy_core import MathExpression, ExpressionParser, get_terms, get_term_ex from mathy_core.problems import mathy_term_string parser = ExpressionParser() expression = parser.parse("4x + 2x - x + 7") term_nodes = get_terms(expression) # Grouping logic example for term_node in term_nodes: ex = get_term_ex(term_node) key = mathy_term_string(variable=ex.variable, exponent=ex.exponent) # Use 'key' to group terms in a dictionaryfrom mathy_core import MathExpression, ExpressionParser, get_terms, get_term_ex from mathy_core.problems import mathy_term_string parser = ExpressionParser() expression = parser.parse("4x + 2x - x + 7") term_nodes = get_terms(expression) for term_node in term_nodes: ex = get_term_ex(term_node) key = mathy_term_string(variable=ex.variable, exponent=ex.exponent)- Parse the string into a
Install the Mathy package in editable mode
masterYou can install the Mathy Python package directly from the local file system using
pip. Using the-eflag allows you to make changes to the source code and have them reflected immediately without re-installing.pip install -e ./mathyRun tests and generate HTML coverage reports
masterTo execute all tests and generate a visual coverage report, run the
test.shscript from the root folder. The results and coverage data will be stored in the./htmlcov/directory. You can view the interactive coverage report by opening./htmlcov/index.htmlin a web browser.sh tools/test.sh