diff --git a/public/exp2.png b/public/exp2.png new file mode 100644 index 0000000000000000000000000000000000000000..61e5d9cb7bcd7d3a3850e0b8f7a6650c659b25ac --- /dev/null +++ b/public/exp2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8e2d12e64a01595f25c46c536583b305113bf6d596755ad5990348fc38e5dcf8 +size 361772 diff --git a/public/exp3.png b/public/exp3.png new file mode 100644 index 0000000000000000000000000000000000000000..2edaf4065aa15d0c75280d01adb3ecc642327f35 --- /dev/null +++ b/public/exp3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56bf5b504b41df6457ce08c3e23360daeb65bf676cc9985df34243144193c5eb +size 370701 diff --git a/public/exp4.png b/public/exp4.png new file mode 100644 index 0000000000000000000000000000000000000000..13ad6f96de527a1599cb38461030542dab6b0054 --- /dev/null +++ b/public/exp4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c0af5d3cb32d4085554466fa7446c8a557e36e26f67eb8ea749f64fb82677e3 +size 342232 diff --git a/public/exp5.png b/public/exp5.png new file mode 100644 index 0000000000000000000000000000000000000000..7b52bcfaa00948d7d0c07cd87c27bba14800e4f1 --- /dev/null +++ b/public/exp5.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ba9cdaee4f7d4b8cb381cee936a1f508446e9ce07828490cd8dcc71346de72d +size 306129 diff --git a/public/exp6.png b/public/exp6.png new file mode 100644 index 0000000000000000000000000000000000000000..374c94ce7e5426231cf00fb2900552faf3c87df7 --- /dev/null +++ b/public/exp6.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:846e9d7001ec02b90a33e7394f689488b1e03d00f9a22c148d9e65b7a0b46b16 +size 288557 diff --git a/public/framework.png b/public/framework.png new file mode 100644 index 0000000000000000000000000000000000000000..bdd056ec57c9c00b97446af1d6dcfdb6d8d09e58 --- /dev/null +++ b/public/framework.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6818364f9dfa44162c3cad96077b36b8f151605b73616ceb95b4dc7f2bed588b +size 263853 diff --git a/public/loss_curve.png b/public/loss_curve.png new file mode 100644 index 0000000000000000000000000000000000000000..7b00fd014171d916cdcde9b1e47daa09c59a0017 --- /dev/null +++ b/public/loss_curve.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ccdb559f9345f33faf13551e43d189e3a7dbb6d2260247c37571940911023928 +size 99761 diff --git a/public/ragen.png b/public/ragen.png new file mode 100644 index 0000000000000000000000000000000000000000..9c29b7e5916746745117feb7662eefb90af162c0 --- /dev/null +++ b/public/ragen.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e94c4580583bde14b79b8efc7fb4f4d31f732f599f3eba2f35aa05791f30ffc +size 486118 diff --git a/public/ragen_logo.jpeg b/public/ragen_logo.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b9d4269b73e535d14caf12ca760f32ee491cffcd --- /dev/null +++ b/public/ragen_logo.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc5a86379273774a743ca113c674414877c5d4c1650fedd0ebb62dfbdf74c284 +size 118420 diff --git a/public/rico.png b/public/rico.png new file mode 100644 index 0000000000000000000000000000000000000000..bb25204ee72e256d8367f5c869fb50b6da742584 --- /dev/null +++ b/public/rico.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d91fb5d0faa84472392f350a0e8a3618181e6c7500fa6b9b1082b1b998d047b8 +size 379036 diff --git a/public/star-history-202556.png b/public/star-history-202556.png new file mode 100644 index 0000000000000000000000000000000000000000..948e2982df3acfc8959c2fc771312844dc6b503c --- /dev/null +++ b/public/star-history-202556.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8612c6e1a5b2e9bc3fca247acc0987add3d90c56eb5c6be8cc1ebaa8c592bd8f +size 210467 diff --git a/public/starpo_logo.png b/public/starpo_logo.png new file mode 100644 index 0000000000000000000000000000000000000000..8e92d2194efedcd82e4c65a2bde9d8593596f3ee --- /dev/null +++ b/public/starpo_logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c40be49fa37555f3dc712e2d91d35e599e6c0a0f107e911af7dfca05d56a1d8e +size 666626 diff --git a/public/step_1.png b/public/step_1.png new file mode 100644 index 0000000000000000000000000000000000000000..6c7c400a9abe25a4f66a201fedee0e5476c01277 --- /dev/null +++ b/public/step_1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7056b065aa5d0f2fbb7af3ccefc26a34a94f6555d7626082e90a3f5f17c7f27e +size 4761654 diff --git a/public/step_2.png b/public/step_2.png new file mode 100644 index 0000000000000000000000000000000000000000..e5a87c1f6a351ecb98342786d3b94d01bcf08dd5 --- /dev/null +++ b/public/step_2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec41173ee19feb2e2bb96cdce2e110002de0474f78ce286decffed3135acff36 +size 4761654 diff --git a/ragen/__init__.py b/ragen/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e041332d026eb0b7bf64753cc1cdd2b5c5c225a1 --- /dev/null +++ b/ragen/__init__.py @@ -0,0 +1,6 @@ +"""RAGEN package initialisation.""" + +from ragen.patches import apply_omega_conf_patch + +# Ensure VERL config instantiation accepts RAGEN-specific extensions. +apply_omega_conf_patch() diff --git a/ragen/__pycache__/__init__.cpython-310.pyc b/ragen/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd82a80e8b6ff99e95c86ab1e20ea136c7111724 Binary files /dev/null and b/ragen/__pycache__/__init__.cpython-310.pyc differ diff --git a/ragen/__pycache__/utils.cpython-310.pyc b/ragen/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3471665abf3b54dab81537a597fe617f7b60b7f4 Binary files /dev/null and b/ragen/__pycache__/utils.cpython-310.pyc differ diff --git a/ragen/demo/__init__.py b/ragen/demo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..985f9997d19b3b5cc6220acacdf3c302da10cf52 --- /dev/null +++ b/ragen/demo/__init__.py @@ -0,0 +1 @@ +# Give an instant demo about LLM rollout and how they process the environment diff --git a/ragen/demo/run.py b/ragen/demo/run.py new file mode 100644 index 0000000000000000000000000000000000000000..704c6a8ee1be1d648f50c072d0bde76c69a02c52 --- /dev/null +++ b/ragen/demo/run.py @@ -0,0 +1,71 @@ +import gradio as gr +from ragen.llm_agent.agent_proxy import LLMAgentProxy, VllmWrapperWg +from verl import DataProto +from transformers import AutoTokenizer +import hydra +import os +import time +import asyncio + +# --- Global agent object +agent_proxy = None + +# --- Initialization function +@hydra.main(version_base=None, config_path="../../config", config_name="stream") +def init_agent(config): + global agent_proxy + os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn" + os.environ["CUDA_VISIBLE_DEVICES"] = str(config.system.CUDA_VISIBLE_DEVICES) + tokenizer = AutoTokenizer.from_pretrained(config.actor_rollout_ref.model.path) + actor_wg = VllmWrapperWg(config, tokenizer) + agent_proxy = LLMAgentProxy(config, actor_wg, tokenizer) + +# --- Streaming rollout generator +def rollout_stream(): + lm_inputs = DataProto(batch=None, non_tensor_batch=None, meta_info={ + 'eos_token_id': 151645, + 'pad_token_id': 151643, + 'recompute_log_prob': False, + 'do_sample': True, + 'validate': True + }) + env_outputs = agent_proxy.val_es_manager.reset() + assert len(env_outputs) == 1 + + for turn_idx in range(agent_proxy.config.agent_proxy.max_turn): + lm_inputs = agent_proxy.val_ctx_manager.get_lm_inputs(env_outputs, prepare_for_update=False) + lm_inputs.meta_info = {'eos_token_id': 151645, 'pad_token_id': 151643, 'recompute_log_prob': False, 'do_sample': True, 'validate': True} + lm_outputs = agent_proxy.generate_sequences(lm_inputs) + + response_texts = lm_outputs.non_tensor_batch['response_texts'] + yield f"\n--- Turn {turn_idx + 1} ---\n" + yield response_texts[0] + + env_inputs = agent_proxy.val_ctx_manager.get_env_inputs(lm_outputs) + env_outputs = agent_proxy.val_es_manager.step(env_inputs) + if len(env_outputs) == 0: + break + yield env_outputs[0]['history'][-1]['state'] + +# --- Gradio Streaming Setup +async def streaming_demo(): + stream = rollout_stream() + output = "" + for chunk in stream: + output += chunk + yield output + +def main(): + init_agent() + + with gr.Blocks() as demo: + output_box = gr.Textbox(label="Agent Output", lines=20) + run_button = gr.Button("Run Agent") + + run_button.click(fn=streaming_demo, inputs=[], outputs=output_box) + + demo.queue() + demo.launch() + +if __name__ == "__main__": + main() diff --git a/ragen/env/__init__.py b/ragen/env/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bc6838e4527675063ab9c6f3257ef0ac4ed7bae9 --- /dev/null +++ b/ragen/env/__init__.py @@ -0,0 +1,59 @@ +# from .alfworld.config import AlfredEnvConfig +# from .alfworld.env import AlfredTXTEnv +from .bandit.config import BanditEnvConfig +from .bandit.env import BanditEnv +from .countdown.config import CountdownEnvConfig +from .countdown.env import CountdownEnv +from .sokoban.config import SokobanEnvConfig +from .sokoban.env import SokobanEnv +from .frozen_lake.config import FrozenLakeEnvConfig +from .frozen_lake.env import FrozenLakeEnv +from .metamathqa.env import MetaMathQAEnv +from .metamathqa.config import MetaMathQAEnvConfig +from .lean.config import LeanEnvConfig +from .lean.env import LeanEnv +from .game_2048.config import Game2048EnvConfig +from .game_2048.env import Game2048Env +from .blackjack.config import BlackjackEnvConfig +from .blackjack.env import BlackjackEnv +from .rubikscube.config import RubiksCube2x2Config +from .rubikscube.env import RubiksCube2x2Env +from .sudoku.config import SudokuEnvConfig +from .sudoku.env import SudokuEnv + + +REGISTERED_ENVS = { + 'bandit': BanditEnv, + 'countdown': CountdownEnv, + 'sokoban': SokobanEnv, + 'frozen_lake': FrozenLakeEnv, + # 'alfworld': AlfredTXTEnv, + 'metamathqa': MetaMathQAEnv, + 'lean': LeanEnv, + 'game_2048': Game2048Env, + 'blackjack': BlackjackEnv, + 'rubikscube': RubiksCube2x2Env, + 'sudoku': SudokuEnv, +} + +REGISTERED_ENV_CONFIGS = { + 'bandit': BanditEnvConfig, + 'countdown': CountdownEnvConfig, + 'sokoban': SokobanEnvConfig, + 'frozen_lake': FrozenLakeEnvConfig, + # 'alfworld': AlfredEnvConfig, + 'metamathqa': MetaMathQAEnvConfig, + 'lean': LeanEnvConfig, + 'game_2048': Game2048EnvConfig, + 'blackjack': BlackjackEnvConfig, + 'rubikscube': RubiksCube2x2Config, + 'sudoku': SudokuEnvConfig, +} + +try: + from .webshop.env import WebShopEnv + from .webshop.config import WebShopEnvConfig + REGISTERED_ENVS['webshop'] = WebShopEnv + REGISTERED_ENV_CONFIGS['webshop'] = WebShopEnvConfig +except ImportError: + pass diff --git a/ragen/env/__pycache__/__init__.cpython-310.pyc b/ragen/env/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75876f401017617a6194dc181134d9db36126568 Binary files /dev/null and b/ragen/env/__pycache__/__init__.cpython-310.pyc differ diff --git a/ragen/env/__pycache__/base.cpython-310.pyc b/ragen/env/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff6fe8ea03dfc63ec20074b1e61fb5d61e94f9bc Binary files /dev/null and b/ragen/env/__pycache__/base.cpython-310.pyc differ diff --git a/ragen/env/alfworld_old/alfworld_config.yaml b/ragen/env/alfworld_old/alfworld_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..99c37425cc3cd6e60a0295ba13588298ab58319a --- /dev/null +++ b/ragen/env/alfworld_old/alfworld_config.yaml @@ -0,0 +1,145 @@ +dataset: + data_path: '$ALFWORLD_DATA/json_2.1.1/train' + eval_id_data_path: '$ALFWORLD_DATA/json_2.1.1/valid_seen' # null/None to disable + eval_ood_data_path: '$ALFWORLD_DATA/json_2.1.1/valid_unseen' # null/None to disable + num_train_games: -1 # max training games (<=0 indicates full dataset) + num_eval_games: -1 # max evaluation games (<=0 indicates full dataset) + +logic: + domain: '$ALFWORLD_DATA/logic/alfred.pddl' # PDDL domain file that defines the world dynamics + grammar: '$ALFWORLD_DATA/logic/alfred.twl2' # Grammar file that defines the text feedbacks + +env: + type: 'AlfredTWEnv' # 'AlfredTWEnv' or 'AlfredThorEnv' or 'AlfredHybrid' + # regen_game_files: False # [Deprecated] Use script `alfworld-generate` instead. + domain_randomization: False # shuffle Textworld print order and object id nums + task_types: [1, 2, 3, 4, 5, 6] # task-type ids: 1 - Pick & Place, 2 - Examine in Light, 3 - Clean & Place, 4 - Heat & Place, 5 - Cool & Place, 6 - Pick Two & Place + expert_timeout_steps: 150 # max steps before timeout for expert to solve the task + expert_type: "handcoded" # 'handcoded' or 'planner'. Note: the planner is very slow for real-time use + goal_desc_human_anns_prob: 0.0 # prob of using human-annotated goal language instead of templated goals (1.0 indicates all human annotations from ALFRED) + + hybrid: + start_eps: 100000 # starting episode of hybrid training, tw-only training upto this point + thor_prob: 0.5 # prob of AlfredThorEnv during hybrid training + eval_mode: "tw" # 'tw' or 'thor' - env used for evaluation during hybrid training + + thor: + screen_width: 300 # width of THOR window + screen_height: 300 # height of THOR window + smooth_nav: False # smooth rotations, looks, and translations during navigation (very slow) + save_frames_to_disk: False # save frame PNGs to disk (useful for making videos) + save_frames_path: './videos/' # path to save frame PNGs + +controller: + type: 'oracle' # 'oracle' or 'oracle_astar' or 'mrcnn' or 'mrcnn_astar' (aka BUTLER) + debug: False + load_receps: True # load receptacle locations from precomputed dict (if available) + +mask_rcnn: + pretrained_model_path: '$ALFWORLD_DATA/detectors/mrcnn.pth' + +general: + random_seed: 42 + use_cuda: True # disable this when running on machine without cuda + visdom: False # plot training/eval curves, run with visdom server + task: 'alfred' + training_method: 'dagger' # 'dqn' or 'dagger' + save_path: './training/' # path to save pytorch models + observation_pool_capacity: 3 # k-size queue, 0 indicates no observation + hide_init_receptacles: False # remove initial observation containing navigable receptacles + + training: + batch_size: 10 + max_episode: 50000 + smoothing_eps: 0.1 + optimizer: + learning_rate: 0.001 + clip_grad_norm: 5 + + evaluate: + run_eval: True + batch_size: 10 + env: + type: "AlfredTWEnv" + + checkpoint: + report_frequency: 1000 # report every N episode + experiment_tag: 'test' # name of experiment + load_pretrained: False # during test, enable this so that the agent load your pretrained model + load_from_tag: 'not loading anything' # name of pre-trained model to load in save_path + + model: + encoder_layers: 1 + decoder_layers: 1 + encoder_conv_num: 5 + block_hidden_dim: 64 + n_heads: 1 + dropout: 0.1 + block_dropout: 0.1 + recurrent: True + +rl: + action_space: "admissible" # 'admissible' (candidates from text engine) or 'generation' (seq2seq-style generation) or 'beam_search_choice' or 'exhaustive' (not working) + max_target_length: 20 # max token length for seq2seq generation + beam_width: 10 # 1 means greedy + generate_top_k: 3 + + training: + max_nb_steps_per_episode: 50 # terminate after this many steps + learn_start_from_this_episode: 0 # delay updates until this epsiode + target_net_update_frequency: 500 # sync target net with online net per this many epochs + + replay: + accumulate_reward_from_final: True + count_reward_lambda: 0.0 # 0 to disable + novel_object_reward_lambda: 0.0 # 0 to disable + discount_gamma_game_reward: 0.9 + discount_gamma_count_reward: 0.5 + discount_gamma_novel_object_reward: 0.5 + replay_memory_capacity: 500000 # adjust this depending on your RAM size + replay_memory_priority_fraction: 0.5 + update_per_k_game_steps: 5 + replay_batch_size: 64 + multi_step: 3 + replay_sample_history_length: 4 + replay_sample_update_from: 2 + + epsilon_greedy: + noisy_net: False # if this is true, then epsilon greedy is disabled + epsilon_anneal_episodes: 1000 # -1 if not annealing + epsilon_anneal_from: 0.3 + epsilon_anneal_to: 0.1 + +dagger: + action_space: "generation" # 'admissible' (candidates from text engine) or 'generation' (seq2seq-style generation) or 'exhaustive' (not working) + max_target_length: 20 # max token length for seq2seq generation + beam_width: 10 # 1 means greedy + generate_top_k: 5 + unstick_by_beam_search: False # use beam-search for failed actions, set True during evaluation + + training: + max_nb_steps_per_episode: 50 # terminate after this many steps + + fraction_assist: + fraction_assist_anneal_episodes: 50000 + fraction_assist_anneal_from: 1.0 + fraction_assist_anneal_to: 0.01 + + fraction_random: + fraction_random_anneal_episodes: 0 + fraction_random_anneal_from: 0.0 + fraction_random_anneal_to: 0.0 + + replay: + replay_memory_capacity: 500000 + update_per_k_game_steps: 5 + replay_batch_size: 64 + replay_sample_history_length: 4 + replay_sample_update_from: 2 + +vision_dagger: + model_type: "resnet" # 'resnet' (whole image features) or 'maskrcnn_whole' (whole image MaskRCNN feats) or 'maskrcnn' (top k MaskRCNN detection feats) or 'no_vision' (zero vision input) + resnet_fc_dim: 64 + maskrcnn_top_k_boxes: 10 # top k box features + use_exploration_frame_feats: False # append feats from initial exploration (memory intensive!) + sequence_aggregation_method: "average" # 'sum' or 'average' or 'rnn' \ No newline at end of file diff --git a/ragen/env/alfworld_old/config.py b/ragen/env/alfworld_old/config.py new file mode 100644 index 0000000000000000000000000000000000000000..f5eaef7e1e5364604234a31920b6ac06e9e30344 --- /dev/null +++ b/ragen/env/alfworld_old/config.py @@ -0,0 +1,26 @@ +from ragen.env.base import BaseEnvConfig +from dataclasses import dataclass, field +from typing import Dict + +@dataclass +class AlfredEnvConfig(BaseEnvConfig): + """configuration for text world AlfredEnv""" + config_file: str = "./ragen/env/alfworld/alfworld_config.yaml" + action_lookup: Dict[int, str] = field(default_factory=lambda: { + 1: "look", + 2: "inventory", + 3: "go to ", + 4: "open ", + 5: "close ", + 6: "take from ", + 7: "move to ", + 8: "examine ", + 9: "use ", + 10: "heat with ", + 11: "clean with ", + 12: "cool with ", + 13: "slice with " + }) + format_score: float = 0.1 + score: float = 1.0 + render_mode: str = "text" \ No newline at end of file diff --git a/ragen/env/alfworld_old/env.py b/ragen/env/alfworld_old/env.py new file mode 100644 index 0000000000000000000000000000000000000000..bb0f479082e8ced737933c22e044b8b743e57f35 --- /dev/null +++ b/ragen/env/alfworld_old/env.py @@ -0,0 +1,158 @@ +""" +This is the environment for the ALFRED dataset. +author: Qineng Wang +date: 2025-03-30 +""" +import os +import random +import textworld +import textworld.gym +import numpy as np +import alfworld.agents.modules.generic as generic +from alfworld.agents.environment.alfred_tw_env import AlfredTWEnv, AlfredDemangler, AlfredInfos +from ragen.env.base import BaseLanguageBasedEnv +from ragen.env.alfworld.config import AlfredEnvConfig +from ragen.env.alfworld.utils import load_config, check_format + +class AlfredTXTEnv(BaseLanguageBasedEnv): + + # raw_env: AlfredTWEnv = AlfredTWEnv(config=load_config(AlfredEnvConfig().config_file), train_eval="train") + # print("initializing alfworld env") + # NOTE Currently raw_env cannot customize config. + + def __init__(self, config: AlfredEnvConfig = AlfredEnvConfig(), mode='eval_in_distribution'): + # mode: "train", "eval_in_distribution" or "eval_out_of_distribution" + super().__init__() + self.config = config + self.ACTION_LOOKUP = self.config.action_lookup + raw_env_config = load_config(self.config.config_file) + self.raw_env = AlfredTWEnv(config=raw_env_config, train_eval=mode) + self.num_games = self.raw_env.num_games + self.game_files = self.raw_env.game_files + print(f"Overall we have {len(self.game_files)} games in split={self.raw_env.train_eval}") + self.alfred_env = self.raw_env.init_env(batch_size=1) + self.current_game_file = None + self.render_cache = None + self.available_actions = None + self.render_mode = self.config.render_mode + assert self.render_mode == 'text' + + def reset(self, seed=None, mode=None): + """ + Reset the environment with a specific seed. + If seed is provided, it deterministically selects a specific game file. + """ + try: + if mode == "test": + if seed is None: + raise ValueError("Seed must be provided in test mode.") + selected_game = self.game_files[seed] + else: + if seed is not None: + np.random.seed(seed) + random.seed(seed) + game_idx = seed % len(self.game_files) + selected_game = self.game_files[game_idx] + else: + selected_game = random.choice(self.game_files) + + self.current_game_file = selected_game + + if hasattr(self, 'alfred_env') and self.alfred_env is not None: + self.alfred_env.close() + + request_infos = textworld.EnvInfos(won=True, admissible_commands=True, extras=["gamefile"]) + config = load_config(self.config.config_file) + wrappers = [AlfredDemangler(), AlfredInfos()] + max_steps = config["rl"]["training"]["max_nb_steps_per_episode"] + + env_id = textworld.gym.register_game( + selected_game, + request_infos=request_infos, + batch_size=1, + asynchronous=False, + max_episode_steps=max_steps, + wrappers=wrappers + ) + + self.alfred_env = textworld.gym.make(env_id) + + obs, info = self.alfred_env.reset() + self.render_cache = obs[0] + self.available_actions = info["admissible_commands"][0] + self.instruction_text = obs[0] + return self.render_cache + + except (RuntimeError, RuntimeWarning) as e: + print(f"Error in reset: {e}") + next_seed = abs(hash(str(seed))) % (2 ** 32) if seed is not None else None + return self.reset(next_seed) + + def compute_score(self, base_reward, valid_action, done): + """ + Compute the score based on the base reward, format reward, and completion status. + + Args: + base_reward: The reward from the environment + valid_action: Whether the action format is valid + done: Whether the episode is finished + + Returns: + The computed score + """ + if done: + return self.config.score + self.config.format_score + base_reward + elif valid_action: + return base_reward + self.config.format_score + else: + return 0.0 + + def step(self, action: str): + """ + Take a step in the environment using the provided action string. + The action must match one of the templates in ACTION_LOOKUP. + """ + valid_action = check_format(action, self.ACTION_LOOKUP.values()) + action_is_available = True if action in self.available_actions else False + if not valid_action: + return f"Invalid action format: {action}", 0, False, {"action_is_effective": False, "action_is_valid": False, "success": False} + + obs, rewards, dones, infos = self.alfred_env.step([action]) # BatchEnv expects a list of commands + observation = obs[0] + self.available_actions = infos["admissible_commands"][0] + self.render_cache = observation + base_reward = rewards[0] + done = dones[0] + info = {"action_is_effective": True, "action_is_valid": action_is_available, "success": infos["won"][0]} + + reward = self.compute_score(base_reward, valid_action, done) + + return self.render_cache, reward, done, info + + def render(self): + return self.render_cache + + def close(self): + self.render_cache = None + self.alfred_env.close() + +if __name__ == "__main__": + import os + os.environ["ALFWORLD_DATA"] = "./data/alfworld" + env = AlfredTXTEnv() + + # Test resetting environment with same seed + print("\n\n=== Testing environment reset with same seed ===") + seed = 42 + obs1 = env.reset(seed) + for i in range(52): + print("Observation:", obs1) + action = "go to shelf 2" + if action.lower() == "exit": + break + obs1, reward, done, info = env.step(action) + + print(f"Reward: {reward}, Done: {done}, Info: {info}") + if done: + break + \ No newline at end of file diff --git a/ragen/env/alfworld_old/utils.py b/ragen/env/alfworld_old/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..af313e95432e4c682f90e6a7eb47f17fdd64e533 --- /dev/null +++ b/ragen/env/alfworld_old/utils.py @@ -0,0 +1,53 @@ +import argparse +import os +import yaml +import re +from typing import List, Any + +def load_config(config_file: str, params: List[str] = []): + assert os.path.exists(config_file), f"Invalid config file: {config_file}" + with open(config_file) as reader: + config = yaml.safe_load(reader) + # Parse overriden params. + for param in params: + fqn_key, value = param.split("=") + entry_to_change = config + keys = fqn_key.split(".") + for k in keys[:-1]: + entry_to_change = entry_to_change[k] + entry_to_change[keys[-1]] = value + return config + +def check_format(action: str, templates: Any) -> bool: + """ + Validate that the action matches one of our action templates. + Returns True if valid, False otherwise. + """ + if "None" in action: + return False + + # Skip validation for basic actions that don't have placeholders + basic_actions = ["look", "inventory"] + if action in basic_actions: + return True + + # Check if the action follows any of our templates + for template in templates: + # Skip "None" and basic actions we already checked + if template == "None" or template in basic_actions: + continue + + # Convert template to regex pattern + # Replace with regex that matches any word(s) + pattern = template.replace("", "([\\w\\s]+)") \ + .replace("", "([\\w\\s]+)") \ + .replace("", "([\\w\\s]+)") + pattern = f"^{pattern}$" # Match the entire string + + if re.match(pattern, action): + return True + + return False + +def check_correctness(action: str, target: str) -> bool: + ... diff --git a/ragen/env/bandit/__init__.py b/ragen/env/bandit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d65793d4dc1bcb0d3f9cfcc276c6cc3986d28357 --- /dev/null +++ b/ragen/env/bandit/__init__.py @@ -0,0 +1,4 @@ +from .env import BanditEnv +from .config import BanditEnvConfig + +__all__ = ["BanditEnv", "BanditEnvConfig"] diff --git a/ragen/env/bandit/__pycache__/__init__.cpython-310.pyc b/ragen/env/bandit/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d24f94baee9ac0831ede4fcbc53a38873bfa6f9c Binary files /dev/null and b/ragen/env/bandit/__pycache__/__init__.cpython-310.pyc differ diff --git a/ragen/env/bandit/__pycache__/config.cpython-310.pyc b/ragen/env/bandit/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5cd82b136e8ce7f59243d5ce42fe31f50859160 Binary files /dev/null and b/ragen/env/bandit/__pycache__/config.cpython-310.pyc differ diff --git a/ragen/env/bandit/__pycache__/env.cpython-310.pyc b/ragen/env/bandit/__pycache__/env.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7431fa8e3e6ec35cee234d5547fc318f7d141a6e Binary files /dev/null and b/ragen/env/bandit/__pycache__/env.cpython-310.pyc differ diff --git a/ragen/env/bandit/config.py b/ragen/env/bandit/config.py new file mode 100644 index 0000000000000000000000000000000000000000..d577cc79e3f3a808bbdd18e61c279bc24ad69f1d --- /dev/null +++ b/ragen/env/bandit/config.py @@ -0,0 +1,41 @@ +from dataclasses import dataclass +from typing import Dict + +@dataclass +class BanditEnvConfig: + split: str = "train" + action_space_start: int = 1 + lo_arm_score: float = 0.1 + hi_arm_loscore: float = 0.0 + hi_arm_hiscore: float = 1.0 + hi_arm_hiscore_prob: float = 0.25 + render_mode: str = "text" + action_lookup: Dict[int, str] = None # defined in env.py + + +ARM_NAMES = { + "train": [ + ("Teacher", "Trader"), + ("Nurse", "StartupFounder"), + ("Librarian", "Investor"), + ("Accountant", "StockBroker"), + ("Engineer", "RealEstateAgent"), + ("Pharmacist", "Musician"), + ("Clerk", "Freelancer"), + ("Technician", "Youtuber"), + ("Planner", "Artist"), + ("Postman", "Pilot"), + ("Banker", "VentureCapitalist"), + ("Gardener", "Cryptominer"), + ], + "test": [ + ("Receptionist", "Explorer"), + ("Archivist", "Filmmaker"), + ("Bookkeeper", "Consultant"), + ("SocialWorker", "Photographer"), + ("Mechanic", "GameDesigner"), + ("Secretary", "Entrepreneur"), + ("Cashier", "DataScientist"), + ("CivilServant", "StartupAccelerator"), + ], +} \ No newline at end of file diff --git a/ragen/env/bandit/env.py b/ragen/env/bandit/env.py new file mode 100644 index 0000000000000000000000000000000000000000..53d0f626c93f22120488d02cca12718fb8b50b5b --- /dev/null +++ b/ragen/env/bandit/env.py @@ -0,0 +1,144 @@ +import gymnasium as gym +import numpy as np +from ragen.env.base import BaseDiscreteActionEnv +from .config import BanditEnvConfig, ARM_NAMES + +INIT_PROMPT = """You are playing a bandit game. Goal: Maximize your total reward by choosing which arm to pull. +Game Rules: +1. There are 2 arms, named {name_a} and {name_b} +2. Each arm has its own reward distribution, related to their names. +3. Analyze the symbolic meaning of each arm's name to guess how their reward distribution might behave. +4. Based on the symbolic meaning of their names, which arm do you think is more likely to give higher rewards on average? Choose between {name_a} and {name_b}, and output like {name_a} or {name_b} . +""" + +# INIT_PROMPT = """You are playing a bandit game. Goal: Maximize your total reward by choosing which arm to pull. +# Game Rules: +# 1. There are 2 arms, named {name_a} and {name_b}. +# 2. Each arm has its own reward distribution, related to their names. +# 3. You need to analyze the symbolic meaning of each arm's name to guess their reward potential. + +# Example answer format: +# +# +# Arm A is named \"{name_a}\". Symbolically, this implies [analysis of name A]. +# Arm B is named \"{name_b}\". Symbolically, this implies [analysis of name B]. +# +# Based on the analysis, {name_a} seems to represent risk/low value, while {name_b} implies wealth/stability. +# +# If I pull {name_b}, I expect a higher average reward because [reasoning]. +# +# +# {name_b} + +# A sample full output is as follows: +# +# +# Arm A is named "Rotten Apple". Symbolically, this implies decay and zero value. +# Arm B is named "Golden Chalice". Symbolically, this implies treasure and high value. +# +# Comparing the two, the Golden Chalice is clearly superior in potential value. +# +# Pulling "Golden Chalice" will likely yield a high positive reward, whereas "Rotten Apple" might give zero or negative reward. +# +# +# Golden Chalice """ + +class BanditEnv(BaseDiscreteActionEnv, gym.Env): + class_counter = 0 + + def __init__(self, config = None): + BaseDiscreteActionEnv.__init__(self) + self.config = config if config is not None else BanditEnvConfig() + self.ACTION_SPACE = gym.spaces.discrete.Discrete(2, start=self.config.action_space_start) + self.split = self.config.split + self.render_cache = None + self.render_mode = self.config.render_mode + self.internal_seed = BanditEnv.class_counter + BanditEnv.class_counter += 1 + assert self.render_mode == 'text' + + def _randomize_arms(self): + start = self.config.action_space_start + if self.np_random.random() < 0.5: + self.ACTION_LOOKUP = { + start: self.lo_arm_name, + start + 1: self.hi_arm_name, + } + else: + self.ACTION_LOOKUP = { + start: self.hi_arm_name, + start + 1: self.lo_arm_name, + } + self.config.action_lookup = self.ACTION_LOOKUP + self.ARM_IDX_TO_NAME = self.ACTION_LOOKUP + self.NAME_TO_ARM_IDX = {name: idx for idx, name in self.ACTION_LOOKUP.items()} + + def _lo_arm_reward(self): + return self.config.lo_arm_score + + def _hi_arm_reward(self): + if self.np_random.random() < self.config.hi_arm_hiscore_prob: + return self.config.hi_arm_hiscore + return self.config.hi_arm_loscore + + def render(self): + return self.render_cache + + def reset(self, seed=None, mode=None): + if seed is not None: + gym.Env.reset(self, seed=seed + self.internal_seed) # add internal seed to differ random reward generator inside the same group + else: + gym.Env.reset(self, seed=seed) + index = int(self.np_random.random() * len(ARM_NAMES[self.split])) + self.lo_arm_name, self.hi_arm_name = ARM_NAMES[self.split][index] + self._randomize_arms() + pos1 = self.config.action_space_start + pos2 = pos1 + 1 + machine1 = self.ARM_IDX_TO_NAME[pos1] + machine2 = self.ARM_IDX_TO_NAME[pos2] + self.render_cache = INIT_PROMPT.format(name_a=machine1, name_b=machine2) + return self.render_cache + + def step(self, action: int): + assert action in self.ACTION_LOOKUP, f"Invalid action: {action}" + reward = self.compute_reward(action) + arm_name = self.ARM_IDX_TO_NAME[action] + next_obs = f"{arm_name}: {reward} points" + self.render_cache = next_obs + done, info = True, {"action_is_effective": True, "action_is_valid": True, "success": arm_name == self.hi_arm_name} + return next_obs, reward, done, info + + def compute_reward(self, action): + arm_name = self.ARM_IDX_TO_NAME[action] + if arm_name == self.lo_arm_name: + return self._lo_arm_reward() + else: + return self._hi_arm_reward() + + def get_all_actions(self): + return [self.ACTION_SPACE.start, self.ACTION_SPACE.start + 1] + + def render(self): + return self.render_cache + + def close(self): + self.render_cache = None + +if __name__ == "__main__": + def run_simulation(env, n_episodes=1000, action=1, start_seed=500): + rewards = [] + for i in range(start_seed, start_seed + n_episodes): + env.reset(seed=i) + reward = env.step(action)[1] + rewards.append(reward) + + return { + 'mean_reward': np.mean(rewards), + 'std_reward': np.std(rewards), + 'n_episodes': n_episodes, + 'action': env.ARM_IDX_TO_NAME[action] + } + + env = BanditEnv() + stats = run_simulation(env) + print(f"Arm: {stats['action']}, Reward: {stats['mean_reward']:.3f} ± {stats['std_reward']:.3f}") \ No newline at end of file diff --git a/ragen/env/base.py b/ragen/env/base.py new file mode 100644 index 0000000000000000000000000000000000000000..e29f1a00f1dec9d73893283e8421db4abd6bf878 --- /dev/null +++ b/ragen/env/base.py @@ -0,0 +1,100 @@ +from abc import ABC, abstractmethod +import re +from typing import Optional, List, Tuple, Any, Dict + +class BaseEnv(ABC): + """ + Abstract base class for all environments. + The class needs to handle text-based input, input may be invalid + - Environment will track the total reward for the trajectory + + """ + def __init__(self): + pass + + @abstractmethod + def reset(self, seed=None, **kwargs) -> Any: + """ + Reset the environment. + NOTE: the environment should be same for the same seed + Returns: + rendered environment + """ + pass + + @abstractmethod + def step(self, action) -> Tuple[Any, float, bool, Dict]: + """ + Execute one step in the environment. + NOTE should also handle predefined invalid action (0) + Args: + action: Action to take, must be in action space, or default invalid action + + Returns: + observation (rendered environment), reward, done, info + """ + pass + + # below are optional methods + + def render(self, mode: str = 'text') -> Any: + """Render the environment. Optional method.""" + pass + + def compute_reward(self, action, **kwargs) -> float: + """Compute reward for the action.""" + pass + + def close(self): + """Close the environment.""" + pass + + +class BaseDiscreteActionEnv(BaseEnv, ABC): + """ + Abstract base class for environments with discrete action spaces + This class provides common functionality for environments like FrozenLakeEnv and SokobanEnv. + """ + + @abstractmethod + def step(self, action: int) -> Tuple[Any, float, bool, Dict]: + """ + Execute one step in the environment. + Args: + action: Action to take, must be in action space, or default invalid action + Returns: + observation (rendered environment), reward, done, info + """ + pass + + @abstractmethod + def get_all_actions(self) -> List[int]: + """Get list of all valid actions.""" + pass + + +class BaseLanguageBasedEnv(BaseEnv, ABC): + """ + Abstract base class for environments with language-based action space environment + This class provides common functionality for environments like countdown from TinyZero + """ + + @abstractmethod + def step(self, action: str) -> Tuple[Any, float, bool, Dict]: + """ + Execute one step in the environment. + Args: + action: Action to take, must be in action space, or default invalid action + Returns: + observation (rendered environment), reward, done, info + """ + pass + + +class BaseEnvConfig(ABC): + """ + Abstract base class for environment configurations. + """ + def __init__(self): + self.invalid_act = "" + self.invalid_act_score = 0 diff --git a/ragen/env/blackjack/__init__.py b/ragen/env/blackjack/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..581ed6b7fc34837ce0bbc54540e0e57a030020a5 --- /dev/null +++ b/ragen/env/blackjack/__init__.py @@ -0,0 +1,2 @@ +from .config import BlackjackEnvConfig +from .env import BlackjackEnv diff --git a/ragen/env/blackjack/__pycache__/__init__.cpython-310.pyc b/ragen/env/blackjack/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91191a117c31f8b041673e819485b54962582567 Binary files /dev/null and b/ragen/env/blackjack/__pycache__/__init__.cpython-310.pyc differ diff --git a/ragen/env/blackjack/__pycache__/config.cpython-310.pyc b/ragen/env/blackjack/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09f3ff3bc2626b59b9810db98b4151ab460a65f9 Binary files /dev/null and b/ragen/env/blackjack/__pycache__/config.cpython-310.pyc differ diff --git a/ragen/env/blackjack/__pycache__/env.cpython-310.pyc b/ragen/env/blackjack/__pycache__/env.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3de0662d3ad70b7beb7e8e3a06a140e7fda0d438 Binary files /dev/null and b/ragen/env/blackjack/__pycache__/env.cpython-310.pyc differ diff --git a/ragen/env/blackjack/config.py b/ragen/env/blackjack/config.py new file mode 100644 index 0000000000000000000000000000000000000000..2825b00b33f2429f5c7f47b1a527731877f63dbb --- /dev/null +++ b/ragen/env/blackjack/config.py @@ -0,0 +1,17 @@ +from dataclasses import dataclass +import gymnasium as gym +from ragen.env.base import BaseEnvConfig + + +@dataclass +class BlackjackEnvConfig(BaseEnvConfig): + render_mode: str = "text" + action_lookup: dict = None + + def __post_init__(self): + if self.action_lookup is None: + # 1: Stick, 2: Hit + self.action_lookup = {1: "Stick", 2: "Hit"} + self.invalid_act = 0 + self.invalid_act_score = 0.0 + self.ACTION_SPACE = gym.spaces.discrete.Discrete(2, start=1) diff --git a/ragen/env/blackjack/env.py b/ragen/env/blackjack/env.py new file mode 100644 index 0000000000000000000000000000000000000000..5bb2760ef20e2f2475ec4af6ba5cb3790e96f595 --- /dev/null +++ b/ragen/env/blackjack/env.py @@ -0,0 +1,129 @@ +import gymnasium as gym +import numpy as np +from typing import Tuple, Any, Dict, List +from ragen.env.base import BaseDiscreteActionEnv +from .config import BlackjackEnvConfig +from ragen.utils import all_seed + +def draw_card(rng: np.random.Generator) -> int: + # 1 is Ace, 2-9 as is, 10 represents 10/J/Q/K + card_vals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + weights = [1, 1, 1, 1, 1, 1, 1, 1, 1, 4] + probs = np.array(weights, dtype=np.float64) + probs /= probs.sum() + return int(rng.choice(card_vals, p=probs)) + +def usable_ace(hand: List[int]) -> bool: + return 1 in hand and sum(hand) + 10 <= 21 + +def hand_sum(hand: List[int]) -> int: + total = sum(hand) + if 1 in hand and total + 10 <= 21: + return total + 10 + return total + +class BlackjackEnv(BaseDiscreteActionEnv, gym.Env): + def __init__(self, config: BlackjackEnvConfig | None = None): + BaseDiscreteActionEnv.__init__(self) + self.config = config or BlackjackEnvConfig() + self.ACTION_LOOKUP = self.config.action_lookup + self.ACTION_SPACE = gym.spaces.discrete.Discrete(2, start=1) + self.render_mode = self.config.render_mode + self.rng = np.random.default_rng() + self.player = [] + self.dealer = [] + + def reset(self, seed=None, mode=None): + gym.Env.reset(self, seed=seed) + with all_seed(seed): + self.rng = np.random.default_rng(seed) + self.player = [draw_card(self.rng), draw_card(self.rng)] + self.dealer = [draw_card(self.rng), draw_card(self.rng)] + + # 即使起手21点,Gym的reset也不能返回done,只能通过Observation提示 + return self.render(done=False) + + def step(self, action: int) -> Tuple[Any, float, bool, Dict]: + assert action in self.ACTION_LOOKUP, f"Invalid action: {action}" + info = {"action_is_effective": True, "action_is_valid": True, "success": False} + + # 1: Stick, 2: Hit + if action == 2: # Hit + self.player.append(draw_card(self.rng)) + if hand_sum(self.player) > 21: + # 爆牌 (Bust) + done = True + reward = -1.0 + info["success"] = False + # 爆牌时,render需要知道游戏结束,不再请求动作 + next_obs = self.render(done=True, result_msg="You Busted! (Sum > 21)") + return next_obs, reward, done, info + + # 继续游戏 + next_obs = self.render(done=False) + return next_obs, 0.0, False, info + + else: # Stick + # Dealer policy: hit to 17 or more + while hand_sum(self.dealer) < 17: + self.dealer.append(draw_card(self.rng)) + + reward = self._settle() + done = True + info["success"] = reward > 0 + + # 生成结算信息 + if reward > 0: res = "You Won!" + elif reward < 0: res = "You Lost." + else: res = "Draw." + + next_obs = self.render(done=True, result_msg=res) + return next_obs, float(reward), done, info + + def _settle(self) -> float: + p = hand_sum(self.player) + d = hand_sum(self.dealer) + if p > 21: return -1.0 + if d > 21: return 1.0 + if p > d: return 1.0 + if p < d: return -1.0 + return 0.0 + + def render(self, mode: str | None = None, done: bool = False, result_msg: str = "") -> str: + p_sum = hand_sum(self.player) + ua = usable_ace(self.player) + + lines = [] + lines.append("=== Blackjack Game State ===") + lines.append(f"Your Hand: {self.player} (Total: {p_sum}).") + if ua: + lines.append("Note: You possess a usable Ace.") + + if not done: + # 游戏进行中,只显示庄家的一张牌 + lines.append(f"Dealer's Visible Card: {self.dealer[0]}.") + lines.append("") + lines.append("Available Actions:") + lines.append("- Action 1: Stick (Stop)") + lines.append("- Action 2: Hit (Add card)") + + # 增加策略提示,防止起手21点还Hit + if p_sum == 21: + lines.append("\nWait! You have 21. It is strongly recommended to Stick (Action 1).") + + lines.append("\nWhat is your next move?") + else: + # 游戏结束,显示全貌 + d_sum = hand_sum(self.dealer) + lines.append(f"Dealer's Hand: {self.dealer} (Total: {d_sum}).") + lines.append("") + lines.append(f"=== Game Over: {result_msg} ===") + # 此时不再询问 Next move + + return "\n".join(lines) + + def close(self): + pass + + def get_all_actions(self): + return list(self.ACTION_LOOKUP.keys()) \ No newline at end of file diff --git a/ragen/env/countdown/__init__.py b/ragen/env/countdown/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b8b82f5770c734996192dad78a215da168214ac0 --- /dev/null +++ b/ragen/env/countdown/__init__.py @@ -0,0 +1,9 @@ +""" +Adapted from the nicely written code from TinyZero and veRL +We plan to generalize this environment to support any sort of static problem sets +""" + +from .env import CountdownEnv +from .config import CountdownEnvConfig + +__all__ = ["CountdownEnv", "CountdownEnvConfig"] diff --git a/ragen/env/countdown/__pycache__/__init__.cpython-310.pyc b/ragen/env/countdown/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3598958c0ea5b7396ec8508eb41bc14dfed8c1d1 Binary files /dev/null and b/ragen/env/countdown/__pycache__/__init__.cpython-310.pyc differ diff --git a/ragen/env/countdown/__pycache__/config.cpython-310.pyc b/ragen/env/countdown/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfe13c0220dd815e8cf05fb34aaf47e618a7a856 Binary files /dev/null and b/ragen/env/countdown/__pycache__/config.cpython-310.pyc differ diff --git a/ragen/env/countdown/__pycache__/env.cpython-310.pyc b/ragen/env/countdown/__pycache__/env.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5698062bd930675b8366c1cc6a62f96fac2964d Binary files /dev/null and b/ragen/env/countdown/__pycache__/env.cpython-310.pyc differ diff --git a/ragen/env/countdown/config.py b/ragen/env/countdown/config.py new file mode 100644 index 0000000000000000000000000000000000000000..3001f841c3a44b50e80fc3869af1c54803e17ab1 --- /dev/null +++ b/ragen/env/countdown/config.py @@ -0,0 +1,11 @@ + +from ragen.env.base import BaseEnvConfig +from dataclasses import dataclass + +@dataclass +class CountdownEnvConfig: + train_path: str = "data/countdown/train.parquet" + max_instances: int = 20000 + render_mode: str = "text" + score = 1 + format_score = 0.1 \ No newline at end of file diff --git a/ragen/env/countdown/env.py b/ragen/env/countdown/env.py new file mode 100644 index 0000000000000000000000000000000000000000..5c4068680dd830e6726c32d8e96777cc17af2811 --- /dev/null +++ b/ragen/env/countdown/env.py @@ -0,0 +1,93 @@ +import gymnasium as gym +from ragen.env.base import BaseLanguageBasedEnv +import datasets +import re +import itertools +from .config import CountdownEnvConfig + + +def check_format(equation, nums): + try: + nums_in_eq = [int(n) for n in re.findall(r'\d+', equation)] + return sorted(nums_in_eq) == sorted(nums) + except: + return False + +def check_correctness(equation_str, target): + try: + result = eval(equation_str, {"__builtins__": None}, {}) + return abs(result - target) < 1e-5 + except: + return False + +def has_solution(nums, target): + """Check if there is a valid equation using each number exactly once.""" + # pad nums all to 4 numbers + length = 4 + nums = nums + [0] * (length - len(nums)) + # +- num1 +- num2 +- num3 +- num4 = target, try all + combinations = list(itertools.product([1, -1], repeat=length)) + for combination in combinations: + if sum(combination[i] * nums[i] for i in range(length)) == target: + return True + return False + + +class CountdownEnv(BaseLanguageBasedEnv, gym.Env): + def __init__(self, config=None): + BaseLanguageBasedEnv.__init__(self) + self.config = config if config is not None else CountdownEnvConfig() + self.data = self._get_data_from_parquet(self.config.train_path) + self.index = None + self.render_cache = None + self.render_mode = self.config.render_mode + assert self.render_mode == 'text' + + def _get_data_from_parquet(self, path): + df = datasets.load_dataset("parquet", data_files=path)['train'].select(range(self.config.max_instances)) + df = df.filter(lambda x: has_solution(x['nums'], x['target'])) + return df + + def reset(self, seed=None, mode=None): + gym.Env.reset(self, seed=seed) + self.index = seed % len(self.data) + data = self.data[self.index] + self.render_cache = f"Target: {data['target']}, nums: {data['nums']}" + return self.render_cache + + def step(self, action): + reward = self.compute_reward(action, self.data[self.index]) + next_obs, done, info = f"Your answer get {reward} points.", True, {"action_is_effective": reward > 0, "action_is_valid": True, "success": reward == self.config.score} + self.render_cache = next_obs + return next_obs, reward, done, info + + def render(self): + return self.render_cache + + + + def compute_reward(self, action, ground_truth): + """Score the countdown task solution.""" + target = ground_truth['target'] + nums = ground_truth['nums'] + if not check_format(action, nums): + return 0 + if not check_correctness(action, target): + return self.config.format_score + else: + return self.config.score + + def close(self): + pass + +if __name__ == "__main__": + def test(path, seed=43): + config = CountdownEnvConfig(train_path=path) + env = CountdownEnv(config) + obs = env.reset(seed=seed) + problem = env.data[env.index] + solution = f"- {problem['nums'][0]} + {problem['nums'][1]} + {problem['nums'][2]}" + _, reward, _, _ = env.step(solution) + print(f"{obs}\nSolution: {solution}, Reward: {reward}") + + test("data/countdown/train.parquet") \ No newline at end of file diff --git a/ragen/env/frozen_lake.png b/ragen/env/frozen_lake.png new file mode 100644 index 0000000000000000000000000000000000000000..92157df2d461ae8d76d10018cdcd378006bade75 --- /dev/null +++ b/ragen/env/frozen_lake.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af337915f437cc2eb4202b03880c8939bb29391ebc76ba77979e66db669aa5fb +size 6663 diff --git a/ragen/env/frozen_lake/__init__.py b/ragen/env/frozen_lake/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f6acdf3bb5aea6fbf166025539cd032e90137ee4 --- /dev/null +++ b/ragen/env/frozen_lake/__init__.py @@ -0,0 +1,45 @@ +""" +Adapted from the nicely written code from gymnasium.envs.toy_text.frozen_lake.generate_random_map +Modify it so that the start and end points are random + +## Description +The game starts with the player at random location of the frozen lake grid world with the +goal located at another random location for the 4x4 environment. + +## Action Space +The action shape is `(1,)` in the range `{0, 3}` indicating +which direction to move the player. +NOTE the action space is different from gymnasium.envs.toy_text.frozen_lake.FrozenLakeEnv, start from 1 +- 0: Still +- 1: Left +- 2: Down +- 3: Right +- 4: Up + +## Starting State +The episode starts with the player at random location + +## Rewards +NOTE added -0.1 as penalty for invalid action +Reward schedule: +- Reach goal: +1 +- Reach hole: 0 +- Reach frozen: 0 + +## Arguments +`is_slippery`: if action is left and is_slippery is True, then: +- P(move left)=1/3 +- P(move up)=1/3 +- P(move down)=1/3 + +## Example +P _ _ _ +_ _ _ O +O _ O _ +O _ _ G +""" + +from .env import FrozenLakeEnv +from .config import FrozenLakeEnvConfig + +__all__ = ["FrozenLakeEnv", "FrozenLakeEnvConfig"] diff --git a/ragen/env/frozen_lake/__pycache__/__init__.cpython-310.pyc b/ragen/env/frozen_lake/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df1cf2dbae8e76747a4c9a63088626e2310a398b Binary files /dev/null and b/ragen/env/frozen_lake/__pycache__/__init__.cpython-310.pyc differ diff --git a/ragen/env/frozen_lake/__pycache__/config.cpython-310.pyc b/ragen/env/frozen_lake/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7c8041b45808dafc8142c70fa11d89fd4936999 Binary files /dev/null and b/ragen/env/frozen_lake/__pycache__/config.cpython-310.pyc differ diff --git a/ragen/env/frozen_lake/__pycache__/env.cpython-310.pyc b/ragen/env/frozen_lake/__pycache__/env.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ef45c4ae45acf1d071479ff83836ec042b4064f Binary files /dev/null and b/ragen/env/frozen_lake/__pycache__/env.cpython-310.pyc differ diff --git a/ragen/env/frozen_lake/__pycache__/utils.cpython-310.pyc b/ragen/env/frozen_lake/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e163d1caac4cd4c65b91590501b46899e8f54949 Binary files /dev/null and b/ragen/env/frozen_lake/__pycache__/utils.cpython-310.pyc differ diff --git a/ragen/env/frozen_lake/config.py b/ragen/env/frozen_lake/config.py new file mode 100644 index 0000000000000000000000000000000000000000..de054f403b9dc240e9fafcaafe6950b7ee442ae0 --- /dev/null +++ b/ragen/env/frozen_lake/config.py @@ -0,0 +1,28 @@ +from typing import Optional, List, Dict +from dataclasses import dataclass, field + +@dataclass +class FrozenLakeEnvConfig: + """Configuration for FrozenLake environment""" + # Map config + size: int = 4 + p: float = 0.9 + success_rate: float = 0.8 + is_slippery: bool = True + map_seed: Optional[int] = None + render_mode: str = "text" + observation_format: str = "grid" + + # Mappings + action_map: Dict[int, int] = field(default_factory=lambda: {1: 0, 2: 1, 3: 2, 4: 3}) + map_lookup: Dict[bytes, int] = field( + default_factory=lambda: {b"P": 0, b"F": 1, b"H": 2, b"G": 3} + ) # b'' string is used for vectorization in numpy + # P: Player; F: Frozen; H: Hole; G: Goal + grid_lookup: Dict[int, str] = field(default_factory=lambda: {0:"P", 1:"_", 2:"O", 3:"G", 4:"X", 5:"√"}) + grid_vocab: Dict[str, str] = field(default_factory=lambda: {"P": "player", "_": "empty", "O": "hole", "G": "goal", "X": "player in hole", "√": "player on goal"}) + action_lookup: Dict[int, str] = field(default_factory=lambda: {1:"Left", 2:"Down", 3:"Right", 4:"Up"}) + + def __post_init__(self): + if self.observation_format not in {"grid", "coord", "grid_coord"}: + raise ValueError(f"Unsupported observation_format: {self.observation_format}") diff --git a/ragen/env/frozen_lake/env.py b/ragen/env/frozen_lake/env.py new file mode 100644 index 0000000000000000000000000000000000000000..eef11d87e630d21618d16a737120af6dfab5df93 --- /dev/null +++ b/ragen/env/frozen_lake/env.py @@ -0,0 +1,112 @@ +import gymnasium as gym +from gymnasium.envs.toy_text.frozen_lake import FrozenLakeEnv as GymFrozenLakeEnv +import numpy as np +from .config import FrozenLakeEnvConfig +from .utils import ( + generate_random_map, + collect_entity_coordinates, + format_coordinate_render, +) +from ragen.utils import all_seed +from ragen.env.base import BaseDiscreteActionEnv + +class FrozenLakeEnv(BaseDiscreteActionEnv, GymFrozenLakeEnv): + def __init__(self, config: FrozenLakeEnvConfig = FrozenLakeEnvConfig()): + # Using mappings directly from config + # import pdb;pdb.set_trace() + self.config = config + self.GRID_LOOKUP = config.grid_lookup + self.ACTION_LOOKUP = config.action_lookup + self.ACTION_SPACE = gym.spaces.discrete.Discrete(4, start=1) + self.render_mode = config.render_mode + self.action_map = config.action_map + self.MAP_LOOKUP = config.map_lookup + self.observation_format = config.observation_format + random_map = generate_random_map(size=config.size, p=config.p, seed=config.map_seed) + BaseDiscreteActionEnv.__init__(self) + GymFrozenLakeEnv.__init__( + self, + desc=random_map, + is_slippery=config.is_slippery, + render_mode=config.render_mode, + success_rate=config.success_rate + ) + + def reset(self, seed=None, mode=None): + try: + with all_seed(seed): + self.config.map_seed = seed + self.__init__(self.config) + GymFrozenLakeEnv.reset(self, seed=seed) + return self.render() + except (RuntimeError, RuntimeWarning) as e: + next_seed = abs(hash(str(seed))) % (2 ** 32) if seed is not None else None + return self.reset(next_seed) + + def step(self, action: int): + prev_pos = int(self.s) + _, reward, done, _, _ = GymFrozenLakeEnv.step(self, self.action_map[action]) + next_obs = self.render() + info = {"action_is_effective": prev_pos != int(self.s), "action_is_valid": True, "success": self.desc[self.player_pos] == b"G"} + + return next_obs, reward, done, info + + def render(self, mode=None): + if mode in {'grid', 'coord', 'grid_coord'}: + return self._render_text(mode) + + render_mode = mode if mode is not None else self.render_mode + if render_mode == 'text': + return self._render_text(self.observation_format) + if render_mode == 'rgb_array': + return self._render_gui('rgb_array') + raise ValueError(f"Invalid mode: {render_mode}") + + def _render_text(self, observation_format: str) -> str: + if observation_format == 'grid': + room = self.desc.copy() + # replace the position of start 'S' with 'F', mark the position of the player as 'P'. + room = np.where(room == b'S', b'F', room) + room[self.player_pos] = b'P' + room = np.vectorize(lambda x: self.MAP_LOOKUP[x])(room) + # add player in hole or player on goal + room[self.player_pos] = 4 if self.desc[self.player_pos] == b'H' else 5 if self.desc[self.player_pos] == b'G' else 0 + + return '\n'.join(''.join(self.GRID_LOOKUP.get(cell, "?") for cell in row) for row in room) + if observation_format == 'coord': + entity_coords = collect_entity_coordinates(self.desc, self.player_pos) + return format_coordinate_render(entity_coords, self.desc.shape) + if observation_format == 'grid_coord': + entity_coords = collect_entity_coordinates(self.desc, self.player_pos) + coord_render = format_coordinate_render(entity_coords, self.desc.shape) + return "Coordinates: \n" + coord_render + "\n" + "Grid Map: \n" + self._render_text('grid') + raise ValueError(f"Invalid observation_format: {observation_format}") + + def get_all_actions(self): + return list([k for k in self.ACTION_LOOKUP.keys()]) + + @property + def player_pos(self): + return (self.s // self.ncol, self.s % self.ncol) # (row, col) + + def close(self): + self.render_cache = None + super(FrozenLakeEnv, self).close() + +if __name__ == "__main__": + import matplotlib.pyplot as plt + config = FrozenLakeEnvConfig(size=4, is_slippery=True) + # import pdb;pdb.set_trace() + env = FrozenLakeEnv(config) + print(env.reset()) + while True: + keyboard = input("Enter action: ") + if keyboard == 'q': + break + action = int(keyboard) + assert action in env.ACTION_LOOKUP, f"Invalid action: {action}" + obs, reward, done, info = env.step(action) + print(obs, reward, done, info) + np_img = env.render('rgb_array') + # save the image + plt.imsave('frozen_lake.png', np_img) diff --git a/ragen/env/frozen_lake/utils.py b/ragen/env/frozen_lake/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..086095c739b0b303ba6d394ae4a00ac7bb1b44c0 --- /dev/null +++ b/ragen/env/frozen_lake/utils.py @@ -0,0 +1,111 @@ +import numpy as np +from typing import Dict, List, Optional, Tuple +from gymnasium.utils import seeding + +CoordDict = Dict[str, List[Tuple[int, int]]] + + +def _to_tuple_list(array: np.ndarray, index_origin: int = 0) -> List[Tuple[int, int]]: + if array.size == 0: + return [] + return [(int(r) + index_origin, int(c) + index_origin) for r, c in array] + + +def collect_entity_coordinates(desc: np.ndarray, player_pos: Tuple[int, int], index_origin: int = 0) -> CoordDict: + """Collect coordinates for key FrozenLake entities.""" + + coords: CoordDict = {} + + start_coords = _to_tuple_list(np.argwhere(desc == b"S"), index_origin) + if start_coords: + coords["start"] = start_coords + + goal_coords = _to_tuple_list(np.argwhere(desc == b"G"), index_origin) + if goal_coords: + coords["goal"] = goal_coords + + hole_coords = _to_tuple_list(np.argwhere(desc == b"H"), index_origin) + if hole_coords: + coords["holes"] = hole_coords + + player_row, player_col = player_pos + player_tile = desc[player_row, player_col] + player_coord = (player_row + index_origin, player_col + index_origin) + + if player_tile == b"G": + coords["player_on_goal"] = [player_coord] + elif player_tile == b"H": + coords["player_in_hole"] = [player_coord] + else: + coords["player"] = [player_coord] + + return coords + + +def format_coordinate_render(entity_coords: CoordDict, board_shape: Tuple[int, int], index_origin: int = 0) -> str: + """Format FrozenLake entities into a coordinate description.""" + + rows, cols = board_shape + origin_str = "zero-indexed" if index_origin == 0 else f"origin at {index_origin}" + lines = [f"Board size: {rows} rows x {cols} cols ({origin_str})."] + + ordered_labels = [ + ("start", "Start"), + ("goal", "Goal"), + ("player", "Player"), + ("player_on_goal", "Player on goal"), + ("player_in_hole", "Player in hole"), + ("holes", "Holes"), + ] + + for key, label in ordered_labels: + coords = entity_coords.get(key, []) + if not coords: + continue + coord_str = ", ".join(f"({r}, {c})" for r, c in coords) + lines.append(f"{label}: {coord_str}") + + return "\n".join(lines) + +def is_valid(board: List[List[str]], max_size: int) -> bool: + frontier, discovered = [], set() + start_r, start_c = np.where(np.array(board) == "S") + frontier.append((start_r[0], start_c[0])) + + while frontier: + r, c = frontier.pop() + if (r, c) not in discovered: + discovered.add((r, c)) + for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]: + r_new, c_new = r + dr, c + dc + if 0 <= r_new < max_size and 0 <= c_new < max_size: + if board[r_new][c_new] == "G": + return True + if board[r_new][c_new] != "H": + frontier.append((r_new, c_new)) + return False + + +def generate_random_map(size: int = 8, p: float = 0.85, seed: Optional[int] = None) -> List[str]: + """ + Generates a random valid map with a path from start (S) to goal (G). + Args: + size: The size of the map. + p: The probability of generating a frozen tile (F). + seed: The seed for the random number generator. + Returns: + A list of strings representing the map. + """ + np_random, _ = seeding.np_random(seed) + + while True: + board = np_random.choice(["F", "H"], (size, size), p=[p, 1 - p]) + start_r, start_c = np_random.integers(size, size=2) + goal_r, goal_c = np_random.integers(size, size=2) + + if (start_r, start_c) != (goal_r, goal_c): + board[start_r][start_c], board[goal_r][goal_c] = "S", "G" + if is_valid(board, size): + break + + return ["".join(row) for row in board] diff --git a/ragen/env/game_2048/__init__.py b/ragen/env/game_2048/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..62f6f2a3f627a0efd1c352df0e7adf18c4e86fbc --- /dev/null +++ b/ragen/env/game_2048/__init__.py @@ -0,0 +1,2 @@ +from .config import Game2048EnvConfig +from .env import Game2048Env \ No newline at end of file diff --git a/ragen/env/game_2048/__pycache__/__init__.cpython-310.pyc b/ragen/env/game_2048/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56160a4a4b323fc54b4c1b8556dd305f0be63354 Binary files /dev/null and b/ragen/env/game_2048/__pycache__/__init__.cpython-310.pyc differ diff --git a/ragen/env/game_2048/__pycache__/config.cpython-310.pyc b/ragen/env/game_2048/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0836f2468b1aef6e271ac5dbd1e543f184add7ea Binary files /dev/null and b/ragen/env/game_2048/__pycache__/config.cpython-310.pyc differ diff --git a/ragen/env/game_2048/__pycache__/env.cpython-310.pyc b/ragen/env/game_2048/__pycache__/env.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbaad9ac60d93ad0da21464dbe15ae4fb1998ccc Binary files /dev/null and b/ragen/env/game_2048/__pycache__/env.cpython-310.pyc differ diff --git a/ragen/env/game_2048/__pycache__/env_api.cpython-310.pyc b/ragen/env/game_2048/__pycache__/env_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14a45be8f7f7f6834600818235bf05e5997aaf2a Binary files /dev/null and b/ragen/env/game_2048/__pycache__/env_api.cpython-310.pyc differ diff --git a/ragen/env/game_2048/config.py b/ragen/env/game_2048/config.py new file mode 100644 index 0000000000000000000000000000000000000000..2dee7846a71c6784c37083c5fc54b325264bb872 --- /dev/null +++ b/ragen/env/game_2048/config.py @@ -0,0 +1,24 @@ +from dataclasses import dataclass +import gymnasium as gym +from ragen.env.base import BaseEnvConfig + + +@dataclass +class Game2048EnvConfig(BaseEnvConfig): + size: int = 4 + two_prob: float = 0.9 + render_mode: str = "text" + action_lookup: dict = None + + # === 新增: 是否在环境内部应用 Log 奖励正则化 === + use_log_reward: bool = True + + def __post_init__(self): + if self.action_lookup is None: + self.action_lookup = {0: "Up", 1: "Right", 2: "Down", 3: "Left"} + + self.invalid_act = 0 + self.invalid_act_score = -0.1 + self.observation_format = "grid" + + self.ACTION_SPACE = gym.spaces.discrete.Discrete(4) \ No newline at end of file diff --git a/ragen/env/game_2048/env.py b/ragen/env/game_2048/env.py new file mode 100644 index 0000000000000000000000000000000000000000..547308c4b566b45f052528e21ef402b828c30ed2 --- /dev/null +++ b/ragen/env/game_2048/env.py @@ -0,0 +1,245 @@ +import gymnasium as gym +import numpy as np +from typing import Tuple, Any, Dict, List +from ragen.env.base import BaseDiscreteActionEnv +from .config import Game2048EnvConfig +from ragen.utils import all_seed + + +class Game2048Env(BaseDiscreteActionEnv, gym.Env): + def __init__(self, config: Game2048EnvConfig | None = None): + BaseDiscreteActionEnv.__init__(self) + self.config = config or Game2048EnvConfig() + self.size = self.config.size + self.two_prob = self.config.two_prob + self.render_mode = self.config.render_mode + self.ACTION_LOOKUP = self.config.action_lookup + + self.action_space = self.config.ACTION_SPACE + self.ACTION_SPACE = self.action_space + + self.observation_space = gym.spaces.Text(max_length=4096) + + self.grid = None + self.score = 0 + self.rng = np.random.default_rng() + + def reset(self, seed=None, mode=None, options=None): + gym.Env.reset(self, seed=seed, options=options) + with all_seed(seed): + self.rng = np.random.default_rng(seed) + self.grid = np.zeros((self.size, self.size), dtype=np.int64) + self.score = 0 + self._spawn_tile() + self._spawn_tile() + + info = { + "grid": self.grid.copy(), + "score": self.score, + "action_mask": self._get_action_mask(), + "raw_reward": 0.0 # 初始化 + } + return self.render(), info + + def step(self, action: int) -> Tuple[Any, float, bool, Dict]: + assert action in self.ACTION_LOOKUP, f"Invalid action: {action}" + + prev_grid = self.grid.copy() + reward_merge, moved = self._move(action) + + terminated = False + + # === 准备 Info === + info = { + "action_is_effective": moved, + "action_is_valid": True, + "success": False, + } + + # === 计算 Raw Reward === + raw_reward = 0.0 + if not moved: + info["action_is_valid"] = False + raw_reward = self.config.invalid_act_score + else: + self._spawn_tile() + # import pdb;pdb.set_trace() + self.score += reward_merge # Score 始终记录原始分数 + raw_reward = float(reward_merge) + + terminated = self._is_terminal() + if terminated: + info["max_tile"] = np.max(self.grid) + if np.max(self.grid) >= 2048: + info["success"] = True + + # === 奖励正则化 (Env 内部处理) === + # 逻辑:如果开启正则化,且 raw_reward > 0,则 log2(r+1)*0.1,否则为 0 + final_reward = raw_reward + if self.config.use_log_reward: + if raw_reward > 0: + final_reward = float(np.log2(raw_reward + 1.0)) * 0.1 + else: + final_reward = 0.0 # 无效移动或无合并时,正则化后奖励归零 (参考原 DQN 逻辑) + + # === 更新 Info === + info["grid"] = self.grid.copy() + info["action_mask"] = self._get_action_mask() + info["score"] = self.score # 累计原始分数 + info["raw_reward"] = raw_reward # 单步原始分数 (供 Logger 使用) + + next_obs = self.render() + done = terminated + + return next_obs, final_reward, done, info + + def render(self, mode: str | None = None) -> str: + lines: List[str] = [] + lines.append("Current 2048 Grid:") + for i in range(self.size): + row = ", ".join(str(int(x)) for x in self.grid[i]) + lines.append(f"Row {i+1}: [{row}]") + + valid_actions = self._valid_actions() + actions_text = ", ".join(f"{a}({self.ACTION_LOOKUP[a]})" for a in valid_actions) if valid_actions else "None" + + lines.append("") + lines.append(f"Valid Actions: {actions_text}.") + lines.append("Goal: Merge same numbers to reach 2048.") + lines.append(f"Current Score: {self.score}") # 显示分数 + lines.append("What is your next move?") + return "\n".join(lines) + + def close(self): + pass + + def get_all_actions(self): + return list(self.ACTION_LOOKUP.keys()) + + # ---- 2048 helpers (保持不变) ---- + def _spawn_tile(self): + empties = list(zip(*np.where(self.grid == 0))) + if not empties: + return + r, c = empties[self.rng.integers(0, len(empties))] + value = 2 if self.rng.random() < self.two_prob else 4 + self.grid[r, c] = value + + def _valid_actions(self) -> List[int]: + valid = [] + for a in self.ACTION_LOOKUP.keys(): + tmp = self.grid.copy() + merged, moved = self._move_sim(tmp, a) + if moved: + valid.append(a) + return valid + + def _get_action_mask(self) -> np.ndarray: + mask = np.zeros(4, dtype=bool) + valid_indices = self._valid_actions() + for idx in valid_indices: + mask[idx] = True + return mask + + def _is_terminal(self) -> bool: + if np.any(self.grid == 0): + return False + for a in self.ACTION_LOOKUP.keys(): + tmp = self.grid.copy() + _, moved = self._move_sim(tmp, a) + if moved: + return False + return True + + def _move(self, action: int) -> Tuple[int, bool]: + grid = self.grid + before = grid.copy() + reward, moved = self._move_sim(grid, action) + return reward, moved + + def _move_sim(self, grid: np.ndarray, action: int) -> Tuple[int, bool]: + if action == 0: return self._compress_and_merge(grid, axis=0, reverse=False) + if action == 1: return self._compress_and_merge(grid, axis=1, reverse=True) + if action == 2: return self._compress_and_merge(grid, axis=0, reverse=True) + if action == 3: return self._compress_and_merge(grid, axis=1, reverse=False) + raise ValueError(f"Unknown action {action}") + + def _compress_and_merge(self, grid: np.ndarray, axis: int, reverse: bool) -> Tuple[int, bool]: + reward = 0 + moved_any = False + size = grid.shape[axis] + other = 1 - axis + for fixed in range(grid.shape[other]): + if axis == 0: line = grid[:, fixed] + else: line = grid[fixed, :] + if reverse: line = line[::-1] + + vals = line[line != 0].tolist() + merged = [] + i = 0 + while i < len(vals): + if i + 1 < len(vals) and vals[i] == vals[i + 1]: + m = vals[i] * 2 + reward += m + merged.append(m) + i += 2 + else: + merged.append(vals[i]) + i += 1 + + merged += [0] * (size - len(merged)) + new_line = np.array(merged, dtype=np.int64) + if reverse: new_line = new_line[::-1] + + if axis == 0: + before_segment = grid[:, fixed].copy() + grid[:, fixed] = new_line + if not np.array_equal(before_segment, new_line): moved_any = True + else: + before_segment = grid[fixed, :].copy() + grid[fixed, :] = new_line + if not np.array_equal(before_segment, new_line): moved_any = True + + return reward, moved_any + +if __name__ == "__main__": + def demo(seed: int = 42, steps: int = 700): + env = Game2048Env() + obs, info = env.reset(seed=seed) + print(f"Start Info: Score={info['score']}, RawReward={info['raw_reward']}") + print(f"obs:{obs}") + key_map = { + 'w': 0, # 上 + 'd': 1, # 右 + 's': 2, # 下 + 'a': 3, # 左 + 'q': -1 # 退出 + } + + for t in range(steps): + actions = env.get_all_actions() + # a = np.random.choice(actions) + valid_input = False + a = 0 + while not valid_input: + user_input = input(f"\n[Step {t+1}] 请输入动作 (w/a/s/d): ").strip().lower() + + if user_input in key_map: + a = key_map[user_input] + if a == -1: + print("手动退出游戏") + return + valid_input = True + else: + print("输入无效,请重新输入 (w/a/s/d)") + # 注意: 这里的 reward 是正则化后的 + obs, reward, done, info = env.step(int(a)) + # import pdb;pdb.set_trace() + print(f"obs:{obs}") + action_name = env.ACTION_LOOKUP[int(a)] + print(f"\nStep {t+1}, Action: {a} ({action_name})") + print(f"Log Reward: {reward:.4f} | Raw Reward: {info['raw_reward']} | Total Score: {info['score']}") + if done: + print("Game Over") + break + demo() \ No newline at end of file diff --git a/ragen/env/game_2048/env_api.py b/ragen/env/game_2048/env_api.py new file mode 100644 index 0000000000000000000000000000000000000000..07e55982100e2ec72d7c2f0264a09cadf2851028 --- /dev/null +++ b/ragen/env/game_2048/env_api.py @@ -0,0 +1,272 @@ +import gymnasium as gym +import numpy as np +from typing import Tuple, Any, Dict, List +from ragen.env.base import BaseDiscreteActionEnv +from .config import Game2048EnvConfig +from ragen.utils import all_seed +import re +from openai import OpenAI + +class Game2048Env(BaseDiscreteActionEnv, gym.Env): + def __init__(self, config: Game2048EnvConfig | None = None): + BaseDiscreteActionEnv.__init__(self) + self.config = config or Game2048EnvConfig() + self.size = self.config.size + self.two_prob = self.config.two_prob + self.render_mode = self.config.render_mode + self.ACTION_LOOKUP = self.config.action_lookup + + self.action_space = self.config.ACTION_SPACE + self.ACTION_SPACE = self.action_space + + self.observation_space = gym.spaces.Text(max_length=4096) + + self.grid = None + self.score = 0 + self.rng = np.random.default_rng() + + def reset(self, seed=None, mode=None, options=None): + gym.Env.reset(self, seed=seed, options=options) + with all_seed(seed): + self.rng = np.random.default_rng(seed) + self.grid = np.zeros((self.size, self.size), dtype=np.int64) + self.score = 0 + self._spawn_tile() + self._spawn_tile() + + info = { + "grid": self.grid.copy(), + "score": self.score, + "action_mask": self._get_action_mask(), + "raw_reward": 0.0 # 初始化 + } + return self.render(), info + + def step(self, action: int) -> Tuple[Any, float, bool, Dict]: + assert action in self.ACTION_LOOKUP, f"Invalid action: {action}" + + prev_grid = self.grid.copy() + reward_merge, moved = self._move(action) + + terminated = False + + # === 准备 Info === + info = { + "action_is_effective": moved, + "action_is_valid": True, + "success": False, + } + + # === 计算 Raw Reward === + raw_reward = 0.0 + if not moved: + info["action_is_valid"] = False + raw_reward = self.config.invalid_act_score + else: + self._spawn_tile() + # import pdb;pdb.set_trace() + self.score += reward_merge # Score 始终记录原始分数 + raw_reward = float(reward_merge) + + terminated = self._is_terminal() + if terminated: + info["max_tile"] = np.max(self.grid) + if np.max(self.grid) >= 2048: + info["success"] = True + + # === 奖励正则化 (Env 内部处理) === + # 逻辑:如果开启正则化,且 raw_reward > 0,则 log2(r+1)*0.1,否则为 0 + final_reward = raw_reward + if self.config.use_log_reward: + if raw_reward > 0: + final_reward = float(np.log2(raw_reward + 1.0)) * 0.1 + else: + final_reward = 0.0 # 无效移动或无合并时,正则化后奖励归零 (参考原 DQN 逻辑) + + # === 更新 Info === + info["grid"] = self.grid.copy() + info["action_mask"] = self._get_action_mask() + info["score"] = self.score # 累计原始分数 + info["raw_reward"] = raw_reward # 单步原始分数 (供 Logger 使用) + + next_obs = self.render() + done = terminated + + return next_obs, final_reward, done, info + + def render(self, mode: str | None = None) -> str: + lines: List[str] = [] + lines.append("Current 2048 Grid:") + for i in range(self.size): + row = ", ".join(str(int(x)) for x in self.grid[i]) + lines.append(f"Row {i+1}: [{row}]") + + valid_actions = self._valid_actions() + actions_text = ", ".join(f"{a}({self.ACTION_LOOKUP[a]})" for a in valid_actions) if valid_actions else "None" + + lines.append("") + lines.append(f"Valid Actions: {actions_text}.") + lines.append("Goal: Merge same numbers to reach 2048.") + lines.append(f"Current Score: {self.score}") # 显示分数 + lines.append("What is your next move?") + return "\n".join(lines) + + def close(self): + pass + + def get_all_actions(self): + return list(self.ACTION_LOOKUP.keys()) + + # ---- 2048 helpers (保持不变) ---- + def _spawn_tile(self): + empties = list(zip(*np.where(self.grid == 0))) + if not empties: + return + r, c = empties[self.rng.integers(0, len(empties))] + value = 2 if self.rng.random() < self.two_prob else 4 + self.grid[r, c] = value + + def _valid_actions(self) -> List[int]: + valid = [] + for a in self.ACTION_LOOKUP.keys(): + tmp = self.grid.copy() + merged, moved = self._move_sim(tmp, a) + if moved: + valid.append(a) + return valid + + def _get_action_mask(self) -> np.ndarray: + mask = np.zeros(4, dtype=bool) + valid_indices = self._valid_actions() + for idx in valid_indices: + mask[idx] = True + return mask + + def _is_terminal(self) -> bool: + if np.any(self.grid == 0): + return False + for a in self.ACTION_LOOKUP.keys(): + tmp = self.grid.copy() + _, moved = self._move_sim(tmp, a) + if moved: + return False + return True + + def _move(self, action: int) -> Tuple[int, bool]: + grid = self.grid + before = grid.copy() + reward, moved = self._move_sim(grid, action) + return reward, moved + + def _move_sim(self, grid: np.ndarray, action: int) -> Tuple[int, bool]: + if action == 0: return self._compress_and_merge(grid, axis=0, reverse=False) + if action == 1: return self._compress_and_merge(grid, axis=1, reverse=True) + if action == 2: return self._compress_and_merge(grid, axis=0, reverse=True) + if action == 3: return self._compress_and_merge(grid, axis=1, reverse=False) + raise ValueError(f"Unknown action {action}") + + def _compress_and_merge(self, grid: np.ndarray, axis: int, reverse: bool) -> Tuple[int, bool]: + reward = 0 + moved_any = False + size = grid.shape[axis] + other = 1 - axis + for fixed in range(grid.shape[other]): + if axis == 0: line = grid[:, fixed] + else: line = grid[fixed, :] + if reverse: line = line[::-1] + + vals = line[line != 0].tolist() + merged = [] + i = 0 + while i < len(vals): + if i + 1 < len(vals) and vals[i] == vals[i + 1]: + m = vals[i] * 2 + reward += m + merged.append(m) + i += 2 + else: + merged.append(vals[i]) + i += 1 + + merged += [0] * (size - len(merged)) + new_line = np.array(merged, dtype=np.int64) + if reverse: new_line = new_line[::-1] + + if axis == 0: + before_segment = grid[:, fixed].copy() + grid[:, fixed] = new_line + if not np.array_equal(before_segment, new_line): moved_any = True + else: + before_segment = grid[fixed, :].copy() + grid[fixed, :] = new_line + if not np.array_equal(before_segment, new_line): moved_any = True + + return reward, moved_any + +if __name__ == "__main__": + client = OpenAI( + api_key="empty", + base_url="http://localhost:8000/v1", + ) + def get_gpt_action(obs, valid_actions): + """将游戏状态发给 GPT 并获取动作""" + # 构造 Prompt + system_text = f""" + 我在玩 2048 游戏,请根据当前的棋盘状态给出下一步动作。 + 注意:只需返回动作对应的数字0(上), 1(右), 2(下), 或 3(左)。""" + + input_text = f"""{obs} + + Valid Actions: {valid_actions} + 请直接输出数字:""" + + completion = client.chat.completions.create( + model="/mnt/general/share/model/openai/gpt-oss-120b", + messages=[{ + "role": "system", + "content": system_text + },{"role": "user", "content": input_text}], + temperature=0 # 建议设为0,保证逻辑稳定 + ) + + response = completion.choices[0].message.content.strip() + print(f"GPT 建议响应: {response}") + + # 使用正则表达式提取第一个出现的数字 + match = re.search(r'[0-3]', response) + if match: + return int(match.group()) + else: + # 如果模型没按格式返回,默认选第一个有效动作 + print("警告:模型未返回有效数字,执行默认动作") + return valid_actions[0] + + def demo(seed: int = 42, steps: int = 700): + env = Game2048Env() + obs, info = env.reset(seed=seed) + + for t in range(steps): + # 1. 获取当前有效动作 + actions = env.get_all_actions() + + # 2. 将 obs 转换成字符串 (如果是 numpy array 需转成易读格式) + # 假设 env.step 返回的 obs 已经包含类似 "Row 1: [0, 2, 0, 0]" 的文本 + # 如果 obs 是 raw matrix,你需要写个简易转换函数 + + # 3. 让 GPT 决定动作 + print(f"\n[Step {t+1}] 正在请求 GPT...") + a = get_gpt_action(obs, actions) + + # 4. 执行动作 + obs, reward, done, info = env.step(int(a)) + + # 打印状态 + action_name = env.ACTION_LOOKUP[int(a)] + print(f"obs:\n{obs}") + print(f"Step {t+1}, Action: {a} ({action_name})") + print(f"Score: {info['score']}") + + if done: + print("Game Over") + break + demo() \ No newline at end of file diff --git a/ragen/env/lean/__init__.py b/ragen/env/lean/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..695693faac5ae9021391fe4bd121ca897061c9bd --- /dev/null +++ b/ragen/env/lean/__init__.py @@ -0,0 +1,1480 @@ +""" +Lean RAGEN environment based on kimina-lean-server. +""" +# TODO: Add instructions on how to configure the lean environment. + +from .config import LeanEnvConfig +from .env import LeanEnv + +__all__ = ["LeanEnv", "LeanEnvConfig"] + +""" +Below is an example of a mock LLM Agent interacting with the environment when solving a complex problem. +We manually inserted two invalid tactics to show how our Lean environment accepts tactics. +(An invalid tactic will not be appended to the code snippet to allow the LLM Agent to correct their actions) + +Initial observation shown to the LLM: +Steps taken: 0/400 | accepted tactics: 0 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + +--- Step 1 --- +LLM proposes tactic: have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 1/400 | accepted tactics: 1 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + +Proof log (latest 5 steps): + 01. have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 3:61] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : (a + b + c) ^ 2 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +⊢ a * b + b * c + c * a = -8 + +--- Step 2 --- +LLM proposes tactic: rw[h1] at h3 +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 2/400 | accepted tactics: 2 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + +Proof log (latest 5 steps): + 01. have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring [✓ accepted] + 02. rw[h1] at h3 [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 4:14] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 ^ 2 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +⊢ a * b + b * c + c * a = -8 + +--- Step 3 --- +LLM proposes tactic: simp at h3 +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 3/400 | accepted tactics: 3 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + +Proof log (latest 5 steps): + 01. have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring [✓ accepted] + 02. rw[h1] at h3 [✓ accepted] + 03. simp at h3 [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 5:12] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +⊢ a * b + b * c + c * a = -8 + +--- Step 4 --- +LLM proposes tactic: -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 4/400 | accepted tactics: 4 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + +Proof log (latest 5 steps): + 01. have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring [✓ accepted] + 02. rw[h1] at h3 [✓ accepted] + 03. simp at h3 [✓ accepted] + 04. -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 5:12] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +⊢ a * b + b * c + c * a = -8 + +--- Step 5 --- +LLM proposes tactic: have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 5/400 | accepted tactics: 5 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + +Proof log (latest 5 steps): + 01. have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring [✓ accepted] + 02. rw[h1] at h3 [✓ accepted] + 03. simp at h3 [✓ accepted] + 04. -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. [✓ accepted] + 05. have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 7:100] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h4 : + (a + b + c) * (a ^ 3 + b ^ 3 + c ^ 3) - (a ^ 4 + b ^ 4 + c ^ 4) = + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) +⊢ a * b + b * c + c * a = -8 + +--- Step 6 --- +LLM proposes tactic: rw[h1,h2] at h4 +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 6/400 | accepted tactics: 6 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + +Proof log (latest 5 steps): + ... (1 earlier steps omitted) + 02. rw[h1] at h3 [✓ accepted] + 03. simp at h3 [✓ accepted] + 04. -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. [✓ accepted] + 05. have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf [✓ accepted] + 06. rw[h1,h2] at h4 [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 8:17] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h4 : 0 * (a ^ 3 + b ^ 3 + c ^ 3) - 128 = a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) +⊢ a * b + b * c + c * a = -8 + +--- Step 7 --- +LLM proposes tactic: simp at h4 +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 7/400 | accepted tactics: 7 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + +Proof log (latest 5 steps): + ... (2 earlier steps omitted) + 03. simp at h3 [✓ accepted] + 04. -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. [✓ accepted] + 05. have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf [✓ accepted] + 06. rw[h1,h2] at h4 [✓ accepted] + 07. simp at h4 [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 9:12] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h4 : -128 = a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) +⊢ a * b + b * c + c * a = -8 + +--- Step 8 --- +LLM proposes tactic: have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 8/400 | accepted tactics: 8 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + +Proof log (latest 5 steps): + ... (3 earlier steps omitted) + 04. -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. [✓ accepted] + 05. have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf [✓ accepted] + 06. rw[h1,h2] at h4 [✓ accepted] + 07. simp at h4 [✓ accepted] + 08. have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 10:76] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h4 : -128 = a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +⊢ a * b + b * c + c * a = -8 + +--- Step 9 --- +LLM proposes tactic: rw[h5] +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 9/400 | accepted tactics: 9 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + +Proof log (latest 5 steps): + ... (4 earlier steps omitted) + 05. have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf [✓ accepted] + 06. rw[h1,h2] at h4 [✓ accepted] + 07. simp at h4 [✓ accepted] + 08. have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith [✓ accepted] + 09. rw[h5] [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 11:8] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h4 : -128 = a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +⊢ -(a ^ 2 + b ^ 2 + c ^ 2) / 2 = -8 + +--- Step 10 --- +LLM proposes tactic: field_simp +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 10/400 | accepted tactics: 10 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + +Proof log (latest 5 steps): + ... (5 earlier steps omitted) + 06. rw[h1,h2] at h4 [✓ accepted] + 07. simp at h4 [✓ accepted] + 08. have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith [✓ accepted] + 09. rw[h5] [✓ accepted] + 10. field_simp [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 12:12] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h4 : -128 = a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +⊢ -c ^ 2 + (-b ^ 2 + -a ^ 2) = -(8 * 2) + +--- Step 11 --- +LLM proposes tactic: apply rfl +System info (Reward: -1.10 | Done: False | Accepted: False | Success: False) +Observation of LLM Agent: +Steps taken: 11/400 | accepted tactics: 10 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + +Proof log (latest 5 steps): + ... (6 earlier steps omitted) + 07. simp at h4 [✓ accepted] + 08. have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith [✓ accepted] + 09. rw[h5] [✓ accepted] + 10. field_simp [✓ accepted] + 11. apply rfl [✗ rejected] + +Last Lean feedback: + accepted: False + messages: +01. [ERROR 13:2 → 13:11] tactic 'apply' failed, failed to unify + ?a = ?a +with + -c ^ 2 + (-b ^ 2 + -a ^ 2) = -(8 * 2) +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h4 : -128 = a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +⊢ -c ^ 2 + (-b ^ 2 + -a ^ 2) = -(8 * 2) + +--- Step 12 --- +LLM proposes tactic: ring_nf +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 12/400 | accepted tactics: 11 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + +Proof log (latest 5 steps): + ... (7 earlier steps omitted) + 08. have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith [✓ accepted] + 09. rw[h5] [✓ accepted] + 10. field_simp [✓ accepted] + 11. apply rfl [✗ rejected] + 12. ring_nf [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 13:9] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h4 : -128 = a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 13 --- +LLM proposes tactic: have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 13/400 | accepted tactics: 12 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + +Proof log (latest 5 steps): + ... (8 earlier steps omitted) + 09. rw[h5] [✓ accepted] + 10. field_simp [✓ accepted] + 11. apply rfl [✗ rejected] + 12. ring_nf [✓ accepted] + 13. have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 14:144] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h4 : -128 = a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 14 --- +LLM proposes tactic: rw [h6] at h4 +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 14/400 | accepted tactics: 13 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + 17 | rw [h6] at h4 + +Proof log (latest 5 steps): + ... (9 earlier steps omitted) + 10. field_simp [✓ accepted] + 11. apply rfl [✗ rejected] + 12. ring_nf [✓ accepted] + 13. have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf [✓ accepted] + 14. rw [h6] at h4 [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 15:15] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h4 : -128 = (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 15 --- +LLM proposes tactic: rw[h1] at h4 +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 15/400 | accepted tactics: 14 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + 17 | rw [h6] at h4 + 18 | rw[h1] at h4 + +Proof log (latest 5 steps): + ... (10 earlier steps omitted) + 11. apply rfl [✗ rejected] + 12. ring_nf [✓ accepted] + 13. have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf [✓ accepted] + 14. rw [h6] at h4 [✓ accepted] + 15. rw[h1] at h4 [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 16:14] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h4 : -128 = (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - 0 * a * b * c +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 16 --- +LLM proposes tactic: simp at h4 +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 16/400 | accepted tactics: 15 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + 17 | rw [h6] at h4 + 18 | rw[h1] at h4 + 19 | simp at h4 + +Proof log (latest 5 steps): + ... (11 earlier steps omitted) + 12. ring_nf [✓ accepted] + 13. have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf [✓ accepted] + 14. rw [h6] at h4 [✓ accepted] + 15. rw[h1] at h4 [✓ accepted] + 16. simp at h4 [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 17:12] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +h4 : -128 = (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 17 --- +LLM proposes tactic: have bogus : False := by trivial +System info (Reward: -1.10 | Done: False | Accepted: False | Success: False) +Observation of LLM Agent: +Steps taken: 17/400 | accepted tactics: 15 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + 17 | rw [h6] at h4 + 18 | rw[h1] at h4 + 19 | simp at h4 + +Proof log (latest 5 steps): + ... (12 earlier steps omitted) + 13. have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf [✓ accepted] + 14. rw [h6] at h4 [✓ accepted] + 15. rw[h1] at h4 [✓ accepted] + 16. simp at h4 [✓ accepted] + 17. have bogus : False := by trivial [✗ rejected] + +Last Lean feedback: + accepted: False + messages: +01. [ERROR 18:27 → 18:34] tactic 'assumption' failed +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +h4 : -128 = (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) +⊢ False +02. [UNSOLVED GOALS 2:64 → 18:34] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +h4 : -128 = (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) +bogus : False +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 18 --- +LLM proposes tactic: rw[h5] at h4 +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 18/400 | accepted tactics: 16 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + 17 | rw [h6] at h4 + 18 | rw[h1] at h4 + 19 | simp at h4 + 20 | rw[h5] at h4 + +Proof log (latest 5 steps): + ... (13 earlier steps omitted) + 14. rw [h6] at h4 [✓ accepted] + 15. rw[h1] at h4 [✓ accepted] + 16. simp at h4 [✓ accepted] + 17. have bogus : False := by trivial [✗ rejected] + 18. rw[h5] at h4 [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 18:14] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +h4 : -128 = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 * (a ^ 2 + b ^ 2 + c ^ 2) +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 19 --- +LLM proposes tactic: field_simp at h4 +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 19/400 | accepted tactics: 17 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + 17 | rw [h6] at h4 + 18 | rw[h1] at h4 + 19 | simp at h4 + 20 | rw[h5] at h4 + 21 | field_simp at h4 + +Proof log (latest 5 steps): + ... (14 earlier steps omitted) + 15. rw[h1] at h4 [✓ accepted] + 16. simp at h4 [✓ accepted] + 17. have bogus : False := by trivial [✗ rejected] + 18. rw[h5] at h4 [✓ accepted] + 19. field_simp at h4 [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 19:18] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +h4 : -(128 * 2) = (-c ^ 2 + (-b ^ 2 + -a ^ 2)) * (a ^ 2 + b ^ 2 + c ^ 2) +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 20 --- +LLM proposes tactic: have h7:((a ^ 2 + b ^ 2 + c ^ 2)/16)^2 = 1:= by linarith +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 20/400 | accepted tactics: 18 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + 17 | rw [h6] at h4 + 18 | rw[h1] at h4 + 19 | simp at h4 + 20 | rw[h5] at h4 + 21 | field_simp at h4 + 22 | have h7:((a ^ 2 + b ^ 2 + c ^ 2)/16)^2 = 1:= by linarith + +Proof log (latest 5 steps): + ... (15 earlier steps omitted) + 16. simp at h4 [✓ accepted] + 17. have bogus : False := by trivial [✗ rejected] + 18. rw[h5] at h4 [✓ accepted] + 19. field_simp at h4 [✓ accepted] + 20. have h7:((a ^ 2 + b ^ 2 + c ^ 2)/16)^2 = 1:= by linarith [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 20:58] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +h4 : -(128 * 2) = (-c ^ 2 + (-b ^ 2 + -a ^ 2)) * (a ^ 2 + b ^ 2 + c ^ 2) +h7 : ((a ^ 2 + b ^ 2 + c ^ 2) / 16) ^ 2 = 1 +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 21 --- +LLM proposes tactic: let C := (a ^ 2 + b ^ 2 + c ^ 2)/16 +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 21/400 | accepted tactics: 19 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + 17 | rw [h6] at h4 + 18 | rw[h1] at h4 + 19 | simp at h4 + 20 | rw[h5] at h4 + 21 | field_simp at h4 + 22 | have h7:((a ^ 2 + b ^ 2 + c ^ 2)/16)^2 = 1:= by linarith + 23 | let C := (a ^ 2 + b ^ 2 + c ^ 2)/16 + +Proof log (latest 5 steps): + ... (16 earlier steps omitted) + 17. have bogus : False := by trivial [✗ rejected] + 18. rw[h5] at h4 [✓ accepted] + 19. field_simp at h4 [✓ accepted] + 20. have h7:((a ^ 2 + b ^ 2 + c ^ 2)/16)^2 = 1:= by linarith [✓ accepted] + 21. let C := (a ^ 2 + b ^ 2 + c ^ 2)/16 [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 21:37] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +h4 : -(128 * 2) = (-c ^ 2 + (-b ^ 2 + -a ^ 2)) * (a ^ 2 + b ^ 2 + c ^ 2) +h7 : ((a ^ 2 + b ^ 2 + c ^ 2) / 16) ^ 2 = 1 +C : ℝ := (a ^ 2 + b ^ 2 + c ^ 2) / 16 +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 22 --- +LLM proposes tactic: have h8:C^2=1:= by dsimp[C]; exact h7 +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 22/400 | accepted tactics: 20 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + 17 | rw [h6] at h4 + 18 | rw[h1] at h4 + 19 | simp at h4 + 20 | rw[h5] at h4 + 21 | field_simp at h4 + 22 | have h7:((a ^ 2 + b ^ 2 + c ^ 2)/16)^2 = 1:= by linarith + 23 | let C := (a ^ 2 + b ^ 2 + c ^ 2)/16 + 24 | have h8:C^2=1:= by dsimp[C]; exact h7 + +Proof log (latest 5 steps): + ... (17 earlier steps omitted) + 18. rw[h5] at h4 [✓ accepted] + 19. field_simp at h4 [✓ accepted] + 20. have h7:((a ^ 2 + b ^ 2 + c ^ 2)/16)^2 = 1:= by linarith [✓ accepted] + 21. let C := (a ^ 2 + b ^ 2 + c ^ 2)/16 [✓ accepted] + 22. have h8:C^2=1:= by dsimp[C]; exact h7 [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 22:39] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +h4 : -(128 * 2) = (-c ^ 2 + (-b ^ 2 + -a ^ 2)) * (a ^ 2 + b ^ 2 + c ^ 2) +h7 : ((a ^ 2 + b ^ 2 + c ^ 2) / 16) ^ 2 = 1 +C : ℝ := (a ^ 2 + b ^ 2 + c ^ 2) / 16 +h8 : C ^ 2 = 1 +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 23 --- +LLM proposes tactic: simp at h8 +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 23/400 | accepted tactics: 21 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + 17 | rw [h6] at h4 + 18 | rw[h1] at h4 + 19 | simp at h4 + 20 | rw[h5] at h4 + 21 | field_simp at h4 + 22 | have h7:((a ^ 2 + b ^ 2 + c ^ 2)/16)^2 = 1:= by linarith + 23 | let C := (a ^ 2 + b ^ 2 + c ^ 2)/16 + 24 | have h8:C^2=1:= by dsimp[C]; exact h7 + 25 | simp at h8 + +Proof log (latest 5 steps): + ... (18 earlier steps omitted) + 19. field_simp at h4 [✓ accepted] + 20. have h7:((a ^ 2 + b ^ 2 + c ^ 2)/16)^2 = 1:= by linarith [✓ accepted] + 21. let C := (a ^ 2 + b ^ 2 + c ^ 2)/16 [✓ accepted] + 22. have h8:C^2=1:= by dsimp[C]; exact h7 [✓ accepted] + 23. simp at h8 [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 23:12] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +h4 : -(128 * 2) = (-c ^ 2 + (-b ^ 2 + -a ^ 2)) * (a ^ 2 + b ^ 2 + c ^ 2) +h7 : ((a ^ 2 + b ^ 2 + c ^ 2) / 16) ^ 2 = 1 +C : ℝ := (a ^ 2 + b ^ 2 + c ^ 2) / 16 +h8 : C = 1 ∨ C = -1 +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 24 --- +LLM proposes tactic: have h9: C > 0 := by dsimp[C];positivity +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 24/400 | accepted tactics: 22 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + 17 | rw [h6] at h4 + 18 | rw[h1] at h4 + 19 | simp at h4 + 20 | rw[h5] at h4 + 21 | field_simp at h4 + 22 | have h7:((a ^ 2 + b ^ 2 + c ^ 2)/16)^2 = 1:= by linarith + 23 | let C := (a ^ 2 + b ^ 2 + c ^ 2)/16 + 24 | have h8:C^2=1:= by dsimp[C]; exact h7 + 25 | simp at h8 + 26 | have h9: C > 0 := by dsimp[C];positivity + +Proof log (latest 5 steps): + ... (19 earlier steps omitted) + 20. have h7:((a ^ 2 + b ^ 2 + c ^ 2)/16)^2 = 1:= by linarith [✓ accepted] + 21. let C := (a ^ 2 + b ^ 2 + c ^ 2)/16 [✓ accepted] + 22. have h8:C^2=1:= by dsimp[C]; exact h7 [✓ accepted] + 23. simp at h8 [✓ accepted] + 24. have h9: C > 0 := by dsimp[C];positivity [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 24:42] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +h4 : -(128 * 2) = (-c ^ 2 + (-b ^ 2 + -a ^ 2)) * (a ^ 2 + b ^ 2 + c ^ 2) +h7 : ((a ^ 2 + b ^ 2 + c ^ 2) / 16) ^ 2 = 1 +C : ℝ := (a ^ 2 + b ^ 2 + c ^ 2) / 16 +h8 : C = 1 ∨ C = -1 +h9 : C > 0 +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 25 --- +LLM proposes tactic: have h10: C = 1 := by cases h8;assumption;linarith +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 25/400 | accepted tactics: 23 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + 17 | rw [h6] at h4 + 18 | rw[h1] at h4 + 19 | simp at h4 + 20 | rw[h5] at h4 + 21 | field_simp at h4 + 22 | have h7:((a ^ 2 + b ^ 2 + c ^ 2)/16)^2 = 1:= by linarith + 23 | let C := (a ^ 2 + b ^ 2 + c ^ 2)/16 + 24 | have h8:C^2=1:= by dsimp[C]; exact h7 + 25 | simp at h8 + 26 | have h9: C > 0 := by dsimp[C];positivity + 27 | have h10: C = 1 := by cases h8;assumption;linarith + +Proof log (latest 5 steps): + ... (20 earlier steps omitted) + 21. let C := (a ^ 2 + b ^ 2 + c ^ 2)/16 [✓ accepted] + 22. have h8:C^2=1:= by dsimp[C]; exact h7 [✓ accepted] + 23. simp at h8 [✓ accepted] + 24. have h9: C > 0 := by dsimp[C];positivity [✓ accepted] + 25. have h10: C = 1 := by cases h8;assumption;linarith [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 25:52] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +h4 : -(128 * 2) = (-c ^ 2 + (-b ^ 2 + -a ^ 2)) * (a ^ 2 + b ^ 2 + c ^ 2) +h7 : ((a ^ 2 + b ^ 2 + c ^ 2) / 16) ^ 2 = 1 +C : ℝ := (a ^ 2 + b ^ 2 + c ^ 2) / 16 +h8 : C = 1 ∨ C = -1 +h9 : C > 0 +h10 : C = 1 +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 26 --- +LLM proposes tactic: dsimp[C] at h10 +System info (Reward: 0.90 | Done: False | Accepted: True | Success: False) +Observation of LLM Agent: +Steps taken: 26/400 | accepted tactics: 24 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + 17 | rw [h6] at h4 + 18 | rw[h1] at h4 + 19 | simp at h4 + 20 | rw[h5] at h4 + 21 | field_simp at h4 + 22 | have h7:((a ^ 2 + b ^ 2 + c ^ 2)/16)^2 = 1:= by linarith + 23 | let C := (a ^ 2 + b ^ 2 + c ^ 2)/16 + 24 | have h8:C^2=1:= by dsimp[C]; exact h7 + 25 | simp at h8 + 26 | have h9: C > 0 := by dsimp[C];positivity + 27 | have h10: C = 1 := by cases h8;assumption;linarith + 28 | dsimp[C] at h10 + +Proof log (latest 5 steps): + ... (21 earlier steps omitted) + 22. have h8:C^2=1:= by dsimp[C]; exact h7 [✓ accepted] + 23. simp at h8 [✓ accepted] + 24. have h9: C > 0 := by dsimp[C];positivity [✓ accepted] + 25. have h10: C = 1 := by cases h8;assumption;linarith [✓ accepted] + 26. dsimp[C] at h10 [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +01. [UNSOLVED GOALS 2:64 → 26:17] unsolved goals +a b c : ℝ +ha : a ≠ 0 +hb : b ≠ 0 +hc : c ≠ 0 +h1 : a + b + c = 0 +h2 : a ^ 4 + b ^ 4 + c ^ 4 = 128 +h3 : 0 = a ^ 2 + b ^ 2 + c ^ 2 + 2 * (a * b + b * c + c * a) +h5 : a * b + b * c + c * a = -(a ^ 2 + b ^ 2 + c ^ 2) / 2 +h6 : + a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = + (a * b + b * c + c * a) * (a ^ 2 + b ^ 2 + c ^ 2) - (a + b + c) * a * b * c +h4 : -(128 * 2) = (-c ^ 2 + (-b ^ 2 + -a ^ 2)) * (a ^ 2 + b ^ 2 + c ^ 2) +h7 : ((a ^ 2 + b ^ 2 + c ^ 2) / 16) ^ 2 = 1 +C : ℝ := (a ^ 2 + b ^ 2 + c ^ 2) / 16 +h8 : C = 1 ∨ C = -1 +h9 : C > 0 +h10 : (a ^ 2 + b ^ 2 + c ^ 2) / 16 = 1 +⊢ -c ^ 2 + (-b ^ 2 - a ^ 2) = -16 + +--- Step 27 --- +LLM proposes tactic: linarith +System info (Reward: 10.90 | Done: True | Accepted: True | Success: True) +Observation of LLM Agent: +Steps taken: 27/400 | accepted tactics: 25 + +Informal statement: + Given three non-zero real numbers a, b, c. If their sum is 0, and the sum of their fourth powers is 128, + prove that the sum of their pairwise products must be -8. + +Proof transcript: + 1 | import Mathlib + 2 | + 3 | theorem algebra_4036 (a b c:ℝ)(ha: a ≠ 0)(hb: b ≠ 0)(hc: c ≠ 0) + 4 | (h1: a + b + c = 0)(h2: a^4 + b^4 + c^4 = 128):a*b+b*c+c*a=-8:= by + 5 | have h3:(a + b + c)^2=a^2+b^2+c^2+2*(a*b+b*c+c*a):= by ring + 6 | rw[h1] at h3 + 7 | simp at h3 + 8 | -- simplify the equation $(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)$. + 9 | have h4:(a+b+c)*(a^3+b^3+c^3)-(a^4 + b^4 + c^4)=(a*(b^3+c^3)+b*(a^3+c^3)+c*(a^3+b^3)):= by ring_nf + 10 | rw[h1,h2] at h4 + 11 | simp at h4 + 12 | have h5:(a * b + b * c + c * a) = -(a ^ 2 + b ^ 2 + c ^ 2)/2:= by linarith + 13 | rw[h5] + 14 | field_simp + 15 | ring_nf + 16 | have h6:a * (b ^ 3 + c ^ 3) + b * (a ^ 3 + c ^ 3) + c * (a ^ 3 + b ^ 3) = (a*b+b*c+c*a)*(a ^ 2 + b ^ 2 + c ^ 2)-(a + b + c)*a*b*c:= by ring_nf + 17 | rw [h6] at h4 + 18 | rw[h1] at h4 + 19 | simp at h4 + 20 | rw[h5] at h4 + 21 | field_simp at h4 + 22 | have h7:((a ^ 2 + b ^ 2 + c ^ 2)/16)^2 = 1:= by linarith + 23 | let C := (a ^ 2 + b ^ 2 + c ^ 2)/16 + 24 | have h8:C^2=1:= by dsimp[C]; exact h7 + 25 | simp at h8 + 26 | have h9: C > 0 := by dsimp[C];positivity + 27 | have h10: C = 1 := by cases h8;assumption;linarith + 28 | dsimp[C] at h10 + 29 | linarith + +Proof log (latest 5 steps): + ... (22 earlier steps omitted) + 23. simp at h8 [✓ accepted] + 24. have h9: C > 0 := by dsimp[C];positivity [✓ accepted] + 25. have h10: C = 1 := by cases h8;assumption;linarith [✓ accepted] + 26. dsimp[C] at h10 [✓ accepted] + 27. linarith [✓ accepted] + +Last Lean feedback: + accepted: True + messages: +(no Lean messages) +""" \ No newline at end of file diff --git a/ragen/env/lean/__pycache__/__init__.cpython-310.pyc b/ragen/env/lean/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae0a8999ee7107d18fe421aecae27777a3ae0598 Binary files /dev/null and b/ragen/env/lean/__pycache__/__init__.cpython-310.pyc differ diff --git a/ragen/env/lean/__pycache__/config.cpython-310.pyc b/ragen/env/lean/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1ba54a5d6b42b24aa89c566f03b7fd51c0627f1 Binary files /dev/null and b/ragen/env/lean/__pycache__/config.cpython-310.pyc differ diff --git a/ragen/env/lean/__pycache__/env.cpython-310.pyc b/ragen/env/lean/__pycache__/env.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd5ec0524b10ccde84e89ad9786a889a373420c8 Binary files /dev/null and b/ragen/env/lean/__pycache__/env.cpython-310.pyc differ diff --git a/ragen/env/lean/config.py b/ragen/env/lean/config.py new file mode 100644 index 0000000000000000000000000000000000000000..c79c41e49ae6ae4c9785a03d591e69ada83ce8d5 --- /dev/null +++ b/ragen/env/lean/config.py @@ -0,0 +1,75 @@ +from dataclasses import dataclass, field +from typing import Optional + +@dataclass +class LeanEnvConfig: + """Configuration options for the Lean theorem-proving environment.""" + + dataset_name_or_path: str = field( + default="CoderBak/minif2f", + metadata={"description": "Hugging Face dataset identifier or local path."}, + ) + dataset_split: str = field( + default="train", + metadata={"description": "Split to use from the Hugging Face dataset."}, + ) + server_url: str = field( + default="http://127.0.0.1:8000", + metadata={"description": "Base URL for the Kimina Lean server."}, + ) + api_key: Optional[str] = field( + default=None, + metadata={"description": "Optional API key for authenticated servers."}, + ) + request_timeout: float = field( + default=30.0, + metadata={"description": "Timeout (seconds) when contacting the server."}, + ) + http_timeout: float = field( + default=60.0, + metadata={ + "description": "HTTP client timeout (seconds) for establishing connections." + }, + ) + max_retries: int = field( + default=3, + metadata={"description": "Number of HTTP retry attempts when querying server."}, + ) + max_steps: int = field( + default=100, + metadata={"description": "Maximum number of tactics per episode."}, + ) + step_penalty: float = field( + default=-0.1, + metadata={"description": "Base reward applied each step."}, + ) + valid_step_reward: float = field( + default=1.0, + metadata={"description": "Additional reward for an accepted tactic."}, + ) + invalid_step_reward: float = field( + default=-1.0, + metadata={"description": "Additional reward when a tactic is rejected."}, + ) + success_reward: float = field( + default=10.0, + metadata={"description": "Reward granted when the proof is complete."}, + ) + timeout_penalty: float = field( + default=-1.0, + metadata={"description": "Penalty applied when the server times out."}, + ) + max_steps_penalty: float = field( + default=-2.0, + metadata={ + "description": "Penalty applied if max_steps is reached without success." + }, + ) + default_imports: str = field( + default="import Mathlib\nimport Aesop\nset_option maxHeartbeats 0\nopen BigOperators Real Nat Topology Rat", + metadata={"description": "Imports prepended when dataset sample omits them."}, + ) + message_truncate_limit: int = field( + default=0, + metadata={"description": "Maximum characters for message (0 = no truncation)."}, + ) diff --git a/ragen/env/lean/env.py b/ragen/env/lean/env.py new file mode 100644 index 0000000000000000000000000000000000000000..d70adb92d72f7964a99c118ab1b2c9fb644e1ffd --- /dev/null +++ b/ragen/env/lean/env.py @@ -0,0 +1,653 @@ +from __future__ import annotations + +import logging +import random +import textwrap +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Sequence, Tuple +from uuid import uuid4 + +from kimina_client import Infotree, Snippet +from kimina_client.models import CheckResponse, CommandResponse, Error, ReplResponse +from kimina_client.sync_client import KiminaClient + +from ragen.env.base import BaseLanguageBasedEnv + +from .config import LeanEnvConfig + +logger = logging.getLogger(__name__) + +_DATASET_CACHE: Dict[Tuple[str, str], List[Dict[str, Any]]] = {} + + +@dataclass +class _LeanStepResult: + status: str + accepted: bool + success: bool + message_objects: List[Dict[str, Any]] + diagnostics: Dict[str, Any] + lean_time: float + response: CommandResponse | Error | None + raw_response: Dict[str, Any] + + +class LeanEnv(BaseLanguageBasedEnv): + """Lean RAGEN environment backed by the Kimina Lean server.""" + + def __init__( + self, + config: Optional[LeanEnvConfig] = None, + *, + client: Optional[KiminaClient] = None, + ): + super().__init__() + self.config = config if config is not None else LeanEnvConfig() + self._client = client + self._server_url = self.config.server_url.rstrip("/") + + self._rng = random.Random() + self._dataset = self._load_dataset() + + self.current_theorem: Dict[str, Any] | None = None + self.tactic_history: List[str] = [] + self.proof_log: List[Dict[str, Any]] = [] + self.last_feedback: str = "" + self.last_result: Optional[_LeanStepResult] = None + self._last_structured_feedback: Dict[str, Any] = {} + self.num_env_steps: int = 0 + self._server_unreachable_warned: bool = False + self._latest_proof_text: str = "" + + def reset(self, seed: Optional[int] = None, **kwargs) -> str: + if seed is not None: + self._rng.seed(seed) + + theorem_idx = kwargs.get("theorem_idx") + if theorem_idx is not None: + idx = theorem_idx % len(self._dataset) + self.current_theorem = self._dataset[idx] + else: + self.current_theorem = self._rng.choice(self._dataset) + + self.tactic_history = [] + self.proof_log = [] + self.last_feedback = "" + self.last_result = None + self._last_structured_feedback = {} + self.num_env_steps = 0 + self._latest_proof_text = self._construct_proof([]) + + return self.render() + + def step(self, action: str): + if not action: + return self._handle_empty_action() + + candidate_steps = self.tactic_history + [action] + result = self._run_lean_query(candidate_steps) + + self.last_result = result + formatted_messages = self._format_message_objects_verbose(result.message_objects) + self._last_structured_feedback = { + "messages": formatted_messages, + "message_objects": result.message_objects, + "accepted": result.accepted, + } + self.last_feedback = formatted_messages[0] if formatted_messages else "" + + if result.accepted: + self.tactic_history.append(action) + self._latest_proof_text = self._construct_proof(self.tactic_history) + + self.num_env_steps += 1 + self.proof_log.append( + { + "action": action, + "accepted": result.accepted, + "messages": formatted_messages, + "message_objects": result.message_objects, + } + ) + + reward = self.config.step_penalty + if result.accepted: + reward += self.config.valid_step_reward + else: + reward += self.config.invalid_step_reward + if result.success: + reward += self.config.success_reward + if result.status == "timeout": + reward += self.config.timeout_penalty + + done = False + if result.success: + done = True + elif self.num_env_steps >= self.config.max_steps: + done = True + reward += self.config.max_steps_penalty + + info: Dict[str, Any] = { + "action_is_valid": result.accepted, + "action_is_effective": result.accepted, + "accepted": result.accepted, + "success": result.success, + "messages": formatted_messages, + "message_objects": result.message_objects, + } + if result.diagnostics: + info["diagnostics"] = result.diagnostics + + observation = self.render() + return observation, reward, done, info + + def render(self, mode: Optional[str] = None) -> str: + if self.current_theorem is None: + return "Lean environment not initialised." + + informal = self.current_theorem.get("natural_language_statement", "").strip() + + accepted_steps = len(self.tactic_history) + lines: List[str] = [] + lines.append( + f"Steps taken: {self.num_env_steps}/{self.config.max_steps} | accepted tactics: {accepted_steps}" + ) + + lines.append("") + lines.append("Informal statement:") + lines.extend(self._format_block(informal)) + + lines.append("") + lines.append("Proof transcript:") + proof_lines = self._format_proof_snippet(self._latest_proof_text) + for line in proof_lines: + lines.append(f" {line}") + + if self.proof_log: + lines.append("") + lines.append("Proof log (latest 5 steps):") + lines.extend(self._format_log_entries(limit=5)) + + if self.last_result is not None: + result = self.last_result + lines.append("") + lines.append("Last Lean feedback:") + lines.append(f" accepted: {result.accepted}") + lines.append(" messages:") + message_lines = self._format_message_objects_verbose( + result.message_objects, indent="" + ) + for entry in message_lines: + lines.append(entry) + elif self.last_feedback: + lines.append(f"\nFeedback: {self.last_feedback}") + + return "\n".join(lines) + + def close(self): + """Nothing to close explicitly.""" + + def _handle_empty_action(self): + reward = self.config.step_penalty + self.config.invalid_step_reward + message = "Empty tactic is not allowed." + message_obj = { + "severity": "error", + "data": message, + } + formatted_messages = self._format_message_objects_verbose([message_obj]) + self.last_feedback = formatted_messages[0] if formatted_messages else message + self.last_result = _LeanStepResult( + status="invalid", + accepted=False, + success=False, + message_objects=[message_obj], + diagnostics={}, + lean_time=0.0, + response=None, + raw_response={}, + ) + self._last_structured_feedback = { + "messages": formatted_messages, + "message_objects": [message_obj], + "accepted": False, + } + self.num_env_steps += 1 + self.proof_log.append( + { + "action": "", + "accepted": False, + "messages": formatted_messages, + "message_objects": [message_obj], + } + ) + self._latest_proof_text = self._construct_proof(self.tactic_history) + + done = False + if self.num_env_steps >= self.config.max_steps: + done = True + reward += self.config.max_steps_penalty + + return ( + self.render(), + reward, + done, + { + "action_is_valid": False, + "action_is_effective": False, + "success": False, + "accepted": False, + "messages": formatted_messages, + "message_objects": [message_obj], + }, + ) + + def _run_lean_query( + self, + candidate_steps: Sequence[str] + ) -> _LeanStepResult: + proof_text = self._construct_proof(candidate_steps) + + def _make_result( + *, + status: str, + accepted: bool, + success: bool, + message_objects: Optional[Sequence[Dict[str, Any]]] = None, + diagnostics: Optional[Dict[str, Any]] = None, + lean_time: float = 0.0, + response: CommandResponse | Error | None = None, + raw_response: Optional[Dict[str, Any]] = None, + ) -> _LeanStepResult: + return _LeanStepResult( + status=status, + accepted=accepted, + success=success, + message_objects=list(message_objects or []), + diagnostics=diagnostics or {}, + lean_time=lean_time, + response=response, + raw_response=raw_response or {}, + ) + + try: + response = self._call_lean_server(proof_text) + self._server_unreachable_warned = False + except Exception as exc: + if not self._server_unreachable_warned: + logger.error( + "Lean server request failed: %s. Make sure the Kimina Lean server " + "is running at %s and that 127.0.0.1 is excluded from your proxy " + "settings (e.g., NO_PROXY).", + exc, + self.config.server_url, + ) + self._server_unreachable_warned = True + status = "timeout" if "timed out" in str(exc).lower() else "server_error" + return _make_result( + status=status, + accepted=False, + success=False, + message_objects=[{"severity": "error", "data": str(exc)}], + ) + + repl_response = self._extract_repl_response(response) + if repl_response is None: + return _make_result( + status="server_error", + accepted=False, + success=False, + message_objects=[ + {"severity": "error", "data": "Empty response from Lean server."} + ], + ) + + if repl_response.error is not None: + error_text = repl_response.error + status = "timeout" if "timed out" in error_text.lower() else "error" + return _make_result( + status=status, + accepted=False, + success=False, + message_objects=[{"severity": "error", "data": error_text}], + diagnostics=repl_response.diagnostics or {}, + lean_time=repl_response.time, + ) + + if repl_response.response is None: + return _make_result( + status="server_error", + accepted=False, + success=False, + message_objects=[ + { + "severity": "error", + "data": "Lean server returned no response payload.", + } + ], + diagnostics=repl_response.diagnostics or {}, + lean_time=repl_response.time, + ) + + payload = repl_response.response + if "message" in payload: + message = payload.get("message", "Lean REPL error.") + synthetic_message = { + "severity": "error", + "data": message, + "pos": payload.get("pos", {}), + } + return _make_result( + status="error", + accepted=False, + success=False, + diagnostics=repl_response.diagnostics or {}, + lean_time=repl_response.time, + response=payload, + message_objects=[synthetic_message], + ) + + command_response = payload + message_objects = list(command_response.get("messages") or []) + blocking_error = False + for msg in message_objects: + severity = str(msg.get("severity", "")).lower() + if severity != "error": + continue + data = str(msg.get("data") or msg.get("message") or "") + if "unsolved goals" in data.lower(): + continue + blocking_error = True + break + + sorries = [] + raw_sorries = command_response.get("sorries") + if isinstance(raw_sorries, list): + sorries = raw_sorries + has_sorry = bool(sorries) + + accepted = not blocking_error and not has_sorry + any_error = any( + str(msg.get("severity", "")).lower() == "error" for msg in message_objects + ) + success = (not any_error) and not has_sorry + status = "valid" if accepted else "invalid" + + return _make_result( + status=status, + accepted=accepted, + success=success, + message_objects=message_objects, + diagnostics=repl_response.diagnostics or {}, + lean_time=repl_response.time, + response=command_response, + raw_response=command_response, + ) + + def _call_lean_server(self, proof_text: str) -> CheckResponse: + snippet_id = f"ragen-proof-{uuid4().hex}" + snippet = Snippet(id=snippet_id, code=proof_text) + infotree = Infotree.tactics + client = self._ensure_client() + return client.api_check( + snippets=[snippet], + timeout=int(self.config.request_timeout), + debug=True, + reuse=True, + infotree=infotree, + safe=False, + ) + + def _ensure_client(self) -> KiminaClient: + if self._client is None: + self._client = KiminaClient( + api_url=self.config.server_url, + api_key=self.config.api_key, + http_timeout=self.config.http_timeout, + n_retries=self.config.max_retries, + ) + return self._client + + @staticmethod + def _extract_repl_response(response: CheckResponse) -> Optional[ReplResponse]: + if not response.results: + return None + return response.results[0] + + def _construct_proof(self, steps: Sequence[str]) -> str: + record = self.current_theorem or {} + imports = record.get("imports") or self.config.default_imports + preamble = record.get("preamble") or "" + statement = record.get("formal_statement", "") + + script_lines: List[str] = [] + + if imports: + script_lines.extend(imports.strip().splitlines()) + script_lines.append("") + + if preamble: + script_lines.extend(preamble.strip().splitlines()) + script_lines.append("") + + if statement: + script_lines.extend(statement.strip().splitlines()) + + if steps: + step_lines = [" " + step for step in steps if step.strip()] + script_lines.extend(step_lines) + + script = "\n".join(script_lines) + if not script.endswith("\n"): + script += "\n" + return script + + @staticmethod + def _truncate_text(text: str, limit: int = 300) -> str: + cleaned = text.strip() + if limit == 0 or len(cleaned) <= limit: + return cleaned + return cleaned[: limit - 3] + "..." + + @staticmethod + def _format_block(text: str, indent_spaces: str = " ", width: int = 88) -> List[str]: + if not text: + return [f"{indent_spaces}(not provided)"] + wrapped = textwrap.wrap(text, width=width) + return [f"{indent_spaces}{line}" if line else indent_spaces.rstrip() for line in wrapped] + + def _format_message_objects_verbose( + self, message_objects: Sequence[Dict[str, Any]], indent: str = " " + ) -> List[str]: + if not message_objects: + return [f"{indent}(no Lean messages)"] + + limit = max(0, int(self.config.message_truncate_limit or 0)) + lines: List[str] = [] + for idx, message in enumerate(message_objects, start=1): + severity = str(message.get("severity", "info")).upper() + pos = message.get("pos") or {} + end_pos = message.get("endPos") or {} + location_parts = [] + if pos: + line_no = pos.get("line") + col_no = pos.get("column") + if line_no is not None and col_no is not None: + location_parts.append(f"{line_no}:{col_no}") + elif line_no is not None: + location_parts.append(f"{line_no}") + if end_pos: + line_no = end_pos.get("line") + col_no = end_pos.get("column") + if line_no is not None and col_no is not None: + location_parts.append(f"{line_no}:{col_no}") + elif line_no is not None: + location_parts.append(f"{line_no}") + location = " → ".join(location_parts) if location_parts else "" + data = message.get("data") or message.get("message") or "" + if limit > 0: + data = self._truncate_text(str(data), limit=limit) + + # Remap severity for non-blocking "unsolved goals" errors + if severity == "ERROR" and "unsolved goals" in str(data).lower(): + severity = "UNSOLVED GOALS" + + prefix = f"{indent}{idx:02d}. [{severity}" + if location: + prefix += f" {location}" + prefix += "]" + lines.append(f"{prefix} {data}".rstrip()) + return lines + + def _format_proof_snippet(self, proof_text: str, max_lines: int = 40) -> List[str]: + lines = proof_text.rstrip("\n").splitlines() + if not lines: + return ["(empty proof)"] + + start_idx = max(0, len(lines) - max_lines) + subset = lines[start_idx:] + number_width = max(3, len(str(start_idx + len(subset)))) + formatted = [ + f"{start_idx + idx + 1:>{number_width}} | {line}" + for idx, line in enumerate(subset) + ] + if start_idx > 0: + formatted.insert(0, f"... ({start_idx} earlier lines omitted)") + return formatted + + def _format_log_entries(self, limit: int = 5) -> List[str]: + if not self.proof_log: + return [" (no steps recorded)"] + + start = max(len(self.proof_log) - limit, 0) + entries = self.proof_log[start:] + lines: List[str] = [] + if start > 0: + lines.append(f" ... ({start} earlier steps omitted)") + + for idx, entry in enumerate(entries, start=start + 1): + marker = "✓" if entry.get("accepted") else "✗" + status = "accepted" if entry.get("accepted") else "rejected" + action = entry.get("action", "") + lines.append(f" {idx:02d}. {action} [{marker} {status}]") + + # The message for these steps are removed to reduce the input length. + # for msg in entry.get("messages") or []: + # lines.append(f" {msg}") + return lines + + def _load_dataset(self) -> List[Dict[str, Any]]: + dataset_name = self.config.dataset_name_or_path or "" + dataset_split = self.config.dataset_split or "train" + cache_key = (dataset_name, dataset_split) + cached = _DATASET_CACHE.get(cache_key) + if cached is not None: + return cached + + if not dataset_name: + message = "LeanEnv requires a dataset_name to load training samples." + logger.error(message) + raise AssertionError(message) + + from datasets import load_dataset + + try: + hf_dataset = load_dataset( + dataset_name, + split=dataset_split, + streaming=False, + ) + except Exception as exc: + message = f"Failed to load dataset {dataset_name} ({dataset_split}): {exc}" + logger.error(message) + raise AssertionError(message) + + records: List[Dict[str, Any]] = [] + for idx, example in enumerate(hf_dataset): + parsed = self._parse_hf_example(example, idx) + if parsed: + records.append(parsed) + + if not records: + available = list(getattr(hf_dataset, "column_names", [])) + message = ( + f"Dataset {dataset_name} yielded no usable samples. " + f"Available columns: {available}" + ) + logger.error(message) + raise AssertionError(message) + + _DATASET_CACHE[cache_key] = records + return records + + def _parse_hf_example( + self, example: Dict[str, Any], idx: int + ) -> Optional[Dict[str, Any]]: + if example is None: + return None + + formal_statement = example.get("formal_statement") + natural_statement = example.get("natural_language_statement") + if not isinstance(formal_statement, str) or not formal_statement.strip(): + logger.debug( + "Skipping dataset example %s: missing formal_statement", + example.get("name", f"hf_{idx}"), + ) + return None + if not isinstance(natural_statement, str): + natural_statement = "" + + name = str(example.get("name") or example.get("id") or f"hf_{idx}") + + imports, preamble, statement_body = self._split_formal_sections(formal_statement) + + return { + "name": str(name), + "imports": imports, + "preamble": preamble, + "formal_statement": statement_body, + "natural_language_statement": natural_statement or "", + } + + @staticmethod + def _split_formal_sections(text: str) -> tuple[str, str, str]: + """Return (imports, preamble, body) sections from a Lean snippet.""" + + imports: List[str] = [] + preamble: List[str] = [] + body: List[str] = [] + + body_started = False + for line in text.splitlines(): + stripped = line.strip() + if not stripped: + if body_started: + body.append(line) + else: + preamble.append(line) + continue + + if stripped.startswith("import") and not body_started: + imports.append(line) + continue + + if not body_started and any( + stripped.startswith(keyword) + for keyword in ("theorem", "lemma", "def", "example", "instance") + ): + body_started = True + body.append(line) + continue + + if body_started: + body.append(line) + else: + preamble.append(line) + + imports_text = "\n".join(imports).strip() + preamble_text = "\n".join(preamble).strip() + body_text = "\n".join(body).strip() + return imports_text, preamble_text, body_text + + def get_available_actions(self) -> List[str]: + """Free-form text environment — no fixed discrete actions.""" + return [] diff --git a/ragen/env/metamathqa/__init__.py b/ragen/env/metamathqa/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7479f3c2049038b557b96c60f5a3e0608104054d --- /dev/null +++ b/ragen/env/metamathqa/__init__.py @@ -0,0 +1,7 @@ +""" +Adapted from the nicely written code from gym_sokoban +""" +from .env import MetaMathQAEnv +from .config import MetaMathQAEnvConfig + +__all__ = ["MetaMathQAEnv", "MetaMathQAEnvConfig"] diff --git a/ragen/env/metamathqa/__pycache__/__init__.cpython-310.pyc b/ragen/env/metamathqa/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eeceb69710cc86ec82edf0ccfcf6e78376ab7a6d Binary files /dev/null and b/ragen/env/metamathqa/__pycache__/__init__.cpython-310.pyc differ diff --git a/ragen/env/metamathqa/config.py b/ragen/env/metamathqa/config.py new file mode 100644 index 0000000000000000000000000000000000000000..fae6c7ae7e465c8a46f580215eeb7aaeb30471b8 --- /dev/null +++ b/ragen/env/metamathqa/config.py @@ -0,0 +1,10 @@ +from typing import Optional, List, Dict +from dataclasses import dataclass, field + +@dataclass +class MetaMathQAEnvConfig: + """Configuration for FrozenLake environment""" + # Map config + dataset_path: str = field(default="meta-math/MetaMathQA") + cache_dir:str = field(default="./data") + split: str = field(default="train") diff --git a/ragen/env/metamathqa/env.py b/ragen/env/metamathqa/env.py new file mode 100644 index 0000000000000000000000000000000000000000..5d4384be2caaabc1a5cb6470456f369494c32161 --- /dev/null +++ b/ragen/env/metamathqa/env.py @@ -0,0 +1,112 @@ +import gym +from gym import spaces +import numpy as np +from datasets import load_dataset +import re +import random +from ragen.env.base import BaseLanguageBasedEnv +from ragen.utils import all_seed +from .config import MetaMathQAEnvConfig +class MetaMathQAEnv(BaseLanguageBasedEnv): + def __init__(self, config: MetaMathQAEnvConfig): + super(MetaMathQAEnv, self).__init__() + + self.config = config + self.dataset = load_dataset(path=self.config.dataset_path, cache_dir=self.config.cache_dir) + self.current_question_idx = None + self.current_question = None + self.correct_answer = None + self.step_num = None + self.render_cache = None + + + def _extract_answer(self, response): + match = re.search(r"The answer is: (.*?)$", response, re.DOTALL) + print(response) + if match: + return match.group(1).strip() + return None + + def reset(self,seed=None, mode=None): + dataset = self.dataset[self.config.split] + with all_seed(seed): + self.current_question_idx = random.randint(0, len(dataset) - 1) + question_data = dataset[self.current_question_idx] + self.current_question = question_data['query'] + self.correct_answer = self._extract_answer(question_data['response']) + self.step_num = 0 + self.render_cache = self.current_question + return self.render_cache + + def step(self, action): + is_correct, is_valid = self._check_answer(action) + reward = 1.0 / (2 ** self.step_num) if is_correct else 0.0 + if is_correct: + observation = "Correct!" + done = True + else: + observation = "Incorrect. Please think again." + done = False + self.step_num += 1 + info = {"action_is_valid": is_valid, "success": is_correct} + self.render_cache = observation + return self.render_cache, reward, done, info + + def _check_answer(self, user_answer): + """Check if the user's answer matches the correct answer.""" + user_answer = user_answer.strip() + normalized_answer = re.sub(r'\s+', '', user_answer.lower()) + if self.correct_answer: + normalized_label = re.sub(r'\s+', '', self.correct_answer.lower()) + is_correct = normalized_answer == normalized_label + else: + is_correct = False + is_valid = normalized_answer != "" + return is_correct, is_valid + + def render(self): + return self.render_cache + + +if __name__ == "__main__": + # Create the environment configuration + config = MetaMathQAEnvConfig( + dataset_path="meta-math/MetaMathQA", + cache_dir="./data", + split="train" + ) + + # Initialize the environment + env = MetaMathQAEnv(config) + + # Reset the environment to get the first question + print("Question:") + question = env.reset(seed=42) + print(question) + print("\nCorrect answer (for testing purposes):") + print(env.correct_answer) + + # Interactive loop for testing + while True: + user_answer = input("\nEnter your answer (or 'q' to quit): ") + if user_answer.lower() == 'q': + break + + # Take a step in the environment with the user's answer + #breakpoint() + obs, reward, done, info = env.step(user_answer) + + + # Print the results + print("\nFeedback:", obs) + print("Reward:", reward) + print("Done:", done) + print("Info:", info) + + # If the episode is done, reset the environment for a new question + if done: + print("\n--- New Question ---") + question = env.reset() + print(question) + print("\nCorrect answer (for testing purposes):") + print(env.correct_answer) \ No newline at end of file diff --git a/ragen/eval.py b/ragen/eval.py new file mode 100644 index 0000000000000000000000000000000000000000..2da65055d4900e16823c79ef42318543066936f1 --- /dev/null +++ b/ragen/eval.py @@ -0,0 +1,38 @@ + +from ragen.llm_agent.ctx_manager import ContextManager +from ragen.llm_agent.es_manager import EnvStateManager +from vllm import LLM, SamplingParams +from verl.single_controller.ray.base import RayWorkerGroup +from transformers import AutoTokenizer, AutoModelForCausalLM +from verl import DataProto +import hydra +import os +from typing import List, Dict +from verl.protocol import pad_dataproto_to_divisor, unpad_dataproto +from ragen.llm_agent.base_llm import ConcurrentLLM +from ragen.llm_agent.agent_proxy import ApiCallingWrapperWg, VllmWrapperWg, LLMAgentProxy + +@hydra.main(version_base=None, config_path="../config", config_name="base") +def main(config): + # detect config name from python -m ragen.llm_agent.agent_proxy --config_name frozen_lake + os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn" + os.environ["CUDA_VISIBLE_DEVICES"] = str(config.system.CUDA_VISIBLE_DEVICES) + tokenizer = AutoTokenizer.from_pretrained(config.actor_rollout_ref.model.path) + actor_wg = VllmWrapperWg(config, tokenizer) + proxy = LLMAgentProxy(config, actor_wg, tokenizer) + import time + start_time = time.time() + rollouts = proxy.rollout(DataProto(batch=None, non_tensor_batch=None, meta_info={'eos_token_id': 151645, 'pad_token_id': 151643, 'recompute_log_prob': False, 'do_sample':config.actor_rollout_ref.rollout.do_sample, 'validate': True}), val=True) + end_time = time.time() + print(f'rollout time: {end_time - start_time} seconds') + # print rollout rewards from the rm_scores + rm_scores = rollouts.batch["rm_scores"] + metrics = rollouts.meta_info["metrics"] + avg_reward = rm_scores.sum(-1).mean().item() + print(f'rollout rewards: {avg_reward}') + print(f'metrics:') + for k, v in metrics.items(): + print(f'{k}: {v}') + +if __name__ == "__main__": + main() diff --git a/ragen/eval_api.py b/ragen/eval_api.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e4b4217f081451b5495b4e800a6c885d90b0e4 --- /dev/null +++ b/ragen/eval_api.py @@ -0,0 +1,39 @@ + +from ragen.llm_agent.ctx_manager import ContextManager +from ragen.llm_agent.es_manager import EnvStateManager +from vllm import LLM, SamplingParams +from verl.single_controller.ray.base import RayWorkerGroup +from transformers import AutoTokenizer, AutoModelForCausalLM +from verl import DataProto +import hydra +import os +from typing import List, Dict +from verl.protocol import pad_dataproto_to_divisor, unpad_dataproto +from ragen.llm_agent.base_llm import ConcurrentLLM +from ragen.llm_agent.agent_proxy import ApiCallingWrapperWg, VllmWrapperWg, LLMAgentProxy + +@hydra.main(version_base=None, config_path="../config", config_name="evaluate_api_llm") +def main(config): + # detect config name from python -m ragen.llm_agent.agent_proxy --config_name frozen_lake + tokenizer = AutoTokenizer.from_pretrained(config.actor_rollout_ref.model.path) + actor_wg = ApiCallingWrapperWg(config, tokenizer) + proxy = LLMAgentProxy(config, actor_wg, tokenizer) + import time + start_time = time.time() + rollouts = proxy.rollout(DataProto(batch=None, non_tensor_batch=None, meta_info={'eos_token_id': 151645, 'pad_token_id': 151643, 'recompute_log_prob': False, 'do_sample': False, 'validate': True}), val=True) + print(f'[DEBUG] rollouts: {rollouts}') + end_time = time.time() + print(f'rollout time: {end_time - start_time} seconds') + # print rollout rewards from the rm_scores + rm_scores = rollouts.batch["rm_scores"] + metrics = rollouts.meta_info["metrics"] + avg_reward = rm_scores.sum(-1).mean().item() + print(f'rollout rewards: {avg_reward}') + print(f'metrics:') + for k, v in metrics.items(): + print(f'{k}: {v}') + + + +if __name__ == "__main__": + main() diff --git a/ragen/utils.py b/ragen/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..50b6d0e26440aee66ef0812b639d900a60f26a2b --- /dev/null +++ b/ragen/utils.py @@ -0,0 +1,86 @@ +import random +import numpy as np +from contextlib import contextmanager +from omegaconf import OmegaConf +import dataclasses + +@contextmanager +def all_seed(seed): + random_state = random.getstate() + np_random_state = np.random.get_state() + + try: + random.seed(seed) + np.random.seed(seed) + yield + finally: + random.setstate(random_state) + np.random.set_state(np_random_state) + +def register_resolvers(): + try: + OmegaConf.register_new_resolver("mul", lambda x, y: x * y) + OmegaConf.register_new_resolver("int_div", lambda x, y: int(float(x) / float(y))) + OmegaConf.register_new_resolver("not", lambda x: not x) + except: + pass # already registered + + + +@dataclasses.dataclass +class GenerationsLogger: + + def log(self, loggers, samples, step, _type='val'): + if 'wandb' in loggers: + self.log_generations_to_wandb(samples, step, _type) + if 'swanlab' in loggers: + self.log_generations_to_swanlab(samples, step, _type) + + def log_generations_to_wandb(self, samples, step, _type='val'): + """Log samples to wandb as a table""" + import wandb + + # Create column names for all samples + columns = ["step"] + sum([[f"input_{i+1}", f"output_{i+1}", f"score_{i+1}"] for i in range(len(samples))], []) + + if not hasattr(self, 'table'): + # Initialize the table on first call + self.table = wandb.Table(columns=columns) + + # Create a new table with same columns and existing data + # Workaround for https://github.com/wandb/wandb/issues/2981#issuecomment-1997445737 + new_table = wandb.Table(columns=columns, data=self.table.data) + + # Add new row with all data + row_data = [] + row_data.append(step) + for sample in samples: + row_data.extend(sample) + + new_table.add_data(*row_data) + + # Update reference and log + wandb.log({f"{_type}/generations": new_table}, step=step) + self.table = new_table + + def log_generations_to_swanlab(self, samples, step, _type='val'): + """Log samples to swanlab as text""" + import swanlab + + swanlab_text_list = [] + for i, sample in enumerate(samples): + row_text = f""" + input: {sample[0]} + + --- + + output: {sample[1]} + + --- + + score: {sample[2]} + """ + swanlab_text_list.append(swanlab.Text(row_text, caption=f"sample {i+1}")) + + # Log to swanlab + swanlab.log({f"{_type}/generations": swanlab_text_list}, step=step)