Harryis commited on
Commit
25ed21e
·
verified ·
1 Parent(s): c98be63

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. public/exp2.png +3 -0
  2. public/exp3.png +3 -0
  3. public/exp4.png +3 -0
  4. public/exp5.png +3 -0
  5. public/exp6.png +3 -0
  6. public/framework.png +3 -0
  7. public/loss_curve.png +3 -0
  8. public/ragen.png +3 -0
  9. public/ragen_logo.jpeg +3 -0
  10. public/rico.png +3 -0
  11. public/star-history-202556.png +3 -0
  12. public/starpo_logo.png +3 -0
  13. public/step_1.png +3 -0
  14. public/step_2.png +3 -0
  15. ragen/__init__.py +6 -0
  16. ragen/__pycache__/__init__.cpython-310.pyc +0 -0
  17. ragen/__pycache__/utils.cpython-310.pyc +0 -0
  18. ragen/demo/__init__.py +1 -0
  19. ragen/demo/run.py +71 -0
  20. ragen/env/__init__.py +59 -0
  21. ragen/env/__pycache__/__init__.cpython-310.pyc +0 -0
  22. ragen/env/__pycache__/base.cpython-310.pyc +0 -0
  23. ragen/env/alfworld_old/alfworld_config.yaml +145 -0
  24. ragen/env/alfworld_old/config.py +26 -0
  25. ragen/env/alfworld_old/env.py +158 -0
  26. ragen/env/alfworld_old/utils.py +53 -0
  27. ragen/env/bandit/__init__.py +4 -0
  28. ragen/env/bandit/__pycache__/__init__.cpython-310.pyc +0 -0
  29. ragen/env/bandit/__pycache__/config.cpython-310.pyc +0 -0
  30. ragen/env/bandit/__pycache__/env.cpython-310.pyc +0 -0
  31. ragen/env/bandit/config.py +41 -0
  32. ragen/env/bandit/env.py +144 -0
  33. ragen/env/base.py +100 -0
  34. ragen/env/blackjack/__init__.py +2 -0
  35. ragen/env/blackjack/__pycache__/__init__.cpython-310.pyc +0 -0
  36. ragen/env/blackjack/__pycache__/config.cpython-310.pyc +0 -0
  37. ragen/env/blackjack/__pycache__/env.cpython-310.pyc +0 -0
  38. ragen/env/blackjack/config.py +17 -0
  39. ragen/env/blackjack/env.py +129 -0
  40. ragen/env/countdown/__init__.py +9 -0
  41. ragen/env/countdown/__pycache__/__init__.cpython-310.pyc +0 -0
  42. ragen/env/countdown/__pycache__/config.cpython-310.pyc +0 -0
  43. ragen/env/countdown/__pycache__/env.cpython-310.pyc +0 -0
  44. ragen/env/countdown/config.py +11 -0
  45. ragen/env/countdown/env.py +93 -0
  46. ragen/env/frozen_lake.png +3 -0
  47. ragen/env/frozen_lake/__init__.py +45 -0
  48. ragen/env/frozen_lake/__pycache__/__init__.cpython-310.pyc +0 -0
  49. ragen/env/frozen_lake/__pycache__/config.cpython-310.pyc +0 -0
  50. ragen/env/frozen_lake/__pycache__/env.cpython-310.pyc +0 -0
public/exp2.png ADDED

Git LFS Details

  • SHA256: 8e2d12e64a01595f25c46c536583b305113bf6d596755ad5990348fc38e5dcf8
  • Pointer size: 131 Bytes
  • Size of remote file: 362 kB
public/exp3.png ADDED

Git LFS Details

  • SHA256: 56bf5b504b41df6457ce08c3e23360daeb65bf676cc9985df34243144193c5eb
  • Pointer size: 131 Bytes
  • Size of remote file: 371 kB
public/exp4.png ADDED

Git LFS Details

  • SHA256: 3c0af5d3cb32d4085554466fa7446c8a557e36e26f67eb8ea749f64fb82677e3
  • Pointer size: 131 Bytes
  • Size of remote file: 342 kB
public/exp5.png ADDED

Git LFS Details

  • SHA256: 9ba9cdaee4f7d4b8cb381cee936a1f508446e9ce07828490cd8dcc71346de72d
  • Pointer size: 131 Bytes
  • Size of remote file: 306 kB
public/exp6.png ADDED

Git LFS Details

  • SHA256: 846e9d7001ec02b90a33e7394f689488b1e03d00f9a22c148d9e65b7a0b46b16
  • Pointer size: 131 Bytes
  • Size of remote file: 289 kB
public/framework.png ADDED

Git LFS Details

  • SHA256: 6818364f9dfa44162c3cad96077b36b8f151605b73616ceb95b4dc7f2bed588b
  • Pointer size: 131 Bytes
  • Size of remote file: 264 kB
public/loss_curve.png ADDED

Git LFS Details

  • SHA256: ccdb559f9345f33faf13551e43d189e3a7dbb6d2260247c37571940911023928
  • Pointer size: 130 Bytes
  • Size of remote file: 99.8 kB
public/ragen.png ADDED

Git LFS Details

  • SHA256: 5e94c4580583bde14b79b8efc7fb4f4d31f732f599f3eba2f35aa05791f30ffc
  • Pointer size: 131 Bytes
  • Size of remote file: 486 kB
public/ragen_logo.jpeg ADDED

Git LFS Details

  • SHA256: fc5a86379273774a743ca113c674414877c5d4c1650fedd0ebb62dfbdf74c284
  • Pointer size: 131 Bytes
  • Size of remote file: 118 kB
public/rico.png ADDED

Git LFS Details

  • SHA256: d91fb5d0faa84472392f350a0e8a3618181e6c7500fa6b9b1082b1b998d047b8
  • Pointer size: 131 Bytes
  • Size of remote file: 379 kB
public/star-history-202556.png ADDED

Git LFS Details

  • SHA256: 8612c6e1a5b2e9bc3fca247acc0987add3d90c56eb5c6be8cc1ebaa8c592bd8f
  • Pointer size: 131 Bytes
  • Size of remote file: 210 kB
public/starpo_logo.png ADDED

Git LFS Details

  • SHA256: c40be49fa37555f3dc712e2d91d35e599e6c0a0f107e911af7dfca05d56a1d8e
  • Pointer size: 131 Bytes
  • Size of remote file: 667 kB
public/step_1.png ADDED

Git LFS Details

  • SHA256: 7056b065aa5d0f2fbb7af3ccefc26a34a94f6555d7626082e90a3f5f17c7f27e
  • Pointer size: 132 Bytes
  • Size of remote file: 4.76 MB
public/step_2.png ADDED

Git LFS Details

  • SHA256: ec41173ee19feb2e2bb96cdce2e110002de0474f78ce286decffed3135acff36
  • Pointer size: 132 Bytes
  • Size of remote file: 4.76 MB
ragen/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """RAGEN package initialisation."""
2
+
3
+ from ragen.patches import apply_omega_conf_patch
4
+
5
+ # Ensure VERL config instantiation accepts RAGEN-specific extensions.
6
+ apply_omega_conf_patch()
ragen/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (250 Bytes). View file
 
ragen/__pycache__/utils.cpython-310.pyc ADDED
Binary file (3.01 kB). View file
 
ragen/demo/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Give an instant demo about LLM rollout and how they process the environment
ragen/demo/run.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from ragen.llm_agent.agent_proxy import LLMAgentProxy, VllmWrapperWg
3
+ from verl import DataProto
4
+ from transformers import AutoTokenizer
5
+ import hydra
6
+ import os
7
+ import time
8
+ import asyncio
9
+
10
+ # --- Global agent object
11
+ agent_proxy = None
12
+
13
+ # --- Initialization function
14
+ @hydra.main(version_base=None, config_path="../../config", config_name="stream")
15
+ def init_agent(config):
16
+ global agent_proxy
17
+ os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
18
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(config.system.CUDA_VISIBLE_DEVICES)
19
+ tokenizer = AutoTokenizer.from_pretrained(config.actor_rollout_ref.model.path)
20
+ actor_wg = VllmWrapperWg(config, tokenizer)
21
+ agent_proxy = LLMAgentProxy(config, actor_wg, tokenizer)
22
+
23
+ # --- Streaming rollout generator
24
+ def rollout_stream():
25
+ lm_inputs = DataProto(batch=None, non_tensor_batch=None, meta_info={
26
+ 'eos_token_id': 151645,
27
+ 'pad_token_id': 151643,
28
+ 'recompute_log_prob': False,
29
+ 'do_sample': True,
30
+ 'validate': True
31
+ })
32
+ env_outputs = agent_proxy.val_es_manager.reset()
33
+ assert len(env_outputs) == 1
34
+
35
+ for turn_idx in range(agent_proxy.config.agent_proxy.max_turn):
36
+ lm_inputs = agent_proxy.val_ctx_manager.get_lm_inputs(env_outputs, prepare_for_update=False)
37
+ lm_inputs.meta_info = {'eos_token_id': 151645, 'pad_token_id': 151643, 'recompute_log_prob': False, 'do_sample': True, 'validate': True}
38
+ lm_outputs = agent_proxy.generate_sequences(lm_inputs)
39
+
40
+ response_texts = lm_outputs.non_tensor_batch['response_texts']
41
+ yield f"\n--- Turn {turn_idx + 1} ---\n"
42
+ yield response_texts[0]
43
+
44
+ env_inputs = agent_proxy.val_ctx_manager.get_env_inputs(lm_outputs)
45
+ env_outputs = agent_proxy.val_es_manager.step(env_inputs)
46
+ if len(env_outputs) == 0:
47
+ break
48
+ yield env_outputs[0]['history'][-1]['state']
49
+
50
+ # --- Gradio Streaming Setup
51
+ async def streaming_demo():
52
+ stream = rollout_stream()
53
+ output = ""
54
+ for chunk in stream:
55
+ output += chunk
56
+ yield output
57
+
58
+ def main():
59
+ init_agent()
60
+
61
+ with gr.Blocks() as demo:
62
+ output_box = gr.Textbox(label="Agent Output", lines=20)
63
+ run_button = gr.Button("Run Agent")
64
+
65
+ run_button.click(fn=streaming_demo, inputs=[], outputs=output_box)
66
+
67
+ demo.queue()
68
+ demo.launch()
69
+
70
+ if __name__ == "__main__":
71
+ main()
ragen/env/__init__.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # from .alfworld.config import AlfredEnvConfig
2
+ # from .alfworld.env import AlfredTXTEnv
3
+ from .bandit.config import BanditEnvConfig
4
+ from .bandit.env import BanditEnv
5
+ from .countdown.config import CountdownEnvConfig
6
+ from .countdown.env import CountdownEnv
7
+ from .sokoban.config import SokobanEnvConfig
8
+ from .sokoban.env import SokobanEnv
9
+ from .frozen_lake.config import FrozenLakeEnvConfig
10
+ from .frozen_lake.env import FrozenLakeEnv
11
+ from .metamathqa.env import MetaMathQAEnv
12
+ from .metamathqa.config import MetaMathQAEnvConfig
13
+ from .lean.config import LeanEnvConfig
14
+ from .lean.env import LeanEnv
15
+ from .game_2048.config import Game2048EnvConfig
16
+ from .game_2048.env import Game2048Env
17
+ from .blackjack.config import BlackjackEnvConfig
18
+ from .blackjack.env import BlackjackEnv
19
+ from .rubikscube.config import RubiksCube2x2Config
20
+ from .rubikscube.env import RubiksCube2x2Env
21
+ from .sudoku.config import SudokuEnvConfig
22
+ from .sudoku.env import SudokuEnv
23
+
24
+
25
+ REGISTERED_ENVS = {
26
+ 'bandit': BanditEnv,
27
+ 'countdown': CountdownEnv,
28
+ 'sokoban': SokobanEnv,
29
+ 'frozen_lake': FrozenLakeEnv,
30
+ # 'alfworld': AlfredTXTEnv,
31
+ 'metamathqa': MetaMathQAEnv,
32
+ 'lean': LeanEnv,
33
+ 'game_2048': Game2048Env,
34
+ 'blackjack': BlackjackEnv,
35
+ 'rubikscube': RubiksCube2x2Env,
36
+ 'sudoku': SudokuEnv,
37
+ }
38
+
39
+ REGISTERED_ENV_CONFIGS = {
40
+ 'bandit': BanditEnvConfig,
41
+ 'countdown': CountdownEnvConfig,
42
+ 'sokoban': SokobanEnvConfig,
43
+ 'frozen_lake': FrozenLakeEnvConfig,
44
+ # 'alfworld': AlfredEnvConfig,
45
+ 'metamathqa': MetaMathQAEnvConfig,
46
+ 'lean': LeanEnvConfig,
47
+ 'game_2048': Game2048EnvConfig,
48
+ 'blackjack': BlackjackEnvConfig,
49
+ 'rubikscube': RubiksCube2x2Config,
50
+ 'sudoku': SudokuEnvConfig,
51
+ }
52
+
53
+ try:
54
+ from .webshop.env import WebShopEnv
55
+ from .webshop.config import WebShopEnvConfig
56
+ REGISTERED_ENVS['webshop'] = WebShopEnv
57
+ REGISTERED_ENV_CONFIGS['webshop'] = WebShopEnvConfig
58
+ except ImportError:
59
+ pass
ragen/env/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.61 kB). View file
 
ragen/env/__pycache__/base.cpython-310.pyc ADDED
Binary file (3.95 kB). View file
 
ragen/env/alfworld_old/alfworld_config.yaml ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ data_path: '$ALFWORLD_DATA/json_2.1.1/train'
3
+ eval_id_data_path: '$ALFWORLD_DATA/json_2.1.1/valid_seen' # null/None to disable
4
+ eval_ood_data_path: '$ALFWORLD_DATA/json_2.1.1/valid_unseen' # null/None to disable
5
+ num_train_games: -1 # max training games (<=0 indicates full dataset)
6
+ num_eval_games: -1 # max evaluation games (<=0 indicates full dataset)
7
+
8
+ logic:
9
+ domain: '$ALFWORLD_DATA/logic/alfred.pddl' # PDDL domain file that defines the world dynamics
10
+ grammar: '$ALFWORLD_DATA/logic/alfred.twl2' # Grammar file that defines the text feedbacks
11
+
12
+ env:
13
+ type: 'AlfredTWEnv' # 'AlfredTWEnv' or 'AlfredThorEnv' or 'AlfredHybrid'
14
+ # regen_game_files: False # [Deprecated] Use script `alfworld-generate` instead.
15
+ domain_randomization: False # shuffle Textworld print order and object id nums
16
+ 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
17
+ expert_timeout_steps: 150 # max steps before timeout for expert to solve the task
18
+ expert_type: "handcoded" # 'handcoded' or 'planner'. Note: the planner is very slow for real-time use
19
+ 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)
20
+
21
+ hybrid:
22
+ start_eps: 100000 # starting episode of hybrid training, tw-only training upto this point
23
+ thor_prob: 0.5 # prob of AlfredThorEnv during hybrid training
24
+ eval_mode: "tw" # 'tw' or 'thor' - env used for evaluation during hybrid training
25
+
26
+ thor:
27
+ screen_width: 300 # width of THOR window
28
+ screen_height: 300 # height of THOR window
29
+ smooth_nav: False # smooth rotations, looks, and translations during navigation (very slow)
30
+ save_frames_to_disk: False # save frame PNGs to disk (useful for making videos)
31
+ save_frames_path: './videos/' # path to save frame PNGs
32
+
33
+ controller:
34
+ type: 'oracle' # 'oracle' or 'oracle_astar' or 'mrcnn' or 'mrcnn_astar' (aka BUTLER)
35
+ debug: False
36
+ load_receps: True # load receptacle locations from precomputed dict (if available)
37
+
38
+ mask_rcnn:
39
+ pretrained_model_path: '$ALFWORLD_DATA/detectors/mrcnn.pth'
40
+
41
+ general:
42
+ random_seed: 42
43
+ use_cuda: True # disable this when running on machine without cuda
44
+ visdom: False # plot training/eval curves, run with visdom server
45
+ task: 'alfred'
46
+ training_method: 'dagger' # 'dqn' or 'dagger'
47
+ save_path: './training/' # path to save pytorch models
48
+ observation_pool_capacity: 3 # k-size queue, 0 indicates no observation
49
+ hide_init_receptacles: False # remove initial observation containing navigable receptacles
50
+
51
+ training:
52
+ batch_size: 10
53
+ max_episode: 50000
54
+ smoothing_eps: 0.1
55
+ optimizer:
56
+ learning_rate: 0.001
57
+ clip_grad_norm: 5
58
+
59
+ evaluate:
60
+ run_eval: True
61
+ batch_size: 10
62
+ env:
63
+ type: "AlfredTWEnv"
64
+
65
+ checkpoint:
66
+ report_frequency: 1000 # report every N episode
67
+ experiment_tag: 'test' # name of experiment
68
+ load_pretrained: False # during test, enable this so that the agent load your pretrained model
69
+ load_from_tag: 'not loading anything' # name of pre-trained model to load in save_path
70
+
71
+ model:
72
+ encoder_layers: 1
73
+ decoder_layers: 1
74
+ encoder_conv_num: 5
75
+ block_hidden_dim: 64
76
+ n_heads: 1
77
+ dropout: 0.1
78
+ block_dropout: 0.1
79
+ recurrent: True
80
+
81
+ rl:
82
+ action_space: "admissible" # 'admissible' (candidates from text engine) or 'generation' (seq2seq-style generation) or 'beam_search_choice' or 'exhaustive' (not working)
83
+ max_target_length: 20 # max token length for seq2seq generation
84
+ beam_width: 10 # 1 means greedy
85
+ generate_top_k: 3
86
+
87
+ training:
88
+ max_nb_steps_per_episode: 50 # terminate after this many steps
89
+ learn_start_from_this_episode: 0 # delay updates until this epsiode
90
+ target_net_update_frequency: 500 # sync target net with online net per this many epochs
91
+
92
+ replay:
93
+ accumulate_reward_from_final: True
94
+ count_reward_lambda: 0.0 # 0 to disable
95
+ novel_object_reward_lambda: 0.0 # 0 to disable
96
+ discount_gamma_game_reward: 0.9
97
+ discount_gamma_count_reward: 0.5
98
+ discount_gamma_novel_object_reward: 0.5
99
+ replay_memory_capacity: 500000 # adjust this depending on your RAM size
100
+ replay_memory_priority_fraction: 0.5
101
+ update_per_k_game_steps: 5
102
+ replay_batch_size: 64
103
+ multi_step: 3
104
+ replay_sample_history_length: 4
105
+ replay_sample_update_from: 2
106
+
107
+ epsilon_greedy:
108
+ noisy_net: False # if this is true, then epsilon greedy is disabled
109
+ epsilon_anneal_episodes: 1000 # -1 if not annealing
110
+ epsilon_anneal_from: 0.3
111
+ epsilon_anneal_to: 0.1
112
+
113
+ dagger:
114
+ action_space: "generation" # 'admissible' (candidates from text engine) or 'generation' (seq2seq-style generation) or 'exhaustive' (not working)
115
+ max_target_length: 20 # max token length for seq2seq generation
116
+ beam_width: 10 # 1 means greedy
117
+ generate_top_k: 5
118
+ unstick_by_beam_search: False # use beam-search for failed actions, set True during evaluation
119
+
120
+ training:
121
+ max_nb_steps_per_episode: 50 # terminate after this many steps
122
+
123
+ fraction_assist:
124
+ fraction_assist_anneal_episodes: 50000
125
+ fraction_assist_anneal_from: 1.0
126
+ fraction_assist_anneal_to: 0.01
127
+
128
+ fraction_random:
129
+ fraction_random_anneal_episodes: 0
130
+ fraction_random_anneal_from: 0.0
131
+ fraction_random_anneal_to: 0.0
132
+
133
+ replay:
134
+ replay_memory_capacity: 500000
135
+ update_per_k_game_steps: 5
136
+ replay_batch_size: 64
137
+ replay_sample_history_length: 4
138
+ replay_sample_update_from: 2
139
+
140
+ vision_dagger:
141
+ 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)
142
+ resnet_fc_dim: 64
143
+ maskrcnn_top_k_boxes: 10 # top k box features
144
+ use_exploration_frame_feats: False # append feats from initial exploration (memory intensive!)
145
+ sequence_aggregation_method: "average" # 'sum' or 'average' or 'rnn'
ragen/env/alfworld_old/config.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ragen.env.base import BaseEnvConfig
2
+ from dataclasses import dataclass, field
3
+ from typing import Dict
4
+
5
+ @dataclass
6
+ class AlfredEnvConfig(BaseEnvConfig):
7
+ """configuration for text world AlfredEnv"""
8
+ config_file: str = "./ragen/env/alfworld/alfworld_config.yaml"
9
+ action_lookup: Dict[int, str] = field(default_factory=lambda: {
10
+ 1: "look",
11
+ 2: "inventory",
12
+ 3: "go to <receptacle>",
13
+ 4: "open <receptacle>",
14
+ 5: "close <receptacle>",
15
+ 6: "take <object> from <receptacle>",
16
+ 7: "move <object> to <receptacle>",
17
+ 8: "examine <something>",
18
+ 9: "use <object>",
19
+ 10: "heat <object> with <receptacle>",
20
+ 11: "clean <object> with <receptacle>",
21
+ 12: "cool <object> with <receptacle>",
22
+ 13: "slice <object> with <object>"
23
+ })
24
+ format_score: float = 0.1
25
+ score: float = 1.0
26
+ render_mode: str = "text"
ragen/env/alfworld_old/env.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This is the environment for the ALFRED dataset.
3
+ author: Qineng Wang
4
+ date: 2025-03-30
5
+ """
6
+ import os
7
+ import random
8
+ import textworld
9
+ import textworld.gym
10
+ import numpy as np
11
+ import alfworld.agents.modules.generic as generic
12
+ from alfworld.agents.environment.alfred_tw_env import AlfredTWEnv, AlfredDemangler, AlfredInfos
13
+ from ragen.env.base import BaseLanguageBasedEnv
14
+ from ragen.env.alfworld.config import AlfredEnvConfig
15
+ from ragen.env.alfworld.utils import load_config, check_format
16
+
17
+ class AlfredTXTEnv(BaseLanguageBasedEnv):
18
+
19
+ # raw_env: AlfredTWEnv = AlfredTWEnv(config=load_config(AlfredEnvConfig().config_file), train_eval="train")
20
+ # print("initializing alfworld env")
21
+ # NOTE Currently raw_env cannot customize config.
22
+
23
+ def __init__(self, config: AlfredEnvConfig = AlfredEnvConfig(), mode='eval_in_distribution'):
24
+ # mode: "train", "eval_in_distribution" or "eval_out_of_distribution"
25
+ super().__init__()
26
+ self.config = config
27
+ self.ACTION_LOOKUP = self.config.action_lookup
28
+ raw_env_config = load_config(self.config.config_file)
29
+ self.raw_env = AlfredTWEnv(config=raw_env_config, train_eval=mode)
30
+ self.num_games = self.raw_env.num_games
31
+ self.game_files = self.raw_env.game_files
32
+ print(f"Overall we have {len(self.game_files)} games in split={self.raw_env.train_eval}")
33
+ self.alfred_env = self.raw_env.init_env(batch_size=1)
34
+ self.current_game_file = None
35
+ self.render_cache = None
36
+ self.available_actions = None
37
+ self.render_mode = self.config.render_mode
38
+ assert self.render_mode == 'text'
39
+
40
+ def reset(self, seed=None, mode=None):
41
+ """
42
+ Reset the environment with a specific seed.
43
+ If seed is provided, it deterministically selects a specific game file.
44
+ """
45
+ try:
46
+ if mode == "test":
47
+ if seed is None:
48
+ raise ValueError("Seed must be provided in test mode.")
49
+ selected_game = self.game_files[seed]
50
+ else:
51
+ if seed is not None:
52
+ np.random.seed(seed)
53
+ random.seed(seed)
54
+ game_idx = seed % len(self.game_files)
55
+ selected_game = self.game_files[game_idx]
56
+ else:
57
+ selected_game = random.choice(self.game_files)
58
+
59
+ self.current_game_file = selected_game
60
+
61
+ if hasattr(self, 'alfred_env') and self.alfred_env is not None:
62
+ self.alfred_env.close()
63
+
64
+ request_infos = textworld.EnvInfos(won=True, admissible_commands=True, extras=["gamefile"])
65
+ config = load_config(self.config.config_file)
66
+ wrappers = [AlfredDemangler(), AlfredInfos()]
67
+ max_steps = config["rl"]["training"]["max_nb_steps_per_episode"]
68
+
69
+ env_id = textworld.gym.register_game(
70
+ selected_game,
71
+ request_infos=request_infos,
72
+ batch_size=1,
73
+ asynchronous=False,
74
+ max_episode_steps=max_steps,
75
+ wrappers=wrappers
76
+ )
77
+
78
+ self.alfred_env = textworld.gym.make(env_id)
79
+
80
+ obs, info = self.alfred_env.reset()
81
+ self.render_cache = obs[0]
82
+ self.available_actions = info["admissible_commands"][0]
83
+ self.instruction_text = obs[0]
84
+ return self.render_cache
85
+
86
+ except (RuntimeError, RuntimeWarning) as e:
87
+ print(f"Error in reset: {e}")
88
+ next_seed = abs(hash(str(seed))) % (2 ** 32) if seed is not None else None
89
+ return self.reset(next_seed)
90
+
91
+ def compute_score(self, base_reward, valid_action, done):
92
+ """
93
+ Compute the score based on the base reward, format reward, and completion status.
94
+
95
+ Args:
96
+ base_reward: The reward from the environment
97
+ valid_action: Whether the action format is valid
98
+ done: Whether the episode is finished
99
+
100
+ Returns:
101
+ The computed score
102
+ """
103
+ if done:
104
+ return self.config.score + self.config.format_score + base_reward
105
+ elif valid_action:
106
+ return base_reward + self.config.format_score
107
+ else:
108
+ return 0.0
109
+
110
+ def step(self, action: str):
111
+ """
112
+ Take a step in the environment using the provided action string.
113
+ The action must match one of the templates in ACTION_LOOKUP.
114
+ """
115
+ valid_action = check_format(action, self.ACTION_LOOKUP.values())
116
+ action_is_available = True if action in self.available_actions else False
117
+ if not valid_action:
118
+ return f"Invalid action format: {action}", 0, False, {"action_is_effective": False, "action_is_valid": False, "success": False}
119
+
120
+ obs, rewards, dones, infos = self.alfred_env.step([action]) # BatchEnv expects a list of commands
121
+ observation = obs[0]
122
+ self.available_actions = infos["admissible_commands"][0]
123
+ self.render_cache = observation
124
+ base_reward = rewards[0]
125
+ done = dones[0]
126
+ info = {"action_is_effective": True, "action_is_valid": action_is_available, "success": infos["won"][0]}
127
+
128
+ reward = self.compute_score(base_reward, valid_action, done)
129
+
130
+ return self.render_cache, reward, done, info
131
+
132
+ def render(self):
133
+ return self.render_cache
134
+
135
+ def close(self):
136
+ self.render_cache = None
137
+ self.alfred_env.close()
138
+
139
+ if __name__ == "__main__":
140
+ import os
141
+ os.environ["ALFWORLD_DATA"] = "./data/alfworld"
142
+ env = AlfredTXTEnv()
143
+
144
+ # Test resetting environment with same seed
145
+ print("\n\n=== Testing environment reset with same seed ===")
146
+ seed = 42
147
+ obs1 = env.reset(seed)
148
+ for i in range(52):
149
+ print("Observation:", obs1)
150
+ action = "go to shelf 2"
151
+ if action.lower() == "exit":
152
+ break
153
+ obs1, reward, done, info = env.step(action)
154
+
155
+ print(f"Reward: {reward}, Done: {done}, Info: {info}")
156
+ if done:
157
+ break
158
+
ragen/env/alfworld_old/utils.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import yaml
4
+ import re
5
+ from typing import List, Any
6
+
7
+ def load_config(config_file: str, params: List[str] = []):
8
+ assert os.path.exists(config_file), f"Invalid config file: {config_file}"
9
+ with open(config_file) as reader:
10
+ config = yaml.safe_load(reader)
11
+ # Parse overriden params.
12
+ for param in params:
13
+ fqn_key, value = param.split("=")
14
+ entry_to_change = config
15
+ keys = fqn_key.split(".")
16
+ for k in keys[:-1]:
17
+ entry_to_change = entry_to_change[k]
18
+ entry_to_change[keys[-1]] = value
19
+ return config
20
+
21
+ def check_format(action: str, templates: Any) -> bool:
22
+ """
23
+ Validate that the action matches one of our action templates.
24
+ Returns True if valid, False otherwise.
25
+ """
26
+ if "None" in action:
27
+ return False
28
+
29
+ # Skip validation for basic actions that don't have placeholders
30
+ basic_actions = ["look", "inventory"]
31
+ if action in basic_actions:
32
+ return True
33
+
34
+ # Check if the action follows any of our templates
35
+ for template in templates:
36
+ # Skip "None" and basic actions we already checked
37
+ if template == "None" or template in basic_actions:
38
+ continue
39
+
40
+ # Convert template to regex pattern
41
+ # Replace <something> with regex that matches any word(s)
42
+ pattern = template.replace("<receptacle>", "([\\w\\s]+)") \
43
+ .replace("<object>", "([\\w\\s]+)") \
44
+ .replace("<something>", "([\\w\\s]+)")
45
+ pattern = f"^{pattern}$" # Match the entire string
46
+
47
+ if re.match(pattern, action):
48
+ return True
49
+
50
+ return False
51
+
52
+ def check_correctness(action: str, target: str) -> bool:
53
+ ...
ragen/env/bandit/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .env import BanditEnv
2
+ from .config import BanditEnvConfig
3
+
4
+ __all__ = ["BanditEnv", "BanditEnvConfig"]
ragen/env/bandit/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (259 Bytes). View file
 
ragen/env/bandit/__pycache__/config.cpython-310.pyc ADDED
Binary file (1.33 kB). View file
 
ragen/env/bandit/__pycache__/env.cpython-310.pyc ADDED
Binary file (4.58 kB). View file
 
ragen/env/bandit/config.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Dict
3
+
4
+ @dataclass
5
+ class BanditEnvConfig:
6
+ split: str = "train"
7
+ action_space_start: int = 1
8
+ lo_arm_score: float = 0.1
9
+ hi_arm_loscore: float = 0.0
10
+ hi_arm_hiscore: float = 1.0
11
+ hi_arm_hiscore_prob: float = 0.25
12
+ render_mode: str = "text"
13
+ action_lookup: Dict[int, str] = None # defined in env.py
14
+
15
+
16
+ ARM_NAMES = {
17
+ "train": [
18
+ ("Teacher", "Trader"),
19
+ ("Nurse", "StartupFounder"),
20
+ ("Librarian", "Investor"),
21
+ ("Accountant", "StockBroker"),
22
+ ("Engineer", "RealEstateAgent"),
23
+ ("Pharmacist", "Musician"),
24
+ ("Clerk", "Freelancer"),
25
+ ("Technician", "Youtuber"),
26
+ ("Planner", "Artist"),
27
+ ("Postman", "Pilot"),
28
+ ("Banker", "VentureCapitalist"),
29
+ ("Gardener", "Cryptominer"),
30
+ ],
31
+ "test": [
32
+ ("Receptionist", "Explorer"),
33
+ ("Archivist", "Filmmaker"),
34
+ ("Bookkeeper", "Consultant"),
35
+ ("SocialWorker", "Photographer"),
36
+ ("Mechanic", "GameDesigner"),
37
+ ("Secretary", "Entrepreneur"),
38
+ ("Cashier", "DataScientist"),
39
+ ("CivilServant", "StartupAccelerator"),
40
+ ],
41
+ }
ragen/env/bandit/env.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gymnasium as gym
2
+ import numpy as np
3
+ from ragen.env.base import BaseDiscreteActionEnv
4
+ from .config import BanditEnvConfig, ARM_NAMES
5
+
6
+ INIT_PROMPT = """You are playing a bandit game. Goal: Maximize your total reward by choosing which arm to pull.
7
+ Game Rules:
8
+ 1. There are 2 arms, named {name_a} and {name_b}
9
+ 2. Each arm has its own reward distribution, related to their names.
10
+ 3. Analyze the symbolic meaning of each arm's name to guess how their reward distribution might behave.
11
+ 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 <answer> {name_a} </answer> or <answer> {name_b} </answer>.
12
+ """
13
+
14
+ # INIT_PROMPT = """You are playing a bandit game. Goal: Maximize your total reward by choosing which arm to pull.
15
+ # Game Rules:
16
+ # 1. There are 2 arms, named {name_a} and {name_b}.
17
+ # 2. Each arm has its own reward distribution, related to their names.
18
+ # 3. You need to analyze the symbolic meaning of each arm's name to guess their reward potential.
19
+
20
+ # Example answer format:
21
+ # <think>
22
+ # <observation>
23
+ # Arm A is named \"{name_a}\". Symbolically, this implies [analysis of name A].
24
+ # Arm B is named \"{name_b}\". Symbolically, this implies [analysis of name B].
25
+ # </observation>
26
+ # Based on the analysis, {name_a} seems to represent risk/low value, while {name_b} implies wealth/stability.
27
+ # <prediction>
28
+ # If I pull {name_b}, I expect a higher average reward because [reasoning].
29
+ # </prediction>
30
+ # </think>
31
+ # <answer> {name_b} </answer>
32
+
33
+ # A sample full output is as follows:
34
+ # <think>
35
+ # <observation>
36
+ # Arm A is named "Rotten Apple". Symbolically, this implies decay and zero value.
37
+ # Arm B is named "Golden Chalice". Symbolically, this implies treasure and high value.
38
+ # </observation>
39
+ # Comparing the two, the Golden Chalice is clearly superior in potential value.
40
+ # <prediction>
41
+ # Pulling "Golden Chalice" will likely yield a high positive reward, whereas "Rotten Apple" might give zero or negative reward.
42
+ # </prediction>
43
+ # </think>
44
+ # <answer> Golden Chalice </answer>"""
45
+
46
+ class BanditEnv(BaseDiscreteActionEnv, gym.Env):
47
+ class_counter = 0
48
+
49
+ def __init__(self, config = None):
50
+ BaseDiscreteActionEnv.__init__(self)
51
+ self.config = config if config is not None else BanditEnvConfig()
52
+ self.ACTION_SPACE = gym.spaces.discrete.Discrete(2, start=self.config.action_space_start)
53
+ self.split = self.config.split
54
+ self.render_cache = None
55
+ self.render_mode = self.config.render_mode
56
+ self.internal_seed = BanditEnv.class_counter
57
+ BanditEnv.class_counter += 1
58
+ assert self.render_mode == 'text'
59
+
60
+ def _randomize_arms(self):
61
+ start = self.config.action_space_start
62
+ if self.np_random.random() < 0.5:
63
+ self.ACTION_LOOKUP = {
64
+ start: self.lo_arm_name,
65
+ start + 1: self.hi_arm_name,
66
+ }
67
+ else:
68
+ self.ACTION_LOOKUP = {
69
+ start: self.hi_arm_name,
70
+ start + 1: self.lo_arm_name,
71
+ }
72
+ self.config.action_lookup = self.ACTION_LOOKUP
73
+ self.ARM_IDX_TO_NAME = self.ACTION_LOOKUP
74
+ self.NAME_TO_ARM_IDX = {name: idx for idx, name in self.ACTION_LOOKUP.items()}
75
+
76
+ def _lo_arm_reward(self):
77
+ return self.config.lo_arm_score
78
+
79
+ def _hi_arm_reward(self):
80
+ if self.np_random.random() < self.config.hi_arm_hiscore_prob:
81
+ return self.config.hi_arm_hiscore
82
+ return self.config.hi_arm_loscore
83
+
84
+ def render(self):
85
+ return self.render_cache
86
+
87
+ def reset(self, seed=None, mode=None):
88
+ if seed is not None:
89
+ gym.Env.reset(self, seed=seed + self.internal_seed) # add internal seed to differ random reward generator inside the same group
90
+ else:
91
+ gym.Env.reset(self, seed=seed)
92
+ index = int(self.np_random.random() * len(ARM_NAMES[self.split]))
93
+ self.lo_arm_name, self.hi_arm_name = ARM_NAMES[self.split][index]
94
+ self._randomize_arms()
95
+ pos1 = self.config.action_space_start
96
+ pos2 = pos1 + 1
97
+ machine1 = self.ARM_IDX_TO_NAME[pos1]
98
+ machine2 = self.ARM_IDX_TO_NAME[pos2]
99
+ self.render_cache = INIT_PROMPT.format(name_a=machine1, name_b=machine2)
100
+ return self.render_cache
101
+
102
+ def step(self, action: int):
103
+ assert action in self.ACTION_LOOKUP, f"Invalid action: {action}"
104
+ reward = self.compute_reward(action)
105
+ arm_name = self.ARM_IDX_TO_NAME[action]
106
+ next_obs = f"{arm_name}: {reward} points"
107
+ self.render_cache = next_obs
108
+ done, info = True, {"action_is_effective": True, "action_is_valid": True, "success": arm_name == self.hi_arm_name}
109
+ return next_obs, reward, done, info
110
+
111
+ def compute_reward(self, action):
112
+ arm_name = self.ARM_IDX_TO_NAME[action]
113
+ if arm_name == self.lo_arm_name:
114
+ return self._lo_arm_reward()
115
+ else:
116
+ return self._hi_arm_reward()
117
+
118
+ def get_all_actions(self):
119
+ return [self.ACTION_SPACE.start, self.ACTION_SPACE.start + 1]
120
+
121
+ def render(self):
122
+ return self.render_cache
123
+
124
+ def close(self):
125
+ self.render_cache = None
126
+
127
+ if __name__ == "__main__":
128
+ def run_simulation(env, n_episodes=1000, action=1, start_seed=500):
129
+ rewards = []
130
+ for i in range(start_seed, start_seed + n_episodes):
131
+ env.reset(seed=i)
132
+ reward = env.step(action)[1]
133
+ rewards.append(reward)
134
+
135
+ return {
136
+ 'mean_reward': np.mean(rewards),
137
+ 'std_reward': np.std(rewards),
138
+ 'n_episodes': n_episodes,
139
+ 'action': env.ARM_IDX_TO_NAME[action]
140
+ }
141
+
142
+ env = BanditEnv()
143
+ stats = run_simulation(env)
144
+ print(f"Arm: {stats['action']}, Reward: {stats['mean_reward']:.3f} ± {stats['std_reward']:.3f}")
ragen/env/base.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ import re
3
+ from typing import Optional, List, Tuple, Any, Dict
4
+
5
+ class BaseEnv(ABC):
6
+ """
7
+ Abstract base class for all environments.
8
+ The class needs to handle text-based input, input may be invalid
9
+ - Environment will track the total reward for the trajectory
10
+
11
+ """
12
+ def __init__(self):
13
+ pass
14
+
15
+ @abstractmethod
16
+ def reset(self, seed=None, **kwargs) -> Any:
17
+ """
18
+ Reset the environment.
19
+ NOTE: the environment should be same for the same seed
20
+ Returns:
21
+ rendered environment
22
+ """
23
+ pass
24
+
25
+ @abstractmethod
26
+ def step(self, action) -> Tuple[Any, float, bool, Dict]:
27
+ """
28
+ Execute one step in the environment.
29
+ NOTE should also handle predefined invalid action (0)
30
+ Args:
31
+ action: Action to take, must be in action space, or default invalid action
32
+
33
+ Returns:
34
+ observation (rendered environment), reward, done, info
35
+ """
36
+ pass
37
+
38
+ # below are optional methods
39
+
40
+ def render(self, mode: str = 'text') -> Any:
41
+ """Render the environment. Optional method."""
42
+ pass
43
+
44
+ def compute_reward(self, action, **kwargs) -> float:
45
+ """Compute reward for the action."""
46
+ pass
47
+
48
+ def close(self):
49
+ """Close the environment."""
50
+ pass
51
+
52
+
53
+ class BaseDiscreteActionEnv(BaseEnv, ABC):
54
+ """
55
+ Abstract base class for environments with discrete action spaces
56
+ This class provides common functionality for environments like FrozenLakeEnv and SokobanEnv.
57
+ """
58
+
59
+ @abstractmethod
60
+ def step(self, action: int) -> Tuple[Any, float, bool, Dict]:
61
+ """
62
+ Execute one step in the environment.
63
+ Args:
64
+ action: Action to take, must be in action space, or default invalid action
65
+ Returns:
66
+ observation (rendered environment), reward, done, info
67
+ """
68
+ pass
69
+
70
+ @abstractmethod
71
+ def get_all_actions(self) -> List[int]:
72
+ """Get list of all valid actions."""
73
+ pass
74
+
75
+
76
+ class BaseLanguageBasedEnv(BaseEnv, ABC):
77
+ """
78
+ Abstract base class for environments with language-based action space environment
79
+ This class provides common functionality for environments like countdown from TinyZero
80
+ """
81
+
82
+ @abstractmethod
83
+ def step(self, action: str) -> Tuple[Any, float, bool, Dict]:
84
+ """
85
+ Execute one step in the environment.
86
+ Args:
87
+ action: Action to take, must be in action space, or default invalid action
88
+ Returns:
89
+ observation (rendered environment), reward, done, info
90
+ """
91
+ pass
92
+
93
+
94
+ class BaseEnvConfig(ABC):
95
+ """
96
+ Abstract base class for environment configurations.
97
+ """
98
+ def __init__(self):
99
+ self.invalid_act = ""
100
+ self.invalid_act_score = 0
ragen/env/blackjack/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .config import BlackjackEnvConfig
2
+ from .env import BlackjackEnv
ragen/env/blackjack/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (239 Bytes). View file
 
ragen/env/blackjack/__pycache__/config.cpython-310.pyc ADDED
Binary file (886 Bytes). View file
 
ragen/env/blackjack/__pycache__/env.cpython-310.pyc ADDED
Binary file (4.29 kB). View file
 
ragen/env/blackjack/config.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ import gymnasium as gym
3
+ from ragen.env.base import BaseEnvConfig
4
+
5
+
6
+ @dataclass
7
+ class BlackjackEnvConfig(BaseEnvConfig):
8
+ render_mode: str = "text"
9
+ action_lookup: dict = None
10
+
11
+ def __post_init__(self):
12
+ if self.action_lookup is None:
13
+ # 1: Stick, 2: Hit
14
+ self.action_lookup = {1: "Stick", 2: "Hit"}
15
+ self.invalid_act = 0
16
+ self.invalid_act_score = 0.0
17
+ self.ACTION_SPACE = gym.spaces.discrete.Discrete(2, start=1)
ragen/env/blackjack/env.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gymnasium as gym
2
+ import numpy as np
3
+ from typing import Tuple, Any, Dict, List
4
+ from ragen.env.base import BaseDiscreteActionEnv
5
+ from .config import BlackjackEnvConfig
6
+ from ragen.utils import all_seed
7
+
8
+ def draw_card(rng: np.random.Generator) -> int:
9
+ # 1 is Ace, 2-9 as is, 10 represents 10/J/Q/K
10
+ card_vals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
11
+ weights = [1, 1, 1, 1, 1, 1, 1, 1, 1, 4]
12
+ probs = np.array(weights, dtype=np.float64)
13
+ probs /= probs.sum()
14
+ return int(rng.choice(card_vals, p=probs))
15
+
16
+ def usable_ace(hand: List[int]) -> bool:
17
+ return 1 in hand and sum(hand) + 10 <= 21
18
+
19
+ def hand_sum(hand: List[int]) -> int:
20
+ total = sum(hand)
21
+ if 1 in hand and total + 10 <= 21:
22
+ return total + 10
23
+ return total
24
+
25
+ class BlackjackEnv(BaseDiscreteActionEnv, gym.Env):
26
+ def __init__(self, config: BlackjackEnvConfig | None = None):
27
+ BaseDiscreteActionEnv.__init__(self)
28
+ self.config = config or BlackjackEnvConfig()
29
+ self.ACTION_LOOKUP = self.config.action_lookup
30
+ self.ACTION_SPACE = gym.spaces.discrete.Discrete(2, start=1)
31
+ self.render_mode = self.config.render_mode
32
+ self.rng = np.random.default_rng()
33
+ self.player = []
34
+ self.dealer = []
35
+
36
+ def reset(self, seed=None, mode=None):
37
+ gym.Env.reset(self, seed=seed)
38
+ with all_seed(seed):
39
+ self.rng = np.random.default_rng(seed)
40
+ self.player = [draw_card(self.rng), draw_card(self.rng)]
41
+ self.dealer = [draw_card(self.rng), draw_card(self.rng)]
42
+
43
+ # 即使起手21点,Gym的reset也不能返回done,只能通过Observation提示
44
+ return self.render(done=False)
45
+
46
+ def step(self, action: int) -> Tuple[Any, float, bool, Dict]:
47
+ assert action in self.ACTION_LOOKUP, f"Invalid action: {action}"
48
+ info = {"action_is_effective": True, "action_is_valid": True, "success": False}
49
+
50
+ # 1: Stick, 2: Hit
51
+ if action == 2: # Hit
52
+ self.player.append(draw_card(self.rng))
53
+ if hand_sum(self.player) > 21:
54
+ # 爆牌 (Bust)
55
+ done = True
56
+ reward = -1.0
57
+ info["success"] = False
58
+ # 爆牌时,render需要知道游戏结束,不再请求动作
59
+ next_obs = self.render(done=True, result_msg="You Busted! (Sum > 21)")
60
+ return next_obs, reward, done, info
61
+
62
+ # 继续游戏
63
+ next_obs = self.render(done=False)
64
+ return next_obs, 0.0, False, info
65
+
66
+ else: # Stick
67
+ # Dealer policy: hit to 17 or more
68
+ while hand_sum(self.dealer) < 17:
69
+ self.dealer.append(draw_card(self.rng))
70
+
71
+ reward = self._settle()
72
+ done = True
73
+ info["success"] = reward > 0
74
+
75
+ # 生成结算信息
76
+ if reward > 0: res = "You Won!"
77
+ elif reward < 0: res = "You Lost."
78
+ else: res = "Draw."
79
+
80
+ next_obs = self.render(done=True, result_msg=res)
81
+ return next_obs, float(reward), done, info
82
+
83
+ def _settle(self) -> float:
84
+ p = hand_sum(self.player)
85
+ d = hand_sum(self.dealer)
86
+ if p > 21: return -1.0
87
+ if d > 21: return 1.0
88
+ if p > d: return 1.0
89
+ if p < d: return -1.0
90
+ return 0.0
91
+
92
+ def render(self, mode: str | None = None, done: bool = False, result_msg: str = "") -> str:
93
+ p_sum = hand_sum(self.player)
94
+ ua = usable_ace(self.player)
95
+
96
+ lines = []
97
+ lines.append("=== Blackjack Game State ===")
98
+ lines.append(f"Your Hand: {self.player} (Total: {p_sum}).")
99
+ if ua:
100
+ lines.append("Note: You possess a usable Ace.")
101
+
102
+ if not done:
103
+ # 游戏进行中,只显示庄家的一张牌
104
+ lines.append(f"Dealer's Visible Card: {self.dealer[0]}.")
105
+ lines.append("")
106
+ lines.append("Available Actions:")
107
+ lines.append("- Action 1: Stick (Stop)")
108
+ lines.append("- Action 2: Hit (Add card)")
109
+
110
+ # 增加策略提示,防止起手21点还Hit
111
+ if p_sum == 21:
112
+ lines.append("\nWait! You have 21. It is strongly recommended to Stick (Action 1).")
113
+
114
+ lines.append("\nWhat is your next move?")
115
+ else:
116
+ # 游戏结束,显示全貌
117
+ d_sum = hand_sum(self.dealer)
118
+ lines.append(f"Dealer's Hand: {self.dealer} (Total: {d_sum}).")
119
+ lines.append("")
120
+ lines.append(f"=== Game Over: {result_msg} ===")
121
+ # 此时不再询问 Next move
122
+
123
+ return "\n".join(lines)
124
+
125
+ def close(self):
126
+ pass
127
+
128
+ def get_all_actions(self):
129
+ return list(self.ACTION_LOOKUP.keys())
ragen/env/countdown/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Adapted from the nicely written code from TinyZero and veRL
3
+ We plan to generalize this environment to support any sort of static problem sets
4
+ """
5
+
6
+ from .env import CountdownEnv
7
+ from .config import CountdownEnvConfig
8
+
9
+ __all__ = ["CountdownEnv", "CountdownEnvConfig"]
ragen/env/countdown/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (428 Bytes). View file
 
ragen/env/countdown/__pycache__/config.cpython-310.pyc ADDED
Binary file (630 Bytes). View file
 
ragen/env/countdown/__pycache__/env.cpython-310.pyc ADDED
Binary file (4.07 kB). View file
 
ragen/env/countdown/config.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from ragen.env.base import BaseEnvConfig
3
+ from dataclasses import dataclass
4
+
5
+ @dataclass
6
+ class CountdownEnvConfig:
7
+ train_path: str = "data/countdown/train.parquet"
8
+ max_instances: int = 20000
9
+ render_mode: str = "text"
10
+ score = 1
11
+ format_score = 0.1
ragen/env/countdown/env.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gymnasium as gym
2
+ from ragen.env.base import BaseLanguageBasedEnv
3
+ import datasets
4
+ import re
5
+ import itertools
6
+ from .config import CountdownEnvConfig
7
+
8
+
9
+ def check_format(equation, nums):
10
+ try:
11
+ nums_in_eq = [int(n) for n in re.findall(r'\d+', equation)]
12
+ return sorted(nums_in_eq) == sorted(nums)
13
+ except:
14
+ return False
15
+
16
+ def check_correctness(equation_str, target):
17
+ try:
18
+ result = eval(equation_str, {"__builtins__": None}, {})
19
+ return abs(result - target) < 1e-5
20
+ except:
21
+ return False
22
+
23
+ def has_solution(nums, target):
24
+ """Check if there is a valid equation using each number exactly once."""
25
+ # pad nums all to 4 numbers
26
+ length = 4
27
+ nums = nums + [0] * (length - len(nums))
28
+ # +- num1 +- num2 +- num3 +- num4 = target, try all
29
+ combinations = list(itertools.product([1, -1], repeat=length))
30
+ for combination in combinations:
31
+ if sum(combination[i] * nums[i] for i in range(length)) == target:
32
+ return True
33
+ return False
34
+
35
+
36
+ class CountdownEnv(BaseLanguageBasedEnv, gym.Env):
37
+ def __init__(self, config=None):
38
+ BaseLanguageBasedEnv.__init__(self)
39
+ self.config = config if config is not None else CountdownEnvConfig()
40
+ self.data = self._get_data_from_parquet(self.config.train_path)
41
+ self.index = None
42
+ self.render_cache = None
43
+ self.render_mode = self.config.render_mode
44
+ assert self.render_mode == 'text'
45
+
46
+ def _get_data_from_parquet(self, path):
47
+ df = datasets.load_dataset("parquet", data_files=path)['train'].select(range(self.config.max_instances))
48
+ df = df.filter(lambda x: has_solution(x['nums'], x['target']))
49
+ return df
50
+
51
+ def reset(self, seed=None, mode=None):
52
+ gym.Env.reset(self, seed=seed)
53
+ self.index = seed % len(self.data)
54
+ data = self.data[self.index]
55
+ self.render_cache = f"Target: {data['target']}, nums: {data['nums']}"
56
+ return self.render_cache
57
+
58
+ def step(self, action):
59
+ reward = self.compute_reward(action, self.data[self.index])
60
+ 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}
61
+ self.render_cache = next_obs
62
+ return next_obs, reward, done, info
63
+
64
+ def render(self):
65
+ return self.render_cache
66
+
67
+
68
+
69
+ def compute_reward(self, action, ground_truth):
70
+ """Score the countdown task solution."""
71
+ target = ground_truth['target']
72
+ nums = ground_truth['nums']
73
+ if not check_format(action, nums):
74
+ return 0
75
+ if not check_correctness(action, target):
76
+ return self.config.format_score
77
+ else:
78
+ return self.config.score
79
+
80
+ def close(self):
81
+ pass
82
+
83
+ if __name__ == "__main__":
84
+ def test(path, seed=43):
85
+ config = CountdownEnvConfig(train_path=path)
86
+ env = CountdownEnv(config)
87
+ obs = env.reset(seed=seed)
88
+ problem = env.data[env.index]
89
+ solution = f"- {problem['nums'][0]} + {problem['nums'][1]} + {problem['nums'][2]}"
90
+ _, reward, _, _ = env.step(solution)
91
+ print(f"{obs}\nSolution: {solution}, Reward: {reward}")
92
+
93
+ test("data/countdown/train.parquet")
ragen/env/frozen_lake.png ADDED

Git LFS Details

  • SHA256: af337915f437cc2eb4202b03880c8939bb29391ebc76ba77979e66db669aa5fb
  • Pointer size: 129 Bytes
  • Size of remote file: 6.66 kB
ragen/env/frozen_lake/__init__.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Adapted from the nicely written code from gymnasium.envs.toy_text.frozen_lake.generate_random_map
3
+ Modify it so that the start and end points are random
4
+
5
+ ## Description
6
+ The game starts with the player at random location of the frozen lake grid world with the
7
+ goal located at another random location for the 4x4 environment.
8
+
9
+ ## Action Space
10
+ The action shape is `(1,)` in the range `{0, 3}` indicating
11
+ which direction to move the player.
12
+ NOTE the action space is different from gymnasium.envs.toy_text.frozen_lake.FrozenLakeEnv, start from 1
13
+ - 0: Still
14
+ - 1: Left
15
+ - 2: Down
16
+ - 3: Right
17
+ - 4: Up
18
+
19
+ ## Starting State
20
+ The episode starts with the player at random location
21
+
22
+ ## Rewards
23
+ NOTE added -0.1 as penalty for invalid action
24
+ Reward schedule:
25
+ - Reach goal: +1
26
+ - Reach hole: 0
27
+ - Reach frozen: 0
28
+
29
+ ## Arguments
30
+ `is_slippery`: if action is left and is_slippery is True, then:
31
+ - P(move left)=1/3
32
+ - P(move up)=1/3
33
+ - P(move down)=1/3
34
+
35
+ ## Example
36
+ P _ _ _
37
+ _ _ _ O
38
+ O _ O _
39
+ O _ _ G
40
+ """
41
+
42
+ from .env import FrozenLakeEnv
43
+ from .config import FrozenLakeEnvConfig
44
+
45
+ __all__ = ["FrozenLakeEnv", "FrozenLakeEnvConfig"]
ragen/env/frozen_lake/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.28 kB). View file
 
ragen/env/frozen_lake/__pycache__/config.cpython-310.pyc ADDED
Binary file (2.04 kB). View file
 
ragen/env/frozen_lake/__pycache__/env.cpython-310.pyc ADDED
Binary file (4.76 kB). View file