Harryis commited on
Commit
4c32b9f
·
verified ·
1 Parent(s): aee0ba7

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. README.md +382 -0
  2. cases/suck_moment.txt +66 -0
  3. cleanrl/.dockerignore +10 -0
  4. cleanrl/.gitpod.Dockerfile +20 -0
  5. cleanrl/.gitpod.yml +26 -0
  6. cleanrl/.pre-commit-config.yaml +78 -0
  7. cleanrl/CHANGES_RL_README.md +64 -0
  8. cleanrl/INTEGRATION_SUMMARY.md +186 -0
  9. cleanrl/LICENSE +316 -0
  10. cleanrl/QUICKSTART_ULTRAHORIZON.md +116 -0
  11. cleanrl/README_convert.md +140 -0
  12. cleanrl/ULTRAHORIZON_README.md +164 -0
  13. cleanrl/cleanrl/noisy_dqn_2048_refined.py +806 -0
  14. cleanrl/cleanrl/ppg_procgen.py +480 -0
  15. cleanrl/cleanrl/ppo.py +312 -0
  16. cleanrl/cleanrl/ppo_2048.py +514 -0
  17. cleanrl/cleanrl/ppo_atari.py +329 -0
  18. cleanrl/cleanrl/ppo_atari_envpool.py +344 -0
  19. cleanrl/cleanrl/ppo_atari_envpool_xla_jax.py +452 -0
  20. cleanrl/cleanrl/ppo_atari_envpool_xla_jax_scan.py +522 -0
  21. cleanrl/cleanrl/ppo_atari_lstm.py +375 -0
  22. cleanrl/cleanrl/ppo_bandit.py +335 -0
  23. cleanrl/cleanrl/ppo_bandit_small.py +343 -0
  24. cleanrl/cleanrl/ppo_blackjack_refine.py +436 -0
  25. cleanrl/cleanrl/ppo_continuous_action.py +353 -0
  26. cleanrl/cleanrl/ppo_rubikscube.py +517 -0
  27. cleanrl/cleanrl/wandb/latest-run/files/code/cleanrl/dqn_bandit.py +344 -0
  28. cleanrl/cleanrl/wandb/latest-run/files/config.yaml +145 -0
  29. cleanrl/cleanrl/wandb/latest-run/files/output.log +49 -0
  30. cleanrl/cleanrl/wandb/latest-run/files/requirements.txt +304 -0
  31. cleanrl/cleanrl/wandb/latest-run/files/wandb-metadata.json +94 -0
  32. cleanrl/cleanrl/wandb/latest-run/files/wandb-summary.json +1 -0
  33. cleanrl/cleanrl/wandb/latest-run/logs/debug-internal.log +15 -0
  34. cleanrl/cleanrl/wandb/latest-run/logs/debug.log +388 -0
  35. cleanrl/cleanrl/wandb/latest-run/run-g1edw7ov.wandb +0 -0
  36. cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/files/code/cleanrl/ppo_bandit.py +335 -0
  37. cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/files/config.yaml +153 -0
  38. cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/files/output.log +61 -0
  39. cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/files/requirements.txt +305 -0
  40. cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/files/wandb-metadata.json +94 -0
  41. cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/files/wandb-summary.json +1 -0
  42. cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/logs/debug.log +24 -0
  43. cleanrl/cleanrl/wandb/run-20251107_100911-8xuf7idy/files/output.log +610 -0
  44. cleanrl/cleanrl/wandb/run-20251107_100911-8xuf7idy/files/requirements.txt +305 -0
  45. cleanrl/cleanrl/wandb/run-20251107_100911-8xuf7idy/logs/debug-internal.log +237 -0
  46. cleanrl/convert_test_results.py +275 -0
  47. cleanrl/entrypoint.sh +6 -0
  48. cleanrl/mkdocs.yml +120 -0
  49. cleanrl/ultrahorizon_gym_wrapper.py +200 -0
  50. train_starpo-s_qwen7B_frommlp_326.sh +172 -0
README.md ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <h1 align="center"> RAGEN: Training Agents by Reinforcing Reasoning </h1>
2
+
3
+
4
+ <p align="center"><img src="public/ragen_logo.jpeg" width="300px" alt="RAGEN icon" /></p>
5
+
6
+
7
+
8
+ <p align="center" style="font-size: 18px;">
9
+ <strong>RAGEN</strong> (<b>R</b>easoning <b>AGEN</b>t, pronounced like "region") leverages reinforcement learning (RL) to train <br>
10
+ <strong>LLM reasoning agents</strong> in interactive, stochastic environments.<br>
11
+ <em>We strongly believe in the future of RL + LLM + Agents. The release is a minimally viable leap forward.</em>
12
+ </p>
13
+
14
+
15
+ <p align="center">
16
+ <a href="https://ragen-ai.github.io/"><img src="https://img.shields.io/badge/📝_HomePage-FF5722?style=for-the-badge&logoColor=white" alt="Blog"></a>
17
+ <a href="https://arxiv.org/abs/2504.20073"><img src="https://img.shields.io/badge/📄_Paper-EA4335?style=for-the-badge&logoColor=white" alt="Paper"></a>
18
+ <a href="https://ragen-doc.readthedocs.io/"><img src="https://img.shields.io/badge/📚_Documentation-4285F4?style=for-the-badge&logoColor=white" alt="Documentation"></a>
19
+ <a href="https://x.com/wzihanw/status/1915052871474712858"><img src="https://img.shields.io/badge/🔍_Post-34A853?style=for-the-badge&logoColor=white" alt="Post"></a>
20
+ <a href="https://api.wandb.ai/links/zihanwang-ai-northwestern-university/a8er8l7b"><img src="https://img.shields.io/badge/🧪_Experiment_Log-AB47BC?style=for-the-badge&logoColor=white" alt="Experiment Log"></a>
21
+
22
+ </p>
23
+
24
+ **2025.5.8 Update:**
25
+ We now release the official [Documentation](https://ragen-doc.readthedocs.io/) for RAGEN. The documentation will be continuously updated and improved to provide a comprehensive and up-to-date guidance.
26
+
27
+ **2025.5.2 Update:**
28
+ We now release a [tracking document](https://docs.google.com/document/d/1bg7obeiKTExuHHBl5uOiSpec5uLDZ2Tgvxy6li5pHX4/edit?usp=sharing) to log minor updates in the RAGEN codebase.
29
+
30
+
31
+ **2025.4.20 Update:**
32
+
33
+ Our RAGEN [paper](https://arxiv.org/abs/2504.20073) is out!
34
+
35
+ We've further streamlined the RAGEN codebase (v0423) to improve development.
36
+ 1. Architecture: Restructured veRL as a submodule for better co-development
37
+ 2. Modularity: Divided RAGEN into three components—Environment Manager, Context Manager, and Agent Proxy, making it significantly simpler to add new environments (details below), track environmental dynamics, and run multiple experiments
38
+
39
+
40
+ **2025.4.16 Update:**
41
+
42
+ We recently noticed that a [third-party website](https://ragen-ai.com) has been created using our project's name and content. While we appreciate the interest in the project, we'd like to clarify that this GitHub repository is the official and primary source for all code, updates, and documentation.
43
+ If we launch an official website in the future, it will be explicitly linked here.
44
+
45
+ Thank you for your support and understanding!
46
+
47
+
48
+ **2025.3.13 Update:**
49
+
50
+
51
+ We are recently refactoring RAGEN code to help you better develop your own idea on the codebase. Please checkout our [developing branch](https://github.com/ZihanWang314/RAGEN/tree/main-new). The first version decomposes RAGEN and veRL for better co-development, taking the latter as a submodule rather than a static directory.
52
+
53
+ **2025.3.8 Update:**
54
+
55
+ 1. In previous veRL implementation, there is a [KL term issue](https://github.com/volcengine/verl/pull/179/files), which has been fixed in recent versions.
56
+ 2. We find evidence from multiple sources that PPO could be more stable than GRPO training in [Open-Reasoner-Zero](https://x.com/rosstaylor90/status/1892664646890312125), [TinyZero](https://github.com/Jiayi-Pan/TinyZero), and [Zhihu](https://www.zhihu.com/search?type=content&q=%E6%97%A0%E5%81%8FGRPO). We have changed the default advantage estimator to GAE (using PPO) and aim to find more stable while efficient RL optimization methods in later versions.
57
+
58
+ **2025.1.27:**
59
+
60
+ We are thrilled to release RAGEN! Check out our post [here](https://x.com/wzihanw/status/1884092805598826609).
61
+
62
+
63
+ ## Overview
64
+
65
+ <!--
66
+ Reinforcement Learning (RL) with rule-based rewards has shown promise in enhancing reasoning capabilities of large language models (LLMs). However, existing approaches have primarily focused on static, single-turn tasks like math reasoning and coding. Extending these methods to agent scenarios introduces two fundamental challenges:
67
+
68
+ 1. **Multi-turn Interactions**: Agents must perform sequential decision-making and react to environment feedback
69
+ 2. **Stochastic Environments**: Uncertainty where identical actions can lead to different outcomes
70
+
71
+ RAGEN addresses these challenges through:
72
+ - A Markov Decision Process (MDP) formulation for agent tasks
73
+ - State-Thinking-Actions-Reward Policy Optimization (StarPO) algorithm that optimizes entire trajectory distributions
74
+ - Progressive reward normalization strategies to handle diverse, complex environments
75
+ -->
76
+
77
+ Reinforcement Learning (RL) with rule-based rewards has shown promise in enhancing reasoning capabilities of large language models (LLMs). However, existing approaches have primarily focused on static, single-turn tasks like math reasoning and coding. Extending these methods to agent scenarios introduces two fundamental challenges:
78
+
79
+ 1. **Multi-turn Interactions**: Agents must perform sequential decision-making and react to environment feedback
80
+ 2. **Stochastic Environments**: Uncertainty where identical actions can lead to different outcomes
81
+
82
+ To address these challenges, we propose a general RL framework: **StarPO** (**S**tate-**T**hinking-**A**ctions-**R**eward **P**olicy **O**ptimization), a comprehensive RL framework that provides a unified approach for training multi-turn, trajectory-level agents with flexible control over reasoning processes, reward assignment mechanisms, and prompt-rollout structures.
83
+ Building upon StarPO, we introduce **RAGEN**, a modular agent training and evaluation system that implements the complete training loop, including rollout generation, reward calculation, and trajectory optimization. RAGEN serves as a robust research infrastructure for systematically analyzing LLM agent training dynamics in multi-turn and stochastic environments.
84
+
85
+ ## Algorithm
86
+
87
+ RAGEN introduces a reinforcement learning framework to train reasoning-capable LLM agents that can operate in interactive, stochastic environments.
88
+
89
+ <p align="center"><img src="public/starpo_logo.png" width="800px" alt="StarPO Framework" /></p>
90
+ <p align="center" style="font-size: 16px; max-width: 800px; margin: 0 auto;">
91
+ The StarPO (State-Thinking-Action-Reward Policy Optimization) framework with two interleaved stages: <b>rollout stage</b> and <b>update stage</b>. LLM iteratively generates reasoning-guided actions to interact with the environment to obtain trajectory-level rewards for LLM update to jointly optimize reasoning and action strategies.
92
+ </p>
93
+
94
+ The framework consists of two key components:
95
+
96
+ ### > MDP Formulation
97
+ We formulate agent-environment interactions as Markov Decision Processes (MDPs) where states and actions are token sequences, allowing LLMs to reason over environment dynamics. At time t, state $s_t$ transitions to the next state through action $a_t$ following a transition function. The policy generates actions given the trajectory history. The objective is to maximize expected cumulative rewards across multiple interaction turns.
98
+
99
+ ### > StarPO: Reinforcing Reasoning via Trajectory-Level Optimization
100
+ StarPO is a general RL framework for optimizing entire multi-turn interaction trajectories for LLM agents.
101
+ The algorithm alternates between two phases:
102
+
103
+ #### Rollout Stage: Reasoning-Interaction Trajectories
104
+ Given an initial state, the LLM generates multiple trajectories. At each step, the model receives the trajectory history and generates a reasoning-guided action: `<think>...</think><ans> action </ans>`. The environment receives the action and returns feedback (reward and next state).
105
+
106
+ #### Update Stage: Multi-turn Trajectory Optimization
107
+ After generating trajectories, we train LLMs to optimize expected rewards. Instead of step-by-step optimization, StarPO optimizes entire trajectories using importance sampling. This approach enables long-horizon reasoning while maintaining computational efficiency.
108
+ StarPO supports multiple optimization strategies:
109
+ - PPO: We estimate token-level advantages using a value function over trajectories
110
+ - GRPO: We assign normalized reward to the full trajectory
111
+
112
+ Rollout and update stages interleave in StarPO, enabling both online and offline learning.
113
+
114
+ <!--
115
+ ### > Reward Normalization Strategies
116
+ We implement three progressive normalization strategies to stabilize training:
117
+ 1. **ARPO**: Preserves raw rewards directly
118
+ 2. **BRPO**: Normalizes rewards across each training batch using batch statistics
119
+ 3. **GRPO**: Normalizes within prompt groups to balance learning across varying task difficulties
120
+ -->
121
+
122
+ ## Environment Setup
123
+ For detailed setup instructions, please check our [documentation](https://ragen-doc.readthedocs.io/). Here's a quick start guide:
124
+
125
+ ```bash
126
+ # Setup environment for RAGEN
127
+ bash scripts/setup_ragen.sh
128
+ ```
129
+
130
+ If this fails, you can follow the manual setup instructions in `scripts/setup_ragen.md`.
131
+
132
+ ## Training Models
133
+ Here's how to train models with RAGEN:
134
+
135
+ ### Export variables and train
136
+ We provide default configuration in `config/base.yaml`. This file includes symbolic links to:
137
+ - `config/ppo_trainer.yaml`
138
+ - `config/envs.yaml`
139
+
140
+ The base configuration automatically inherits all contents from these two config files, creating a unified configuration system.
141
+
142
+ To train:
143
+
144
+ ```bash
145
+ python train.py --config-name base
146
+ ```
147
+
148
+
149
+ ### Parameter efficient training with LoRA
150
+
151
+ ### Saving compute
152
+ By default our code is runnable on A100 80GB machines. If you are using machine with lower memory (e.g. RTX 4090), please consider adapting below parameters, like follows (performance might change due to smaller batch size and shorter context length):
153
+ ```bash
154
+ python train.py \
155
+ micro_batch_size_per_gpu=1 \
156
+ ppo_mini_batch_size=8 \
157
+ actor_rollout_ref.rollout.max_model_len=2048 \
158
+ actor_rollout_ref.rollout.response_length=128
159
+ ```
160
+
161
+ #### Parameter efficient training with LoRA
162
+ We provide a default configuration with LoRA enabled in `config/base-lora.yaml`. To customize the LoRA settings, see the the `lora` section at the top of the configuration file. The current settings are:
163
+
164
+ ```yaml
165
+ lora rank: 64
166
+ lora alpha: 64
167
+ actor learning rate: 1e-5
168
+ critic learning rate: 1e-4
169
+ ```
170
+
171
+ <!--
172
+ ## Supervised Finetuning (Optional)
173
+ For supervised finetuning with LoRA:
174
+
175
+ 1. Create supervised finetuning data:
176
+ ```bash
177
+ bash sft/generate_data.sh <env_type>
178
+ ```
179
+
180
+ 2. Finetune the model:
181
+ ```bash
182
+ bash sft/finetune_lora.sh <env_type> <num_gpus> <save_path>
183
+ ```
184
+
185
+ 3. Merge LoRA weights with the base model:
186
+ ```bash
187
+ python sft/utils/merge_lora.py \
188
+ --base_model_name <base_model_name> \
189
+ --lora_model_path <lora_model_path> \
190
+ --output_path <output_path>
191
+ ```
192
+ -->
193
+
194
+ ## Visualization
195
+ Please check the `val/generations` metric in your wandb dashboard to see the trajectories generated by the model throughout training. Check this [relevant issue](https://github.com/RAGEN-AI/RAGEN/issues/84) for more information.
196
+
197
+
198
+ ## Performance
199
+
200
+ We evaluate RAGEN across multiple environments. Below are results Qwen-2.5-0.5B-Instruct on Sokoban, Frozenlake, and Bandit.
201
+ - No KL loss or KL penalty was applied during training
202
+ - We selectively retained only the top 25% of trajectories that successfully completed their respective tasks
203
+
204
+ <p align="center" style="display: flex; justify-content: center; align-items: center; flex-direction: column; gap: 20px; max-width: 500px; margin: 0 auto;">
205
+ <img src="public/exp1.png" width="250px" alt="Bandit" />
206
+ <img src="public/exp2.png" width="250px" alt="Simple Sokoban" />
207
+ <img src="public/exp3.png" width="250px" alt="Frozen lake" />
208
+ </p>
209
+
210
+ We demonstrate RAGEN's robust generalization ability by training on simple Sokoban environments (6×6 with 1 box) and successfully evaluating performance on:
211
+ - Larger Sokoban environments (8×8 with 2 boxes)
212
+ - Simple Sokoban with alternative grid vocabulary representations
213
+ - FrozenLake environments
214
+
215
+ <p align="center" style="display: flex; justify-content: center; align-items: center; flex-direction: column; gap: 20px; max-width: 500px; margin: 0 auto;">
216
+ <img src="public/exp4.png" width="250px" alt="Larger Sokoban" />
217
+ <img src="public/exp5.png" width="250px" alt="Sokoban with Different Grid Vocabulary" />
218
+ <img src="public/exp6.png" width="250px" alt="Frozen lake" />
219
+ </p>
220
+
221
+ Key observations:
222
+ - By using no KL and filtering out failed trajectories, we can achieve better and stable performance
223
+ - Generalization results highlight RAGEN's capacity to transfer learned policies across varying environment complexities, representations, and domains.
224
+
225
+ ## Evaluation
226
+ RAGEN provides a easy way to evaluate a model:
227
+ ```bash
228
+ python -m ragen.llm_agent.agent_proxy --config-name <eval_config>
229
+ ```
230
+ The proxy now loads `config/eval.yaml` by default, which only keeps the rollout-specific knobs required for evaluation. You can still point to any other file via `--config-name`. Each evaluation config supports an `output` block so you can control where rollouts are stored and which fields are persisted:
231
+
232
+ ```yaml
233
+ output:
234
+ dir: results/eval
235
+ filename: val_rollouts.pkl
236
+ append_timestamp: true # include run timestamp in the file name
237
+ keep_batch_keys: ["rm_scores", "responses"] # set to null to keep everything
238
+ keep_non_tensor_keys: null
239
+ keep_meta_info: true
240
+ ```
241
+
242
+ With this configuration the proxy filters the `DataProto` before saving (handy if you want to drop large tensors such as log-probs) and places the artifact directly under `results/eval`.
243
+ You only need to set model and environment to evaluate in `config/<eval_config>.yaml`.
244
+ To limit how many previous turns the model sees during evaluation, you can set `agent_proxy.max_context_window` in your config file.
245
+
246
+
247
+ <!--
248
+ ## Example Trajectories
249
+
250
+ Visualization of agent reasoning on the Sokoban task:
251
+
252
+ <p align="center" style="display: flex; justify-content: center; gap: 10px;">
253
+ <img src="./public/step_1.png" width="200px" alt="Step 1" />
254
+ <img src="./public/step_2.png" width="200px" alt="Step 2" />
255
+ </p>
256
+
257
+ The visualizations show how the agent reasons through sequential steps to solve the puzzle.
258
+
259
+ ## Case Studies
260
+ We provide several case studies showing the model's behavior:
261
+ - [Reward hacking](https://github.com/ZihanWang314/agent-r1/blob/main/cases/reward_hacking.txt)
262
+ - [Challenging moments](https://github.com/ZihanWang314/agent-r1/blob/main/cases/suck_moment.txt)
263
+
264
+ More case studies will be added to showcase both successful reasoning patterns and failure modes.
265
+ -->
266
+
267
+ ## Modular System Design of RAGEN
268
+
269
+ We implement RAGEN as a modular system: there are three main modules: **Environment State Manager** (`ragen/llm_agent/es_manager.py`), **Context Manager** (`ragen/llm_agent/ctx_manager.py`), and **Agent Proxy** (`ragen/llm_agent/agent_proxy.py`).
270
+
271
+ - Environment State Manager (**es_manager**):
272
+ - Supports multiple environments (different environments, same environment different seeds, same environment same seed)
273
+ - Training seeds are controlled via `seed.train` in the config. The manager increments this seed each reset so runs are deterministic.
274
+ - Records states of each environment during rollout
275
+ - Processes actions from **ctx_manager**, executes step, and returns action results (observations) to **ctx_manager** in a batch-wise manner
276
+ - Context Manager (**ctx_manager**):
277
+ - Parses raw agent tokens into structured actions for the **es_manager**
278
+ - Formats observation from **es_manager**, parses and formulates them for following rollout of agent.
279
+ - Supports a `max_context_window` hyperparameter, which limits how many previous turns of interaction history are retained in the model’s input.
280
+ - Gathers final rollout trajectories and compiles them into tokens, attention masks, reward scores, and loss masks for llm updating.
281
+ - Agent Proxy (**agent_proxy**): Serves as the interface for executing single or multi-round rollouts
282
+
283
+ ## Adding Custom Environments
284
+
285
+ To add a new environment to our framework:
286
+
287
+ 1. Implement an OpenAI Gym-compatible environment in `ragen/env/new_env/env.py` with these required methods:
288
+ - `step(action)`: Process actions and return next state
289
+ - `reset(seed)`: Initialize environment with new seed
290
+ - `render()`: Return current state observation
291
+ - `close()`: Clean up resources
292
+
293
+ 2. Define environment configuration in `ragen/env/new_env/config.py`
294
+
295
+ 3. Register your environment in `config/envs.yaml`:
296
+ ```yaml
297
+ custom_envs:
298
+ - NewEnvironment # Tag
299
+ - env_type: new_env # Must match environment class name
300
+ - max_actions_per_traj: 50 # Example value
301
+ - env_instruction: "Your environment instructions here"
302
+ - env_config: {} # Configuration options from config.py
303
+ ```
304
+
305
+ 4. Add the environment tag to the `es_manager` section in `config/base.yaml`
306
+
307
+ ## Using RAGEN with dstack
308
+
309
+ [dstackai/dstack](https://github.com/dstackai/dstack) is an open-source container orchestrator that simplifies distributed training across cloud providers and on-premises environments
310
+ without the need to use K8S or Slurm.
311
+
312
+ ### 1. Create fleet
313
+
314
+ Before submitting distributed training jobs, create a `dstack` [fleet](https://dstack.ai/docs/concepts/fleets).
315
+
316
+ ### 2. Run a Ray cluster task
317
+
318
+ Once the fleet is created, define and apply a Ray cluster task:
319
+
320
+ ```shell
321
+ $ dstack apply -f examples/distributed-training/ray-ragen/.dstack.yml
322
+ ```
323
+
324
+ You can find the task configuration example at [`examples/distributed-training/ray-ragen/.dstack.yml`](https://github.com/dstackai/dstack/blob/master/examples/distributed-training/ray-ragen/.dstack.yml).
325
+
326
+ The `dstack apply` command will provision the Ray cluster with all dependencies and forward the Ray dashboard port to `localhost:8265`.
327
+
328
+
329
+ ### 3. Submit a training job
330
+
331
+ Now you can submit a training job locally to the Ray cluster:
332
+
333
+ ```shell
334
+ $ RAY_ADDRESS=http://localhost:8265
335
+ $ ray job submit \
336
+ ...
337
+ ```
338
+
339
+ See the full [RAGEN+Ray example](https://dstack.ai/examples/distributed-training/ray-ragen/).
340
+
341
+ For more details on how `dstack` can be used for distributed training, check out the [Clusters](https://dstack.ai/docs/guides/clusters/) guide.
342
+
343
+ ## Feedback
344
+ We welcome all forms of feedback! Please raise an issue for bugs, questions, or suggestions. This helps our team address common problems efficiently and builds a more productive community.
345
+
346
+ ## Awesome work powered or inspired by RAGEN
347
+ - [ROLL](https://github.com/alibaba/ROLL): An Efficient and User-Friendly Scaling Library for Reinforcement Learning with Large Language Models
348
+ - [VAGEN](https://github.com/RAGEN-AI/VAGEN): Training Visual Agents with multi-turn reinforcement learning
349
+ - [Search-R1](https://github.com/PeterGriffinJin/Search-R1): Train your LLMs to reason and call a search engine with reinforcement learning
350
+ - [ZeroSearch](https://github.com/Alibaba-nlp/ZeroSearch): Incentivize the Search Capability of LLMs without Searching
351
+ - [Agent-R1](https://github.com/0russwest0/Agent-R1): Training Powerful LLM Agents with End-to-End Reinforcement Learning
352
+ - [OpenManus-RL](https://github.com/OpenManus/OpenManus-RL): A live stream development of RL tunning for LLM agents
353
+ - [MetaSpatial](https://github.com/PzySeere/MetaSpatial): Reinforcing 3D Spatial Reasoning in VLMs for the Metaverse
354
+ - [s3](https://github.com/pat-jj/s3): Efficient Yet Effective Search Agent Training via Reinforcement Learning
355
+
356
+
357
+ ## Contributors
358
+
359
+ [**Zihan Wang**\*](https://zihanwang314.github.io/), [**Kangrui Wang**\*](https://jameskrw.github.io/), [**Qineng Wang**\*](https://qinengwang-aiden.github.io/), [**Pingyue Zhang**\*](https://williamzhangsjtu.github.io/), [**Linjie Li**\*](https://scholar.google.com/citations?user=WR875gYAAAAJ&hl=en), [**Zhengyuan Yang**](https://zyang-ur.github.io/), [**Xing Jin**](https://openreview.net/profile?id=~Xing_Jin3), [**Kefan Yu**](https://www.linkedin.com/in/kefan-yu-22723a25b/en/), [**Minh Nhat Nguyen**](https://www.linkedin.com/in/menhguin/?originalSubdomain=sg), [**Licheng Liu**](https://x.com/liulicheng10), [**Eli Gottlieb**](https://www.linkedin.com/in/eli-gottlieb1/), [**Yiping Lu**](https://2prime.github.io), [**Kyunghyun Cho**](https://kyunghyuncho.me/), [**Jiajun Wu**](https://jiajunwu.com/), [**Li Fei-Fei**](https://profiles.stanford.edu/fei-fei-li), [**Lijuan Wang**](https://www.microsoft.com/en-us/research/people/lijuanw/), [**Yejin Choi**](https://homes.cs.washington.edu/~yejin/), [**Manling Li**](https://limanling.github.io/)
360
+
361
+ *:Equal Contribution.
362
+
363
+ ## Acknowledgements
364
+ We thank the [DeepSeek](https://github.com/deepseek-ai/DeepSeek-R1) team for providing the DeepSeek-R1 model and early conceptual inspirations. We are grateful to the [veRL](https://github.com/volcengine/verl) team for their infrastructure support. We thank the [TinyZero](https://github.com/Jiayi-Pan/TinyZero) team for their discoveries that informed our initial exploration. We would like to appreciate insightful discussions with Han Liu, Xinyu Xing, Li Erran Li, John Schulman, Akari Asai, Eiso Kant, Lu Lu, Runxin Xu, Huajian Xin, Zijun Liu, Weiyi Liu, Weimin Wu, Yibo Wen, Jiarui Liu, Lorenzo Xiao, Ishan Mukherjee, Anabella Isaro, Haosen Sun, How-Yeh Wan, Lester Xue, Matthew Khoriaty, Haoxiang Sun, Jiajun Liu.
365
+
366
+ ## Star History
367
+
368
+ [![Star History Chart](https://api.star-history.com/svg?repos=ragen-ai/ragen&type=Date)](https://www.star-history.com/#ragen-ai/ragen&Date)
369
+
370
+ ## Citation
371
+ If you find RAGEN useful, we would appreciate it if you consider citing our work:
372
+ ```md
373
+ @misc{ragen,
374
+ title={RAGEN: Understanding Self-Evolution in LLM Agents via Multi-Turn Reinforcement Learning},
375
+ author={Zihan Wang and Kangrui Wang and Qineng Wang and Pingyue Zhang and Linjie Li and Zhengyuan Yang and Xing Jin and Kefan Yu and Minh Nhat Nguyen and Licheng Liu and Eli Gottlieb and Yiping Lu and Kyunghyun Cho and Jiajun Wu and Li Fei-Fei and Lijuan Wang and Yejin Choi and Manling Li},
376
+ year={2025},
377
+ eprint={2504.20073},
378
+ archivePrefix={arXiv},
379
+ primaryClass={cs.LG},
380
+ url={https://arxiv.org/abs/2504.20073},
381
+ }
382
+ ```
cases/suck_moment.txt ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [Cumulative Observations]:
2
+ # # # # # #
3
+ # _ P # # #
4
+ # _ X # # #
5
+ # _ O _ _ #
6
+ # _ _ _ # #
7
+ # # # # # #
8
+ Decide the next action:
9
+ Always output: <think> [Your thoughts] </think> <answer> [your answer] </answer> with no extra test. Strictly follow this format. <|im_end|>
10
+ <|im_start|>assistant
11
+ <think> I need to move and place boxes to target with optimal solutions first.</th>
12
+ <suck> Let's start by placing the boxes one by one from right to left on all the floor squares. </suck><|im_end|>
13
+ <|im_start|>user
14
+ Action is invalid. You stay in the same position. The observation is:
15
+ # # # # # #
16
+ # _ P # # #
17
+ # _ X # # #
18
+ # _ O _ _ #
19
+ # _ _ _ # #
20
+ # # # # # #
21
+ reward: -0.1
22
+ done: False
23
+ <|im_end|>
24
+ <|im_start|>assistant
25
+ <think> Next, I should place them on the squares that are reserved as targets.</th>
26
+ <suck> Move all boxes with target orientations from left to right. </suck><|im_end|>
27
+ <|im_start|>user
28
+ Action is invalid. You stay in the same position. The observation is:
29
+ # # # # # #
30
+ # _ P # # #
31
+ # _ X # # #
32
+ # _ O _ _ #
33
+ # _ _ _ # #
34
+ # # # # # #
35
+ reward: -0.1
36
+ done: False
37
+ <|im_end|>
38
+ <|im_start|>assistant
39
+ <think> Move all boxes with target orientations from right to left. </th>
40
+ <suck> Choose square with boxes on top as target and move all the manifests. </suck><|im_end|>
41
+ <|im_start|>user
42
+ Action is invalid. You stay in the same position. The observation is:
43
+ # # # # # #
44
+ # _ P # # #
45
+ # _ X # # #
46
+ # _ O _ _ #
47
+ # _ _ _ # #
48
+ # # # # # #
49
+ reward: -0.1
50
+ done: False
51
+ <|im_end|>
52
+ <|im_start|>assistant
53
+ <think> I need to find a way to make the placements. First, I will prioritize boxes with target orientations based on their height.</th>
54
+ <suck> Compute the height of all boxes as status. Then prioritize the upward moves. </suck>
55
+ <suck> For each upward move, use the strategy S which naturally generates the target of the upper one.</suck>
56
+ <suck> But now I just need to move those up as indicated. </suck>
57
+ <suck> Remember to use the<|im_end|>
58
+ <|im_start|>user
59
+ Action is invalid. You stay in the same position. The observation is:
60
+ # # # # # #
61
+ # _ P # # #
62
+ # _ X # # #
63
+ # _ O _ _ #
64
+ # _ _ _ # #
65
+ # # # # # #
66
+ reward: -0.1
cleanrl/.dockerignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ *.mp4
2
+ *.pyc
3
+ *.pyo
4
+ *.log
5
+ *.json
6
+ **/wandb
7
+ **/runs
8
+ **/videos
9
+ .git
10
+ *.tfevents.*
cleanrl/.gitpod.Dockerfile ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM gitpod/workspace-full-vnc:latest
2
+ USER gitpod
3
+ RUN if ! grep -q "export PIP_USER=no" "$HOME/.bashrc"; then printf '%s\n' "export PIP_USER=no" >> "$HOME/.bashrc"; fi
4
+
5
+ # install ubuntu dependencies
6
+ ENV DEBIAN_FRONTEND=noninteractive
7
+ RUN sudo apt-get update && \
8
+ sudo apt-get -y install xvfb ffmpeg git build-essential python-opengl
9
+
10
+ # install python dependencies
11
+ RUN mkdir cleanrl_utils && touch cleanrl_utils/__init__.py
12
+ RUN pip install uv --upgrade
13
+ RUN uv config virtualenvs.in-project true
14
+
15
+ # install mujoco_py
16
+ RUN sudo apt-get -y install wget unzip software-properties-common \
17
+ libgl1-mesa-dev \
18
+ libgl1-mesa-glx \
19
+ libglew-dev \
20
+ libosmesa6-dev patchelf
cleanrl/.gitpod.yml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ image:
2
+ file: .gitpod.Dockerfile
3
+
4
+ tasks:
5
+ - init: uv pip install .
6
+
7
+ # vscode:
8
+ # extensions:
9
+ # - learnpack.learnpack-vscode
10
+
11
+ github:
12
+ prebuilds:
13
+ # enable for the master/default branch (defaults to true)
14
+ master: true
15
+ # enable for all branches in this repo (defaults to false)
16
+ branches: true
17
+ # enable for pull requests coming from this repo (defaults to true)
18
+ pullRequests: true
19
+ # enable for pull requests coming from forks (defaults to false)
20
+ pullRequestsFromForks: true
21
+ # add a "Review in Gitpod" button as a comment to pull requests (defaults to true)
22
+ addComment: false
23
+ # add a "Review in Gitpod" button to pull requests (defaults to false)
24
+ addBadge: false
25
+ # add a label once the prebuild is ready to pull requests (defaults to false)
26
+ addLabel: prebuilt-in-gitpod
cleanrl/.pre-commit-config.yaml ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/asottile/pyupgrade
3
+ rev: v3.20.0
4
+ hooks:
5
+ - id: pyupgrade
6
+ args:
7
+ - --py37-plus
8
+ - repo: https://github.com/PyCQA/isort
9
+ rev: 5.13.2
10
+ hooks:
11
+ - id: isort
12
+ args:
13
+ - --profile=black
14
+ - --skip-glob=wandb/**/*
15
+ - --thirdparty=wandb
16
+ - repo: https://github.com/python/black
17
+ rev: 25.1.0
18
+ hooks:
19
+ - id: black
20
+ args:
21
+ - --line-length=127
22
+ - --exclude=wandb
23
+ - repo: https://github.com/codespell-project/codespell
24
+ rev: v2.4.1
25
+ hooks:
26
+ - id: codespell
27
+ args:
28
+ - --ignore-words-list=nd,reacher,thist,ths,magent,ba,Meger
29
+ - --skip=docs/css/termynal.css,docs/js/termynal.js,docs/get-started/CleanRL_Huggingface_Integration_Demo.ipynb
30
+ - repo: https://github.com/astral-sh/uv-pre-commit
31
+ rev: 0.7.19
32
+ hooks:
33
+ - id: uv-export
34
+ name: uv-export requirements.txt
35
+ args: ["--no-hashes", "--output-file", "requirements/requirements.txt"]
36
+ stages: [manual]
37
+ - id: uv-export
38
+ name: uv-export requirements-atari.txt
39
+ args: ["--no-hashes", "--output-file", "requirements/requirements-atari.txt", "--extra", "atari"]
40
+ stages: [manual]
41
+ - id: uv-export
42
+ name: uv-export requirements-mujoco.txt
43
+ args: ["--no-hashes", "--output-file", "requirements/requirements-mujoco.txt", "--extra", "mujoco"]
44
+ stages: [manual]
45
+ - id: uv-export
46
+ name: uv-export requirements-dm_control.txt
47
+ args: ["--no-hashes", "--output-file", "requirements/requirements-dm_control.txt", "--extra", "dm_control"]
48
+ stages: [manual]
49
+ - id: uv-export
50
+ name: uv-export requirements-procgen.txt
51
+ args: ["--no-hashes", "--output-file", "requirements/requirements-procgen.txt", "--extra", "procgen"]
52
+ stages: [manual]
53
+ - id: uv-export
54
+ name: uv-export requirements-envpool.txt
55
+ args: ["--no-hashes", "--output-file", "requirements/requirements-envpool.txt", "--extra", "envpool"]
56
+ stages: [manual]
57
+ - id: uv-export
58
+ name: uv-export requirements-pettingzoo.txt
59
+ args: ["--no-hashes", "--output-file", "requirements/requirements-pettingzoo.txt", "--extra", "pettingzoo"]
60
+ stages: [manual]
61
+ - id: uv-export
62
+ name: uv-export requirements-jax.txt
63
+ args: ["--no-hashes", "--output-file", "requirements/requirements-jax.txt", "--extra", "jax"]
64
+ stages: [manual]
65
+ - id: uv-export
66
+ name: uv-export requirements-optuna.txt
67
+ args: ["--no-hashes", "--output-file", "requirements/requirements-optuna.txt", "--extra", "optuna"]
68
+ stages: [manual]
69
+ - id: uv-export
70
+ name: uv-export requirements-docs.txt
71
+ args: ["--no-hashes", "--output-file", "requirements/requirements-docs.txt", "--extra", "docs"]
72
+ stages: [manual]
73
+ - id: uv-export
74
+ name: uv-export requirements-cloud.txt
75
+ args: ["--no-hashes", "--output-file", "requirements/requirements-cloud.txt", "--extra", "cloud"]
76
+ stages: [manual]
77
+ # requirements-memory-gym.txt must be hand updated,
78
+ # `cd cleanrl/ppo_trxl`, `uv export --no-hashes --output-file ../../requirements/requirements-memory_gym.txt`
cleanrl/CHANGES_RL_README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Classic RL for RAGEN (DQN/PPO)
2
+
3
+ This note summarizes the changes and how to run the small-MLP RL baselines (DQN/PPO) on RAGEN environments without changing environment internals or interfaces.
4
+
5
+ ## What Changed
6
+
7
+ - Added gymnasium-compatible wrappers that convert text observations into fixed-size numeric vectors purely from observable text, preserving the original env API semantics:
8
+ - `cleanrl/cleanrl/ragen_wrappers.py`
9
+ - `BanditWrapper`: hashes text observation into a small one-hot vector; episodes remain single-step (no custom episode shaping).
10
+ - `FrozenLakeWrapper`: parses the grid from text into one-hot cells + normalized player pos. Shape is inferred by reading the first observable reset; no access to internal config.
11
+ - `SokobanWrapper`: parses the room from text into one-hot cells. Shape is inferred at first observable reset; no access to internal config.
12
+
13
+ - Small-MLP agents using standard RL:
14
+ - `cleanrl/cleanrl/dqn_bandit.py`: DQN for Bandit (discrete, single-step feedback), uses a small MLP and epsilon-greedy with replay + target network.
15
+ - `cleanrl/cleanrl/ppo_frozenlake.py`: PPO for FrozenLake (episodic grid nav, discrete actions), simple MLP actor-critic with GAE.
16
+ - `cleanrl/cleanrl/ppo_sokoban.py`: PPO for Sokoban (grid puzzle, discrete actions), larger MLP actor-critic.
17
+
18
+ These implementations only use the text returned by `reset`/`step` and the reward/done/info. They do not modify wrappers of the environments shipped in `ragen/env/*` nor rely on hidden rules.
19
+
20
+ ## Why These Algorithms
21
+
22
+ - Bandit: DQN fits discrete action selection with value learning and works well with a small feature encoder; PPO is possible but overkill for single-step returns.
23
+ - FrozenLake: PPO handles sparse/delayed rewards with on-policy updates and advantage estimation across rollouts.
24
+ - Sokoban: PPO scales better with longer horizons and stochastic exploration; larger MLP helps with the higher-dimensional state encoding.
25
+
26
+ ## Usage
27
+
28
+ From repo root:
29
+
30
+ - Bandit (DQN):
31
+ - `python cleanrl/cleanrl/dqn_bandit.py --total-timesteps 100000 --seed 1`
32
+
33
+ - FrozenLake (PPO):
34
+ - `python cleanrl/cleanrl/ppo_frozenlake.py --total-timesteps 1000000 --num-envs 8 --grid-size 4 --is-slippery True`
35
+
36
+ - Sokoban (PPO):
37
+ - `python cleanrl/cleanrl/ppo_sokoban.py --total-timesteps 5000000 --num-envs 8 --dim-room "(6, 6)" --num-boxes 1`
38
+
39
+ TensorBoard:
40
+ - `tensorboard --logdir runs/`
41
+
42
+ Optional W&B tracking (all scripts):
43
+ - `--track --wandb-project-name RAGEN-RL --wandb-entity <team>`
44
+
45
+ ## Notes and Assumptions
46
+
47
+ - Action mapping: environments use 1-indexed actions; wrappers map to 0-indexed `Discrete` spaces and back on `step`.
48
+ - Observation sizes are derived from text alone at runtime. We avoid accessing env config objects to respect the “no hidden info” constraint.
49
+ - Vectorized rollout: PPO scripts use `gym.vector.SyncVectorEnv`; DQN runs with a single env for simplicity (can be extended).
50
+ - We keep environment episodes as defined by the original envs. Bandit remains single-step; PPO variants rely on the environment’s termination.
51
+
52
+ ## File Index
53
+
54
+ - Wrappers: `cleanrl/cleanrl/ragen_wrappers.py`
55
+ - DQN (Bandit): `cleanrl/cleanrl/dqn_bandit.py`
56
+ - PPO (FrozenLake): `cleanrl/cleanrl/ppo_frozenlake.py`
57
+ - PPO (Sokoban): `cleanrl/cleanrl/ppo_sokoban.py`
58
+
59
+ ## Next Steps (Optional)
60
+
61
+ - Add simple CNN encoders over 2D grids (FrozenLake/Sokoban) to better capture spatial structure.
62
+ - Support prioritized replay in DQN and double-DQN for Bandit.
63
+ - Curriculum or map randomization sweeps for FrozenLake; tuned entropy schedule for Sokoban.
64
+
cleanrl/INTEGRATION_SUMMARY.md ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ultrahorizon 环境集成总结
2
+
3
+ ## 🎯 任务目标
4
+
5
+ **纯粹的 RL 高分任务**:训练智能体在 Ultrahorizon 网格环境中获得最高分数,而不需要理解或推理世界规则。
6
+
7
+ ## 📊 环境特性
8
+
9
+ ### 观测空间(全局观测)
10
+ - **维度**: 605维特征向量
11
+ - **组成**:
12
+ - 位置 (2): 当前 x, y 坐标归一化
13
+ - 能量 (1): 当前能量/20
14
+ - 分数 (1): 当前分数(可为负)
15
+ - 步数 (1): 当前步数/30
16
+ - **完整网格状态 (600)**: 10×10 网格的全局观测,每个格子 one-hot 编码 (A-E, X)
17
+
18
+ ### 动作空间
19
+ - **4个离散动作**: 上(0), 下(1), 左(2), 右(3)
20
+
21
+ ### Episode 特性
22
+ - **长度**: 20-30 步
23
+ - 最小: 20步(能量耗尽,每步消耗1能量,初始20能量)
24
+ - 最大: 30步(达到最大步数限制)
25
+ - **终止条件**:
26
+ 1. 能量耗尽 (energy = 0)
27
+ 2. 达到最大步数 (steps = 30)
28
+ 3. 无效移动(出界或已终止)
29
+
30
+ ### 奖励设计
31
+ - **成功移动**: reward = 当前分数 - 上一步分数(分数变化)
32
+ - **无效移动**: reward = -10(重罚,避免浪费步数)
33
+ - **目标**: 最大化累积奖励 = 最大化最终分数
34
+
35
+ ## 🔑 关键设计决策
36
+
37
+ ### 1. 全局观测 vs 局部观测
38
+ ✅ **使用全局观测**
39
+ - 智能体可以看到整个 10×10 网格
40
+ - 有利于规划最优路径
41
+ - 符合环境允许全局观测的特性
42
+
43
+ ### 2. 奖励函数
44
+ ✅ **分数变化作为奖励**
45
+ - 直接优化目标:最大化分数
46
+ - 不需要理解字母效果的内在规则
47
+ - 智能体通过试错学习哪些移动能获得高分
48
+
49
+ ### 3. Episode 长度处理
50
+ ✅ **自然终止**
51
+ - 不使用固定长度截断
52
+ - 让环境自然终止(能量或步数)
53
+ - Episode 长度在 20-30 步之间变化
54
+
55
+ ## 📁 文件结构
56
+
57
+ ```
58
+ cleanrl/
59
+ ├── envs/
60
+ │ ├── __init__.py
61
+ │ └── common.py # Difficulty 枚举
62
+ ├── Ultrahorizon_grid_env.py # 原始环境
63
+ ├── ultrahorizon_gym_wrapper.py # Gymnasium 包装器
64
+ ├── cleanrl/
65
+ │ ├── ppo_atari.py # 原始 PPO
66
+ │ └── ppo_ultrahorizon.py # 适配的 PPO
67
+ └── INTEGRATION_SUMMARY.md # 本文件
68
+ ```
69
+
70
+ ## 🚀 使用方法
71
+
72
+ ### 快速开始
73
+ ```bash
74
+ cd /Users/harryis/why_code/ICML_Memory/cleanrl
75
+ python cleanrl/ppo_ultrahorizon.py --difficulty EASY
76
+ ```
77
+
78
+ ### 推荐配置
79
+
80
+ #### EASY 难度
81
+ ```bash
82
+ python cleanrl/ppo_ultrahorizon.py \
83
+ --difficulty EASY \
84
+ --num-envs 8 \
85
+ --total-timesteps 500000 \
86
+ --learning-rate 3e-4
87
+ ```
88
+
89
+ #### HARD 难度
90
+ ```bash
91
+ python cleanrl/ppo_ultrahorizon.py \
92
+ --difficulty HARD \
93
+ --num-envs 8 \
94
+ --total-timesteps 1000000 \
95
+ --learning-rate 2.5e-4
96
+ ```
97
+
98
+ ## 🧠 神经网络架构
99
+
100
+ ```
101
+ 输入: 605维观测向量
102
+
103
+ Linear(605 → 256) + ReLU
104
+
105
+ Linear(256 → 256) + ReLU
106
+
107
+ Linear(256 → 128) + ReLU
108
+
109
+ ├─→ Actor: Linear(128 → 4) # 策略网络
110
+ └─→ Critic: Linear(128 → 1) # 价值网络
111
+ ```
112
+
113
+ ## 📈 预期行为
114
+
115
+ ### 学习过程
116
+ 1. **初期**: 随机探索,学习避免无效移动
117
+ 2. **中期**: 学习哪些字母倾向于给正分,哪些给负分
118
+ 3. **后期**: 优化路径,最大化累积分数
119
+
120
+ ### 性能指标
121
+ - **Episode Return**: 累积奖励(应逐渐增加)
122
+ - **Episode Length**: 20-30 步(受能量限制)
123
+ - **Policy Loss**: 策略梯度损失
124
+ - **Value Loss**: 价值函数损失
125
+
126
+ ## ⚙️ 超参数建议
127
+
128
+ | 参数 | EASY | MEDIUM | HARD |
129
+ |------|------|--------|------|
130
+ | learning_rate | 3e-4 | 2.5e-4 | 2.5e-4 |
131
+ | num_envs | 8 | 8 | 8 |
132
+ | total_timesteps | 500K | 750K | 1M |
133
+ | num_steps | 128 | 128 | 128 |
134
+ | ent_coef | 0.01 | 0.01 | 0.005 |
135
+
136
+ ## 🔍 调试建议
137
+
138
+ ### 检查学习是否正常
139
+ ```python
140
+ # 查看 episode return 是否增长
141
+ tensorboard --logdir runs/
142
+
143
+ # 关注指标:
144
+ # - charts/episodic_return (应该上升)
145
+ # - charts/episodic_length (应该在 20-30 之间)
146
+ # - losses/entropy (初期高,后期降低)
147
+ ```
148
+
149
+ ### 常见问题
150
+
151
+ **Q: Episode return 不增长?**
152
+ - 检查学习率是否过大或过小
153
+ - 增加探索(提高 ent_coef)
154
+ - 确保奖励信号正确(检查分数变化)
155
+
156
+ **Q: Episode 过早终止?**
157
+ - 检查是否频繁触发无效移动
158
+ - 可能需要调整网络架构或学习率
159
+
160
+ **Q: 训练不稳定?**
161
+ - 降低学习率
162
+ - 增加 num_envs 以稳定梯度
163
+ - 检查奖励尺度是否合理
164
+
165
+ ## 🎓 与原始 PPO Atari 的对比
166
+
167
+ | 特性 | PPO Atari | PPO Ultrahorizon |
168
+ |------|-----------|------------------|
169
+ | **任务类型** | 视觉游戏 | 网格探索 |
170
+ | **观测** | 84×84×4 图像 | 605维特征向量 |
171
+ | **观测范围** | 屏幕内容 | **全局网格** |
172
+ | **网络** | CNN | MLP |
173
+ | **Episode长度** | 变化大 | **固定20-30步** |
174
+ | **奖励** | 游戏分数 | **分数变化** |
175
+ | **目标** | 玩游戏 | **纯粹高分** |
176
+
177
+ ## ✅ 核心 PPO 算法保持不变
178
+
179
+ - GAE (Generalized Advantage Estimation)
180
+ - Clipped Surrogate Objective
181
+ - Value Function Clipping
182
+ - Entropy Regularization
183
+ - Learning Rate Annealing
184
+ - Advantage Normalization
185
+
186
+ 所有这些标准 PPO 组件都完整保留,只是适配了不同的环境接口。
cleanrl/LICENSE ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2019 CleanRL developers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+
24
+ --------------------------------------------------------------------------------
25
+
26
+ Code in `cleanrl/ppo_procgen.py` and `cleanrl/ppg_procgen.py` are adapted from https://github.com/AIcrowd/neurips2020-procgen-starter-kit/blob/142d09586d2272a17f44481a115c4bd817cf6a94/models/impala_cnn_torch.py
27
+
28
+ **NOTE: the original repo did not fill out the copyright section in their license
29
+ so the following copyright notice is copied as is per the license requirement.
30
+ See https://github.com/AIcrowd/neurips2020-procgen-starter-kit/blob/142d09586d2272a17f44481a115c4bd817cf6a94/LICENSE#L190
31
+
32
+
33
+ Copyright [yyyy] [name of copyright owner]
34
+
35
+ Licensed under the Apache License, Version 2.0 (the "License");
36
+ you may not use this file except in compliance with the License.
37
+ You may obtain a copy of the License at
38
+
39
+ http://www.apache.org/licenses/LICENSE-2.0
40
+
41
+ Unless required by applicable law or agreed to in writing, software
42
+ distributed under the License is distributed on an "AS IS" BASIS,
43
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
44
+ See the License for the specific language governing permissions and
45
+ limitations under the License.
46
+
47
+ --------------------------------------------------------------------------------
48
+ Code in `cleanrl/ddpg_continuous_action.py` and `cleanrl/td3_continuous_action.py` are adapted from https://github.com/sfujim/TD3
49
+
50
+
51
+ MIT License
52
+
53
+ Copyright (c) 2020 Scott Fujimoto
54
+
55
+ Permission is hereby granted, free of charge, to any person obtaining a copy
56
+ of this software and associated documentation files (the "Software"), to deal
57
+ in the Software without restriction, including without limitation the rights
58
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
59
+ copies of the Software, and to permit persons to whom the Software is
60
+ furnished to do so, subject to the following conditions:
61
+
62
+ The above copyright notice and this permission notice shall be included in all
63
+ copies or substantial portions of the Software.
64
+
65
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
66
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
67
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
68
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
69
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
70
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
71
+ SOFTWARE.
72
+
73
+ --------------------------------------------------------------------------------
74
+ Code in `cleanrl/sac_continuous_action.py` is inspired and adapted from [haarnoja/sac](https://github.com/haarnoja/sac), [openai/spinningup](https://github.com/openai/spinningup), [pranz24/pytorch-soft-actor-critic](https://github.com/pranz24/pytorch-soft-actor-critic), [DLR-RM/stable-baselines3](https://github.com/DLR-RM/stable-baselines3), and [denisyarats/pytorch_sac](https://github.com/denisyarats/pytorch_sac).
75
+
76
+ - [haarnoja/sac](https://github.com/haarnoja/sac/blob/8258e33633c7e37833cc39315891e77adfbe14b2/LICENSE.txt)
77
+
78
+ COPYRIGHT
79
+
80
+ All contributions by the University of California:
81
+ Copyright (c) 2017, 2018 The Regents of the University of California (Regents)
82
+ All rights reserved.
83
+
84
+ All other contributions:
85
+ Copyright (c) 2017, 2018, the respective contributors
86
+ All rights reserved.
87
+
88
+ SAC uses a shared copyright model: each contributor holds copyright over
89
+ their contributions to the SAC codebase. The project versioning records all such
90
+ contribution and copyright details. If a contributor wants to further mark
91
+ their specific copyright on a particular contribution, they should indicate
92
+ their copyright solely in the commit message of the change when it is
93
+ committed.
94
+
95
+ LICENSE
96
+
97
+ Redistribution and use in source and binary forms, with or without
98
+ modification, are permitted provided that the following conditions are met:
99
+
100
+ 1. Redistributions of source code must retain the above copyright notice, this
101
+ list of conditions and the following disclaimer.
102
+ 2. Redistributions in binary form must reproduce the above copyright notice,
103
+ this list of conditions and the following disclaimer in the documentation
104
+ and/or other materials provided with the distribution.
105
+
106
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
107
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
108
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
109
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
110
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
111
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
112
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
113
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
114
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
115
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
116
+
117
+ CONTRIBUTION AGREEMENT
118
+
119
+ By contributing to the SAC repository through pull-request, comment,
120
+ or otherwise, the contributor releases their content to the
121
+ license and copyright terms herein.
122
+
123
+ - [openai/spinningup](https://github.com/openai/spinningup/blob/038665d62d569055401d91856abb287263096178/LICENSE)
124
+
125
+ The MIT License
126
+
127
+ Copyright (c) 2018 OpenAI (http://openai.com)
128
+
129
+ Permission is hereby granted, free of charge, to any person obtaining a copy
130
+ of this software and associated documentation files (the "Software"), to deal
131
+ in the Software without restriction, including without limitation the rights
132
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
133
+ copies of the Software, and to permit persons to whom the Software is
134
+ furnished to do so, subject to the following conditions:
135
+
136
+ The above copyright notice and this permission notice shall be included in
137
+ all copies or substantial portions of the Software.
138
+
139
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
140
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
141
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
142
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
143
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
144
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
145
+ THE SOFTWARE.
146
+
147
+ - [DLR-RM/stable-baselines3](https://github.com/DLR-RM/stable-baselines3/blob/44e53ff8115e8f4bff1d5218f10c8c7d1a4cfc12/LICENSE)
148
+
149
+ The MIT License
150
+
151
+ Copyright (c) 2019 Antonin Raffin
152
+
153
+ Permission is hereby granted, free of charge, to any person obtaining a copy
154
+ of this software and associated documentation files (the "Software"), to deal
155
+ in the Software without restriction, including without limitation the rights
156
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
157
+ copies of the Software, and to permit persons to whom the Software is
158
+ furnished to do so, subject to the following conditions:
159
+
160
+ The above copyright notice and this permission notice shall be included in
161
+ all copies or substantial portions of the Software.
162
+
163
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
164
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
165
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
166
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
167
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
168
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
169
+ THE SOFTWARE.
170
+
171
+ - [denisyarats/pytorch_sac](https://github.com/denisyarats/pytorch_sac/blob/81c5b536d3a1c5616b2531e446450df412a064fb/LICENSE)
172
+
173
+ MIT License
174
+
175
+ Copyright (c) 2019 Denis Yarats
176
+
177
+ Permission is hereby granted, free of charge, to any person obtaining a copy
178
+ of this software and associated documentation files (the "Software"), to deal
179
+ in the Software without restriction, including without limitation the rights
180
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
181
+ copies of the Software, and to permit persons to whom the Software is
182
+ furnished to do so, subject to the following conditions:
183
+
184
+ The above copyright notice and this permission notice shall be included in all
185
+ copies or substantial portions of the Software.
186
+
187
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
188
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
189
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
190
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
191
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
192
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
193
+ SOFTWARE.
194
+
195
+ - [pranz24/pytorch-soft-actor-critic](https://github.com/pranz24/pytorch-soft-actor-critic/blob/master/LICENSE)
196
+
197
+ MIT License
198
+
199
+ Copyright (c) 2018 Pranjal Tandon
200
+
201
+ Permission is hereby granted, free of charge, to any person obtaining a copy
202
+ of this software and associated documentation files (the "Software"), to deal
203
+ in the Software without restriction, including without limitation the rights
204
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
205
+ copies of the Software, and to permit persons to whom the Software is
206
+ furnished to do so, subject to the following conditions:
207
+
208
+ The above copyright notice and this permission notice shall be included in all
209
+ copies or substantial portions of the Software.
210
+
211
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
212
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
213
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
214
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
215
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
216
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
217
+ SOFTWARE.
218
+
219
+
220
+ ---------------------------------------------------------------------------------
221
+ The CONTRIBUTING.md is adopted from https://github.com/entity-neural-network/incubator/blob/2a0c38b30828df78c47b0318c76a4905020618dd/CONTRIBUTING.md
222
+ and https://github.com/Stable-Baselines-Team/stable-baselines3-contrib/blob/master/CONTRIBUTING.md
223
+
224
+ MIT License
225
+
226
+ Copyright (c) 2021 Entity Neural Network developers
227
+
228
+ Permission is hereby granted, free of charge, to any person obtaining a copy
229
+ of this software and associated documentation files (the "Software"), to deal
230
+ in the Software without restriction, including without limitation the rights
231
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
232
+ copies of the Software, and to permit persons to whom the Software is
233
+ furnished to do so, subject to the following conditions:
234
+
235
+ The above copyright notice and this permission notice shall be included in all
236
+ copies or substantial portions of the Software.
237
+
238
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
239
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
240
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
241
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
242
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
243
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
244
+ SOFTWARE.
245
+
246
+
247
+
248
+ MIT License
249
+
250
+ Copyright (c) 2020 Stable-Baselines Team
251
+
252
+ Permission is hereby granted, free of charge, to any person obtaining a copy
253
+ of this software and associated documentation files (the "Software"), to deal
254
+ in the Software without restriction, including without limitation the rights
255
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
256
+ copies of the Software, and to permit persons to whom the Software is
257
+ furnished to do so, subject to the following conditions:
258
+
259
+ The above copyright notice and this permission notice shall be included in all
260
+ copies or substantial portions of the Software.
261
+
262
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
263
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
264
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
265
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
266
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
267
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
268
+ SOFTWARE.
269
+
270
+
271
+ ---------------------------------------------------------------------------------
272
+ The cleanrl/ppo_continuous_action_isaacgym.py is contributed by Nvidia
273
+
274
+ SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
275
+ SPDX-License-Identifier: MIT
276
+
277
+ Permission is hereby granted, free of charge, to any person obtaining a
278
+ copy of this software and associated documentation files (the "Software"),
279
+ to deal in the Software without restriction, including without limitation
280
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
281
+ and/or sell copies of the Software, and to permit persons to whom the
282
+ Software is furnished to do so, subject to the following conditions:
283
+
284
+ The above copyright notice and this permission notice shall be included in
285
+ all copies or substantial portions of the Software.
286
+
287
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
288
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
289
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
290
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
291
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
292
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
293
+ DEALINGS IN THE SOFTWARE.
294
+
295
+ --------------------------------------------------------------------------------
296
+
297
+ Code in `cleanrl/qdagger_dqn_atari_impalacnn.py` and `cleanrl/qdagger_dqn_atari_jax_impalacnn.py` are adapted from https://github.com/google-research/reincarnating_rl
298
+
299
+ **NOTE: the original repo did not fill out the copyright section in their license
300
+ so the following copyright notice is copied as is per the license requirement.
301
+ See https://github.com/google-research/reincarnating_rl/blob/a1d402f48a9f8658ca6aa0ddf416ab391745ff2c/LICENSE#L189
302
+
303
+
304
+ Copyright [yyyy] [name of copyright owner]
305
+
306
+ Licensed under the Apache License, Version 2.0 (the "License");
307
+ you may not use this file except in compliance with the License.
308
+ You may obtain a copy of the License at
309
+
310
+ http://www.apache.org/licenses/LICENSE-2.0
311
+
312
+ Unless required by applicable law or agreed to in writing, software
313
+ distributed under the License is distributed on an "AS IS" BASIS,
314
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
315
+ See the License for the specific language governing permissions and
316
+ limitations under the License.
cleanrl/QUICKSTART_ULTRAHORIZON.md ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Quick Start: Training PPO on Ultrahorizon
2
+
3
+ ## 快速开始指南
4
+
5
+ ### 1. 测试环境包装器
6
+
7
+ 首先测试 Gymnasium 包装器是否正常工作:
8
+
9
+ ```bash
10
+ cd /Users/harryis/why_code/ICML_Memory/cleanrl
11
+ python ultrahorizon_gym_wrapper.py
12
+ ```
13
+
14
+ 这将运行一个简单的测试,创建环境、重置并执行几个随机动作。
15
+
16
+ ### 2. 训练 PPO 智能体
17
+
18
+ #### 简单模式(EASY)训练:
19
+
20
+ ```bash
21
+ python cleanrl/ppo_ultrahorizon.py --difficulty EASY --total-timesteps 500000
22
+ ```
23
+
24
+ #### 困难模式(HARD)训练:
25
+
26
+ ```bash
27
+ python cleanrl/ppo_ultrahorizon.py --difficulty HARD --total-timesteps 1000000
28
+ ```
29
+
30
+ #### 使用更多并行环境加速训练:
31
+
32
+ ```bash
33
+ python cleanrl/ppo_ultrahorizon.py \
34
+ --difficulty MEDIUM \
35
+ --num-envs 8 \
36
+ --total-timesteps 1000000 \
37
+ --learning-rate 3e-4
38
+ ```
39
+
40
+ ### 3. 监控训练过程
41
+
42
+ 启动 TensorBoard 查看训练指标:
43
+
44
+ ```bash
45
+ tensorboard --logdir runs/
46
+ ```
47
+
48
+ 然后在浏览器中打开 `http://localhost:6006`
49
+
50
+ ### 4. 主要参数说明
51
+
52
+ | 参数 | 默认值 | 说明 |
53
+ |------|--------|------|
54
+ | `--difficulty` | EASY | 环境难度:EASY, MEDIUM, HARD |
55
+ | `--total-timesteps` | 1000000 | 总训练步数 |
56
+ | `--learning-rate` | 2.5e-4 | 学习率 |
57
+ | `--num-envs` | 4 | 并行环境数量 |
58
+ | `--num-steps` | 128 | 每次rollout的步数 |
59
+ | `--seed` | 1 | 随机种子 |
60
+ | `--cuda` | True | 是否使用GPU |
61
+
62
+ ### 5. 文件结构
63
+
64
+ ```
65
+ cleanrl/
66
+ ├── envs/
67
+ │ ├── __init__.py # 环境包初始化
68
+ │ └── common.py # Difficulty 枚举定义
69
+ ├── Ultrahorizon_grid_env.py # 原始环境(你提供的)
70
+ ├── ultrahorizon_gym_wrapper.py # Gymnasium 包装器
71
+ ├── cleanrl/
72
+ │ ├── ppo_atari.py # 原始 PPO Atari 实现
73
+ │ └── ppo_ultrahorizon.py # PPO Ultrahorizon 实现(新)
74
+ ├── ULTRAHORIZON_README.md # 详细文档
75
+ └── QUICKSTART_ULTRAHORIZON.md # 本文件
76
+ ```
77
+
78
+ ### 6. 关键修改点
79
+
80
+ 从 `ppo_atari.py` 到 `ppo_ultrahorizon.py` 的主要变化:
81
+
82
+ 1. **环境包装器**:使用 `make_ultrahorizon_env()` 替代 `make_env()`
83
+ 2. **神经网络**:使用 MLP 替代 CNN
84
+ - Atari: Conv2D layers → 处理图像
85
+ - Ultrahorizon: Linear layers → 处理特征向量
86
+ 3. **观察空间**:605维特征向量(位置、能量、分数、步数、网格状态)
87
+ 4. **动作空间**:4个离散动作(上下左右)
88
+
89
+ ### 7. 预期训练时间
90
+
91
+ - **EASY 模式**:约 10-20 分钟(500K steps,4 envs,GPU)
92
+ - **MEDIUM 模式**:约 20-40 分钟(1M steps,4 envs,GPU)
93
+ - **HARD 模式**:约 30-60 分钟(1M steps,4 envs,GPU)
94
+
95
+ ### 8. 常见问题
96
+
97
+ **Q: 训练很慢怎么办?**
98
+ - 增加 `--num-envs` 参数(如 8 或 16)
99
+ - 确保使用 GPU:`--cuda True`
100
+ - 减少 `--total-timesteps`
101
+
102
+ **Q: 内存不足?**
103
+ - 减少 `--num-envs`(如 2 或 1)
104
+ - 使用 CPU:`--cuda False`
105
+
106
+ **Q: 如何保存模型?**
107
+ - 目前代码没有自动保存,可以在训练循环中添加模型保存逻辑
108
+ - 或者使用 Weights & Biases:`--track --wandb-project-name "your-project"`
109
+
110
+ ### 9. 下一步
111
+
112
+ - 调整超参数以获得更好的性能
113
+ - 尝试不同的难度级别
114
+ - 修改奖励函数以更好地引导学习
115
+ - 添加模型保存和加载功能
116
+ - 实现评估脚本来测试训练好的模型
cleanrl/README_convert.md ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 测试结果转换工具
2
+
3
+ 这个工具可以将PPO训练过程中保存的测试结果从one-hot向量格式转换为更直观的10x10字母矩阵格式,方便LLM分析。
4
+
5
+ ## 功能
6
+
7
+ - 将observation中的one-hot编码转换回字母(A-E, X)
8
+ - 重建10x10的网格地图
9
+ - 将归一化的位置坐标转换回实际坐标
10
+ - 在网格中标记agent的当前位置(用@表示)
11
+ - 保留所有原始的统计信息和轨迹数据
12
+
13
+ ## 使用方法
14
+
15
+ ### 1. 转换单个文件
16
+
17
+ ```bash
18
+ python convert_test_results.py /path/to/test_iter_732.json
19
+ ```
20
+
21
+ 这会在同一目录下生成 `test_iter_732_readable.json`
22
+
23
+ ### 2. 指定输出文件
24
+
25
+ ```bash
26
+ python convert_test_results.py /path/to/test_iter_732.json -o /path/to/output.json
27
+ ```
28
+
29
+ ### 3. 批量转换目录中的所有测试文件
30
+
31
+ ```bash
32
+ python convert_test_results.py /path/to/runs/directory -a
33
+ ```
34
+
35
+ 这会递归查找所有 `test_iter_*.json` 文件并转换它们。
36
+
37
+ ### 4. 自定义批量转换的文件模式
38
+
39
+ ```bash
40
+ python convert_test_results.py /path/to/runs/directory -a -p "test_*.json"
41
+ ```
42
+
43
+ ## 示例
44
+
45
+ ### 转换EASY难度的所有测试结果
46
+
47
+ ```bash
48
+ python convert_test_results.py runs/Ultrahorizon-v0__ppo_ultrahorizon__1_EASY__1761810199 -a
49
+ ```
50
+
51
+ ### 转换特定的测试文件
52
+
53
+ ```bash
54
+ python convert_test_results.py runs/Ultrahorizon-v0__ppo_ultrahorizon__1_EASY__1761810199/test_iter_732.json
55
+ ```
56
+
57
+ ## 输出格式
58
+
59
+ 转换后的JSON文件包含:
60
+
61
+ ```json
62
+ {
63
+ "iteration": 732,
64
+ "global_step": 1497088,
65
+ "training_progress": 0.1,
66
+ "test_results": {
67
+ "episode_returns": [...],
68
+ "episode_lengths": [...],
69
+ "final_scores": [...],
70
+ "mean_return": 123.45,
71
+ "trajectories": [
72
+ {
73
+ "actions": [0, 1, 2, ...],
74
+ "rewards": [1.0, -0.5, ...],
75
+ "dones": [false, false, ...],
76
+ "observations": [
77
+ {
78
+ "step": 0,
79
+ "position": {"x": 5, "y": 3},
80
+ "energy": 20.0,
81
+ "score": 0.0,
82
+ "steps": 0.0,
83
+ "grid": [
84
+ ["A", "B", "C", ...],
85
+ ["D", "E", "X", ...],
86
+ ...
87
+ ],
88
+ "grid_string": " 0 1 2 3 4 5 6 7 8 9\n -------------------\n0|A B C D E X A B C D \n1|E X A B C D E X A B \n...",
89
+ "action": "right",
90
+ "reward": 1.0
91
+ },
92
+ ...
93
+ ]
94
+ }
95
+ ]
96
+ }
97
+ }
98
+ ```
99
+
100
+ ## 网格可视化
101
+
102
+ 每个observation都包含 `grid_string` 字段,显示10x10的网格:
103
+
104
+ ```
105
+ 0 1 2 3 4 5 6 7 8 9
106
+ -------------------
107
+ 0|A B C D E X A B C D
108
+ 1|E X A B C D E X A B
109
+ 2|C D E X A B C D E X
110
+ 3|A B C D E @ A B C D <- @ 表示agent位置
111
+ 4|E X A B C D E X A B
112
+ 5|C D E X A B C D E X
113
+ 6|A B C D E X A B C D
114
+ 7|E X A B C D E X A B
115
+ 8|C D E X A B C D E X
116
+ 9|A B C D E X A B C D
117
+ ```
118
+
119
+ ## 观察向量结构
120
+
121
+ 原始observation是605维向量:
122
+ - **位置 (2维)**: x, y 坐标,归一化到 [0, 1]
123
+ - **能量 (1维)**: 归一化到 [0, 1],原始范围约为 [0, 20]
124
+ - **分数 (1维)**: 当前累积分数
125
+ - **步数 (1维)**: 归一化到 [0, 1],原始范围为 [0, 30]
126
+ - **网格状态 (600维)**: 10x10网格,每个格子6维one-hot编码(A, B, C, D, E, X)
127
+
128
+ ## 动作映射
129
+
130
+ - 0: up (向上)
131
+ - 1: down (向下)
132
+ - 2: left (向左)
133
+ - 3: right (向右)
134
+
135
+ ## 注意事项
136
+
137
+ 1. 转换后的文件会比原始文件大,因为包含了可读的字符串表示
138
+ 2. 网格坐标系:y=0在顶部,y=9在底部
139
+ 3. agent位置用 `@` 标记在grid_string中
140
+ 4. 所有原始数据(actions, rewards, dones)都会保留
cleanrl/ULTRAHORIZON_README.md ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ultrahorizon Grid Environment Integration with CleanRL PPO
2
+
3
+ This integration adapts the Ultrahorizon grid environment to work with CleanRL's PPO implementation.
4
+
5
+ ## Files Created
6
+
7
+ 1. **`envs/common.py`** - Common utilities including the `Difficulty` enum
8
+ 2. **`ultrahorizon_gym_wrapper.py`** - Gymnasium wrapper that converts the async text-based Ultrahorizon environment into a synchronous gym-compatible interface
9
+ 3. **`cleanrl/ppo_ultrahorizon.py`** - PPO implementation adapted for the Ultrahorizon environment
10
+
11
+ ## Key Differences from PPO Atari
12
+
13
+ ### Environment
14
+ - **Atari**: Image-based observations (84x84x4 frames), various discrete actions
15
+ - **Ultrahorizon**: Feature vector observations (605-dimensional), 4 discrete actions (up/down/left/right)
16
+
17
+ ### Neural Network Architecture
18
+ - **Atari**: Convolutional Neural Network (CNN) for processing images
19
+ - **Ultrahorizon**: Multi-Layer Perceptron (MLP) for processing feature vectors
20
+
21
+ ### Observation Space
22
+ The observation vector (605 dimensions) contains:
23
+ - **Position** (2): x, y coordinates normalized to [0, 1]
24
+ - **Energy** (1): Current energy normalized by initial energy (20)
25
+ - **Score** (1): Current score (can be negative)
26
+ - **Steps** (1): Current step count normalized by max steps (30)
27
+ - **Grid State** (600): 10x10 grid with one-hot encoded letters (A-E, X) = 10×10×6
28
+
29
+ ### Action Space
30
+ - 0: Move up
31
+ - 1: Move down
32
+ - 2: Move left
33
+ - 3: Move right
34
+
35
+ ## Usage
36
+
37
+ ### Basic Training
38
+
39
+ ```bash
40
+ cd /Users/harryis/why_code/ICML_Memory/cleanrl
41
+ python cleanrl/ppo_ultrahorizon.py --difficulty EASY
42
+ ```
43
+
44
+ ### Training with Custom Parameters
45
+
46
+ ```bash
47
+ python cleanrl/ppo_ultrahorizon.py \
48
+ --difficulty HARD \
49
+ --total-timesteps 1000000 \
50
+ --learning-rate 3e-4 \
51
+ --num-envs 8 \
52
+ --num-steps 128
53
+ ```
54
+
55
+ ### Available Arguments
56
+
57
+ - `--difficulty`: Environment difficulty (EASY, MEDIUM, HARD)
58
+ - `--total-timesteps`: Total training timesteps (default: 1000000)
59
+ - `--learning-rate`: Learning rate (default: 2.5e-4)
60
+ - `--num-envs`: Number of parallel environments (default: 4)
61
+ - `--num-steps`: Steps per rollout (default: 128)
62
+ - `--seed`: Random seed (default: 1)
63
+ - `--track`: Enable Weights & Biases tracking
64
+ - `--cuda`: Enable CUDA (default: True)
65
+
66
+ ### With Weights & Biases Tracking
67
+
68
+ ```bash
69
+ python cleanrl/ppo_ultrahorizon.py \
70
+ --track \
71
+ --wandb-project-name "ultrahorizon-ppo" \
72
+ --wandb-entity "your-entity"
73
+ ```
74
+
75
+ ## Testing the Wrapper
76
+
77
+ You can test the Gymnasium wrapper independently:
78
+
79
+ ```bash
80
+ cd /Users/harryis/why_code/ICML_Memory/cleanrl
81
+ python ultrahorizon_gym_wrapper.py
82
+ ```
83
+
84
+ This will run a simple test that creates the environment, resets it, and takes a few random actions.
85
+
86
+ ## Implementation Details
87
+
88
+ ### Reward Structure
89
+ The reward at each step is based on the score change in the environment. The agent learns to:
90
+ - Maximize score by discovering the hidden effects of letters A-E
91
+ - Manage energy efficiently (each move costs 1 energy)
92
+ - Navigate the grid strategically
93
+
94
+ ### Episode Termination
95
+ An episode terminates when:
96
+ - Energy reaches 0
97
+ - Maximum steps (30) are reached
98
+ - An invalid move is attempted
99
+
100
+ ### Synchronous Wrapper
101
+ Since the original Ultrahorizon environment uses async methods, the wrapper uses `asyncio.run()` to convert async calls to synchronous ones, making it compatible with CleanRL's synchronous training loop.
102
+
103
+ ## Requirements
104
+
105
+ Make sure you have the following dependencies installed:
106
+
107
+ ```bash
108
+ pip install gymnasium torch numpy tensorboard tyro
109
+ ```
110
+
111
+ For the Ultrahorizon environment, you'll also need:
112
+ ```bash
113
+ pip install openai pyyaml
114
+ ```
115
+
116
+ ## Monitoring Training
117
+
118
+ Training metrics are logged to TensorBoard:
119
+
120
+ ```bash
121
+ tensorboard --logdir runs/
122
+ ```
123
+
124
+ Key metrics to monitor:
125
+ - `charts/episodic_return`: Episode returns over time
126
+ - `charts/episodic_length`: Episode lengths
127
+ - `losses/policy_loss`: Policy gradient loss
128
+ - `losses/value_loss`: Value function loss
129
+ - `losses/entropy`: Policy entropy (exploration)
130
+ - `charts/learning_rate`: Current learning rate (if annealing)
131
+
132
+ ## Troubleshooting
133
+
134
+ ### Import Errors
135
+ If you encounter import errors, make sure you're running the script from the correct directory:
136
+ ```bash
137
+ cd /Users/harryis/why_code/ICML_Memory/cleanrl
138
+ python cleanrl/ppo_ultrahorizon.py
139
+ ```
140
+
141
+ ### CUDA Out of Memory
142
+ If you encounter CUDA memory issues, try:
143
+ - Reducing `--num-envs` (e.g., from 8 to 4)
144
+ - Reducing `--num-steps` (e.g., from 128 to 64)
145
+ - Using `--cuda False` to train on CPU
146
+
147
+ ### Slow Training
148
+ The environment involves async operations which may slow down training. Consider:
149
+ - Increasing `--num-envs` to parallelize more
150
+ - Using a faster machine or GPU
151
+ - Reducing the observation space dimensionality if needed
152
+
153
+ ## Comparison with Original PPO Atari
154
+
155
+ | Feature | PPO Atari | PPO Ultrahorizon |
156
+ |---------|-----------|------------------|
157
+ | Observation | 84×84×4 images | 605-dim feature vector |
158
+ | Network | CNN | MLP |
159
+ | Actions | Game-specific | 4 directions |
160
+ | Default envs | 8 | 4 |
161
+ | Total timesteps | 10M | 1M |
162
+ | Clip coefficient | 0.1 | 0.2 |
163
+
164
+ The main algorithmic components (PPO loss, GAE, value clipping) remain identical to the original implementation.
cleanrl/cleanrl/noisy_dqn_2048_refined.py ADDED
@@ -0,0 +1,806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NoisyNet DQN (dueling CNN) for RAGEN 2048
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Dict, Any, Tuple
8
+ from collections import deque
9
+
10
+ import gymnasium as gym
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.optim as optim
15
+ import tyro
16
+ import json
17
+
18
+ import sys
19
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../'))
20
+
21
+ # 引用你提供的 env 和 config
22
+ from ragen.env.game_2048.env import Game2048Env
23
+ from ragen.env.game_2048.config import Game2048EnvConfig
24
+
25
+
26
+ class Game2048Wrapper(gym.Env):
27
+ metadata = {"render_modes": ["text"]}
28
+
29
+ def __init__(self, env: Game2048Env, n_channels: int = 16):
30
+ super().__init__()
31
+ self._env = env
32
+ self._n_channels = int(n_channels)
33
+ self.observation_space = gym.spaces.Box(low=0.0, high=1.0, shape=(self._n_channels, 4, 4), dtype=np.float32)
34
+ self.action_space = self._env.action_space
35
+ self._last_info: Dict[str, Any] | None = None
36
+
37
+ def _encode_grid(self, grid: np.ndarray) -> np.ndarray:
38
+ grid_flat = grid.flatten()
39
+ with np.errstate(divide='ignore'):
40
+ power_grid = np.log2(grid_flat, where=(grid_flat > 0)).astype(int)
41
+ power_grid[grid_flat == 0] = 0
42
+ power_grid = np.clip(power_grid, 0, self._n_channels - 1)
43
+ one_hot = np.eye(self._n_channels)[power_grid]
44
+ obs = one_hot.reshape(4, 4, self._n_channels).transpose(2, 0, 1)
45
+ return obs.astype(np.float32)
46
+
47
+ def reset(self, *, seed: int | None = None, options: Dict[str, Any] | None = None):
48
+ text_obs, info = self._env.reset(seed=seed, options=options)
49
+ self._last_info = info
50
+ grid = info.get('grid', np.zeros((4, 4), dtype=np.int64))
51
+ obs = self._encode_grid(grid)
52
+ # augment info with max_tile for downstream logging
53
+ ret_info = {k: v for k, v in (info or {}).items() if k != 'grid'}
54
+ try:
55
+ ret_info['max_tile'] = int(np.max(grid))
56
+ except Exception:
57
+ ret_info['max_tile'] = int(ret_info.get('max_tile', 0))
58
+ return obs, ret_info
59
+
60
+ def step(self, action: int):
61
+ text_obs, reward, done, info = self._env.step(int(action))
62
+ self._last_info = info
63
+ grid = info.get('grid', np.zeros((4, 4), dtype=np.int64))
64
+ obs = self._encode_grid(grid)
65
+
66
+ ret_info = {k: v for k, v in (info or {}).items() if k != 'grid'}
67
+ try:
68
+ ret_info['max_tile'] = int(np.max(grid))
69
+ except Exception:
70
+ ret_info['max_tile'] = int(ret_info.get('max_tile', 0))
71
+
72
+ terminated = bool(done)
73
+ truncated = False
74
+ return obs, float(reward), terminated, truncated, ret_info
75
+
76
+
77
+ def get_action_mask(self) -> np.ndarray:
78
+ if self._last_info is None:
79
+ return np.ones((4,), dtype=bool)
80
+ mask = self._last_info.get('action_mask', None)
81
+ if mask is None:
82
+ return np.ones((4,), dtype=bool)
83
+ return np.asarray(mask, dtype=bool)
84
+
85
+ def render(self):
86
+ return self._env.render()
87
+
88
+ def close(self):
89
+ self._env.close()
90
+
91
+
92
+ @dataclass
93
+ class Args:
94
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
95
+ seed: int = 1
96
+ torch_deterministic: bool = True
97
+ cuda: bool = True
98
+ track: bool = True
99
+ wandb_project_name: str = "2048-RL"
100
+ wandb_entity: str | None = None
101
+ capture_video: bool = False
102
+
103
+ # Algorithm
104
+ env_id: str = "Game2048NoisyDQN"
105
+ total_timesteps: int = 1_000_000
106
+ learning_rate: float = 1e-4
107
+ gamma: float = 0.997
108
+ batch_size: int = 512
109
+ buffer_size: int = 2400_000
110
+ target_network_frequency: int = 15000
111
+ train_frequency: int = 4
112
+ learning_starts: int = 20_000
113
+
114
+ # Epsilon-greedy (used lightly for warmup; noisy nets handle exploration)
115
+ start_e: float = 1.0
116
+ end_e: float = 0.05
117
+ exploration_fraction: float = 0.8
118
+
119
+ # Model
120
+ dueling: bool = True
121
+ # reward_transform 和 clip 参数不再使用,由环境 config 控制
122
+
123
+ # n-step and PER
124
+ n_step: int = 10
125
+ per_alpha: float = 0.5
126
+ per_beta_start: float = 0.4
127
+ per_beta_frames: int = 1_000_000
128
+ per_eps: float = 1e-6
129
+
130
+ # Env config
131
+ two_prob: float = 0.9
132
+ max_steps_env: int = 1000
133
+
134
+ # Eval config
135
+ eval_splits: int = 2
136
+ eval_episodes: int = 200
137
+
138
+
139
+ def make_env(run_name: str, seed: int, args: Args, capture_video: bool = False):
140
+ # 显式开启 use_log_reward=True,尽管 config 默认可能已为 True
141
+ cfg = Game2048EnvConfig(size=4, two_prob=args.two_prob, use_log_reward=True)
142
+ base = Game2048Env(cfg)
143
+ env = Game2048Wrapper(base)
144
+ env = gym.wrappers.TimeLimit(env, max_episode_steps=args.max_steps_env)
145
+ env = gym.wrappers.RecordEpisodeStatistics(env)
146
+ if capture_video:
147
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
148
+ return env
149
+
150
+
151
+ class NoisyLinear(nn.Module):
152
+ def __init__(self, in_features: int, out_features: int, std_init: float = 0.5):
153
+ super().__init__()
154
+ self.in_features = in_features
155
+ self.out_features = out_features
156
+ self.weight_mu = nn.Parameter(torch.empty(out_features, in_features))
157
+ self.weight_sigma = nn.Parameter(torch.empty(out_features, in_features))
158
+ self.register_buffer('weight_epsilon', torch.empty(out_features, in_features))
159
+ self.bias_mu = nn.Parameter(torch.empty(out_features))
160
+ self.bias_sigma = nn.Parameter(torch.empty(out_features))
161
+ self.register_buffer('bias_epsilon', torch.empty(out_features))
162
+ self.std_init = std_init / np.sqrt(in_features)
163
+ self.reset_parameters()
164
+ self.reset_noise()
165
+
166
+ def reset_parameters(self):
167
+ mu_range = 1 / np.sqrt(self.in_features)
168
+ self.weight_mu.data.uniform_(-mu_range, mu_range)
169
+ self.weight_sigma.data.fill_(self.std_init)
170
+ self.bias_mu.data.uniform_(-mu_range, mu_range)
171
+ self.bias_sigma.data.fill_(self.std_init)
172
+
173
+ def reset_noise(self):
174
+ epsilon_in = torch.randn(self.in_features, device=self.weight_mu.device)
175
+ epsilon_out = torch.randn(self.out_features, device=self.weight_mu.device)
176
+ self.weight_epsilon.copy_(epsilon_out.ger(epsilon_in))
177
+ self.bias_epsilon.copy_(epsilon_out)
178
+
179
+ def forward(self, x):
180
+ if self.training:
181
+ w = self.weight_mu + self.weight_sigma * self.weight_epsilon
182
+ b = self.bias_mu + self.bias_sigma * self.bias_epsilon
183
+ else:
184
+ w = self.weight_mu
185
+ b = self.bias_mu
186
+ return torch.nn.functional.linear(x, w, b)
187
+
188
+
189
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
190
+ if isinstance(layer, NoisyLinear):
191
+ nn.init.orthogonal_(layer.weight_mu, std)
192
+ nn.init.constant_(layer.bias_mu, bias_const)
193
+ layer.weight_sigma.data.fill_(layer.std_init)
194
+ layer.bias_sigma.data.fill_(layer.std_init)
195
+ else:
196
+ nn.init.orthogonal_(layer.weight, std)
197
+ nn.init.constant_(layer.bias, bias_const)
198
+ return layer
199
+
200
+
201
+ class QConvNoisy(nn.Module):
202
+ def __init__(self, obs_shape: Tuple[int, int, int], act_dim: int, dueling: bool = True):
203
+ super().__init__()
204
+ c, h, w = obs_shape
205
+ self.dueling = dueling
206
+ self._act_dim = act_dim
207
+ self.features = nn.Sequential(
208
+ layer_init(nn.Conv2d(c, 64, 2, 1, 0)),
209
+ nn.ReLU(),
210
+ layer_init(nn.Conv2d(64, 128, 2, 1, 1)),
211
+ nn.ReLU(),
212
+ layer_init(nn.Conv2d(128, 128, 2, 1, 0)),
213
+ nn.ReLU(),
214
+ nn.Flatten(),
215
+ )
216
+ # compute fc_in via dummy
217
+ with torch.no_grad():
218
+ dummy = torch.zeros(1, c, h, w)
219
+ fc_in = int(self.features(dummy).shape[1])
220
+ if self.dueling:
221
+ self.adv_head = nn.Sequential(
222
+ layer_init(NoisyLinear(fc_in, 512)),
223
+ nn.ReLU(),
224
+ layer_init(NoisyLinear(512, act_dim), std=0.01),
225
+ )
226
+ self.val_head = nn.Sequential(
227
+ layer_init(NoisyLinear(fc_in, 512)),
228
+ nn.ReLU(),
229
+ layer_init(NoisyLinear(512, 1), std=0.01),
230
+ )
231
+ else:
232
+ self.head = nn.Sequential(
233
+ layer_init(NoisyLinear(fc_in, 512)),
234
+ nn.ReLU(),
235
+ layer_init(NoisyLinear(512, act_dim), std=0.01),
236
+ )
237
+
238
+ def reset_noise(self):
239
+ for m in self.modules():
240
+ if isinstance(m, NoisyLinear):
241
+ m.reset_noise()
242
+
243
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
244
+ x = self.features(x)
245
+ if self.dueling:
246
+ adv = self.adv_head(x)
247
+ val = self.val_head(x)
248
+ q = val + adv - adv.mean(dim=1, keepdim=True)
249
+ return q
250
+ else:
251
+ q = self.head(x)
252
+ return q
253
+
254
+
255
+ class SumTree:
256
+ def __init__(self, capacity: int):
257
+ self.capacity = 1
258
+ while self.capacity < capacity:
259
+ self.capacity *= 2
260
+ self.tree = np.zeros(2 * self.capacity, dtype=np.float32)
261
+ self.size = 0
262
+ self.ptr = 0
263
+
264
+ def add(self, p: float):
265
+ idx = self.ptr + self.capacity
266
+ self.update(idx, p)
267
+ self.ptr = (self.ptr + 1) % self.capacity
268
+ self.size = min(self.size + 1, self.capacity)
269
+ return idx
270
+
271
+ def update(self, idx: int, p: float):
272
+ change = p - self.tree[idx]
273
+ self.tree[idx] = p
274
+ idx //= 2
275
+ while idx >= 1:
276
+ self.tree[idx] += change
277
+ idx //= 2
278
+
279
+ def total(self) -> float:
280
+ return float(self.tree[1])
281
+
282
+ def get(self, s: float) -> int:
283
+ idx = 1
284
+ while idx < self.capacity:
285
+ left = 2 * idx
286
+ if s <= self.tree[left]:
287
+ idx = left
288
+ else:
289
+ s -= self.tree[left]
290
+ idx = left + 1
291
+ return idx
292
+
293
+
294
+ class PrioritizedReplayBuffer:
295
+ def __init__(self, capacity: int, obs_shape: Tuple[int, int, int], alpha: float = 0.6, eps: float = 1e-6):
296
+ self.capacity = capacity
297
+ self.alpha = alpha
298
+ self.eps = eps
299
+ self.tree = SumTree(capacity)
300
+ self.obs_buf = np.zeros((capacity,) + obs_shape, dtype=np.float32)
301
+ self.next_obs_buf = np.zeros((capacity,) + obs_shape, dtype=np.float32)
302
+ self.act_buf = np.zeros((capacity,), dtype=np.int64)
303
+ self.rew_buf = np.zeros((capacity,), dtype=np.float32)
304
+ self.done_buf = np.zeros((capacity,), dtype=np.float32)
305
+ self.max_prio = 1.0
306
+
307
+ def _store_index(self) -> int:
308
+ idx_leaf = self.tree.add(self.max_prio ** self.alpha)
309
+ idx = (idx_leaf - self.tree.capacity) % self.capacity
310
+ return idx, idx_leaf
311
+
312
+ def add(self, obs: np.ndarray, act: int, rew: float, done: bool, next_obs: np.ndarray):
313
+ idx, idx_leaf = self._store_index()
314
+ self.obs_buf[idx] = obs
315
+ self.next_obs_buf[idx] = next_obs
316
+ self.act_buf[idx] = act
317
+ self.rew_buf[idx] = rew
318
+ self.done_buf[idx] = 1.0 if done else 0.0
319
+ return idx_leaf
320
+
321
+ def can_sample(self, batch_size: int) -> bool:
322
+ return self.tree.size >= batch_size
323
+
324
+ def sample(self, batch_size: int, beta: float):
325
+ total_p = self.tree.total()
326
+ if (not np.isfinite(total_p)) or (total_p <= 0.0):
327
+ size = max(1, self.tree.size)
328
+ idxs = np.random.randint(0, size, size=batch_size)
329
+ idx_leaves = (idxs + self.tree.capacity).astype(np.int64)
330
+ weights = np.ones((batch_size,), dtype=np.float32)
331
+ return (
332
+ self.obs_buf[idxs],
333
+ self.act_buf[idxs],
334
+ self.rew_buf[idxs],
335
+ self.done_buf[idxs],
336
+ self.next_obs_buf[idxs],
337
+ idx_leaves,
338
+ weights,
339
+ )
340
+ seg = total_p / float(batch_size)
341
+ idx_leaves = []
342
+ idxs = []
343
+ priorities = []
344
+ for i in range(batch_size):
345
+ a = seg * i
346
+ b = seg * (i + 1)
347
+ s = np.random.uniform(a, b)
348
+ idx_leaf = self.tree.get(s)
349
+ idx = (idx_leaf - self.tree.capacity) % self.capacity
350
+ p = float(self.tree.tree[idx_leaf])
351
+ idx_leaves.append(idx_leaf)
352
+ idxs.append(idx)
353
+ priorities.append(p)
354
+ probs = np.asarray(priorities, dtype=np.float32) / float(total_p)
355
+ probs = np.clip(probs, 1e-12, None)
356
+ weights = (self.tree.size * probs) ** (-beta)
357
+ weights = weights / (weights.max() + 1e-8)
358
+ return (
359
+ self.obs_buf[idxs],
360
+ self.act_buf[idxs],
361
+ self.rew_buf[idxs],
362
+ self.done_buf[idxs],
363
+ self.next_obs_buf[idxs],
364
+ np.asarray(idx_leaves, dtype=np.int64),
365
+ np.asarray(weights, dtype=np.float32),
366
+ )
367
+
368
+ def update_priorities(self, idx_leaves: np.ndarray, td_errors: np.ndarray):
369
+ td = np.abs(td_errors)
370
+ td = np.where(np.isfinite(td), td, self.eps)
371
+ td = np.clip(td + self.eps, self.eps, 1e3)
372
+ self.max_prio = max(self.max_prio, float(td.max()))
373
+ for idx_leaf, p in zip(idx_leaves, td):
374
+ self.tree.update(int(idx_leaf), float(p) ** self.alpha)
375
+
376
+
377
+ class NStepBuffer:
378
+ def __init__(self, n: int, gamma: float):
379
+ self.n = int(max(1, n))
380
+ self.gamma = float(gamma)
381
+ self.states = []
382
+ self.actions = []
383
+ self.rewards = []
384
+ self.dones = []
385
+ self.next_states = []
386
+
387
+ def push(self, s, a, r, d, next_s):
388
+ self.states.append(s)
389
+ self.actions.append(a)
390
+ self.rewards.append(r)
391
+ self.dones.append(d)
392
+ self.next_states.append(next_s)
393
+ if len(self.states) >= self.n:
394
+ return self._pop()
395
+ return None
396
+
397
+ def _pop(self):
398
+ m = min(self.n, len(self.states))
399
+ R = 0.0
400
+ cut = m
401
+ for i in range(m):
402
+ R += (self.gamma ** i) * self.rewards[i]
403
+ if self.dones[i]:
404
+ cut = i + 1
405
+ break
406
+ s0 = self.states[0]
407
+ a0 = self.actions[0]
408
+ dN = any(self.dones[: cut])
409
+ last_idx = cut - 1
410
+ sN = self.next_states[last_idx]
411
+ self.states.pop(0)
412
+ self.actions.pop(0)
413
+ self.rewards.pop(0)
414
+ self.dones.pop(0)
415
+ self.next_states.pop(0)
416
+ return s0, a0, R, dN, sN
417
+
418
+ def flush(self):
419
+ out = []
420
+ while len(self.states) > 0:
421
+ out_tr = self._pop()
422
+ if out_tr is not None:
423
+ out.append(out_tr)
424
+ return out
425
+
426
+
427
+ def augment_transition(obs, action, reward, done, next_obs):
428
+ """
429
+ 利用 2048 的旋转和镜像对称性,将 1 条经验扩展为 8 条。
430
+ """
431
+ augmented_data = []
432
+
433
+ curr_obs = obs.copy()
434
+ curr_next_obs = next_obs.copy()
435
+ curr_action = action
436
+
437
+ rot_90_map = {0: 3, 1: 0, 2: 1, 3: 2}
438
+ flip_map = {0: 0, 1: 3, 2: 2, 3: 1}
439
+
440
+ for _ in range(4):
441
+ # 1. 添加当前旋转状态
442
+ augmented_data.append((curr_obs, curr_action, reward, done, curr_next_obs))
443
+
444
+ # 2. 添加当前旋转状态的【水平翻转】版本
445
+ flip_obs = np.flip(curr_obs, axis=2)
446
+ flip_next_obs = np.flip(curr_next_obs, axis=2)
447
+ flip_action = flip_map[curr_action]
448
+ augmented_data.append((flip_obs, flip_action, reward, done, flip_next_obs))
449
+
450
+ # 3. 旋转90度
451
+ curr_obs = np.rot90(curr_obs, k=1, axes=(1, 2))
452
+ curr_next_obs = np.rot90(curr_next_obs, k=1, axes=(1, 2))
453
+ curr_action = rot_90_map[curr_action]
454
+
455
+ return augmented_data
456
+
457
+
458
+ if __name__ == "__main__":
459
+ args = tyro.cli(Args)
460
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
461
+
462
+ if args.track:
463
+ import wandb
464
+ wandb.init(
465
+ project=args.wandb_project_name,
466
+ entity=args.wandb_entity,
467
+ config=vars(args),
468
+ name=run_name,
469
+ monitor_gym=True,
470
+ save_code=True,
471
+ )
472
+ try:
473
+ wandb.define_metric("global_step")
474
+ for prefix in ["train/*", "rollout/*", "eval/*", "losses/*", "charts/*", "perf/*"]:
475
+ wandb.define_metric(prefix, step_metric="global_step")
476
+ except Exception:
477
+ pass
478
+
479
+ random.seed(args.seed)
480
+ np.random.seed(args.seed)
481
+ torch.manual_seed(args.seed)
482
+ torch.backends.cudnn.deterministic = args.torch_deterministic
483
+
484
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
485
+
486
+ env = make_env(run_name, args.seed, args, args.capture_video)
487
+ obs_shape = env.observation_space.shape
488
+ act_dim = env.action_space.n
489
+
490
+ policy_net = QConvNoisy(obs_shape, act_dim, dueling=args.dueling).to(device)
491
+ target_net = QConvNoisy(obs_shape, act_dim, dueling=args.dueling).to(device)
492
+ target_net.load_state_dict(policy_net.state_dict())
493
+ target_net.eval()
494
+
495
+ optimizer = optim.Adam(policy_net.parameters(), lr=args.learning_rate)
496
+
497
+ rb = PrioritizedReplayBuffer(args.buffer_size, obs_shape, alpha=args.per_alpha, eps=args.per_eps)
498
+ nbuf = NStepBuffer(args.n_step, args.gamma)
499
+
500
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes: int, step_tag: int):
501
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
502
+ out_dir.mkdir(parents=True, exist_ok=True)
503
+ out_path = out_dir / "trajectories.jsonl"
504
+ env_eval = make_env_fn()
505
+ collected = 0
506
+ summary_returns = []
507
+ summary_success = []
508
+ with out_path.open("w") as f:
509
+ while collected < n_episodes:
510
+ state, info = env_eval.reset(seed=args.seed + 100000 + collected)
511
+ current_info = info or {}
512
+ traj_states = [np.asarray(state).tolist()]
513
+ traj_actions = []
514
+ traj_rewards = []
515
+ traj_dones = []
516
+ traj_success = []
517
+ done = False
518
+ step_count = 0
519
+ max_eval_steps = getattr(env_eval, '_max_episode_steps', None) or args.max_steps_env
520
+ while not done:
521
+ with torch.no_grad():
522
+ q = agent_model(torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0))
523
+ mask_np = current_info.get('action_mask', np.ones(act_dim, dtype=bool))
524
+ mask = torch.tensor(mask_np, device=device, dtype=torch.bool).unsqueeze(0)
525
+ masked_q = torch.where(mask, q, torch.full_like(q, -1e9))
526
+ action = int(torch.argmax(masked_q, dim=1).item())
527
+ next_state, reward, terminated, truncated, info = env_eval.step(action)
528
+ traj_actions.append(int(action))
529
+
530
+ # === Eval: 使用 Raw Reward 进行统计 (Pre-regularization) ===
531
+ raw_r = info.get('raw_reward', reward) if info else reward
532
+ traj_rewards.append(float(raw_r))
533
+
534
+ step_count += 1
535
+ d = bool(terminated) or bool(truncated) or (step_count >= max_eval_steps)
536
+ traj_dones.append(d)
537
+ traj_success.append(bool((info or {}).get('success', False)))
538
+ state = next_state
539
+ current_info = info or {}
540
+ traj_states.append(np.asarray(state).tolist())
541
+ done = d
542
+ ep_ret = float(sum(traj_rewards))
543
+ ep_succ = bool(any(traj_success))
544
+ record = {
545
+ "states": traj_states,
546
+ "actions": traj_actions,
547
+ "rewards": traj_rewards,
548
+ "dones": traj_dones,
549
+ "success": traj_success,
550
+ "episode_return": ep_ret,
551
+ "episode_success": ep_succ,
552
+ }
553
+ f.write(json.dumps(record) + "\n")
554
+ collected += 1
555
+ summary_returns.append(ep_ret)
556
+ summary_success.append(1.0 if ep_succ else 0.0)
557
+ env_eval.close()
558
+ try:
559
+ metrics = {
560
+ "global_step": int(step_tag),
561
+ "episodes": int(n_episodes),
562
+ "success_rate": float(np.mean(summary_success)) if len(summary_success) else 0.0,
563
+ "avg_return": float(np.mean(summary_returns)) if len(summary_returns) else 0.0,
564
+ "std_return": float(np.std(summary_returns)) if len(summary_returns) else 0.0,
565
+ }
566
+ with (out_dir / "metrics.json").open("w") as mf:
567
+ json.dump(metrics, mf)
568
+ except Exception as e:
569
+ print(f"Warning: failed to write eval metrics: {e}")
570
+
571
+ exploration_steps = max(1, int(args.exploration_fraction * args.total_timesteps))
572
+
573
+ def epsilon_by_step(t: int):
574
+ return args.end_e + (args.start_e - args.end_e) * max(0.0, (exploration_steps - t) / exploration_steps)
575
+
576
+ global_step = 0
577
+ start_time = time.time()
578
+
579
+ obs, info = env.reset(seed=args.seed)
580
+ current_info = info or {}
581
+
582
+ # 记录当前 episode 的原始分数累积
583
+ ep_return = 0.0
584
+ ep_len = 0
585
+ # 记录该 episode 内每步的累计分数,用于 score_mean 和 final_score
586
+ ep_scores = []
587
+
588
+ # 滑动窗口记录最近的 success 和 return (raw)
589
+ ep_success_window = deque(maxlen=100)
590
+ ep_return_window = deque(maxlen=100)
591
+
592
+ # 仅用于 PPO charts 的 step_reward 分布 (这里记录 Log Reward 用于观察训练稳定性)
593
+ step_reward_window = deque(maxlen=2048)
594
+
595
+ eval_every_steps = max(1, args.total_timesteps // args.eval_splits)
596
+
597
+ while global_step < args.total_timesteps:
598
+ epsilon = epsilon_by_step(global_step)
599
+ with torch.no_grad():
600
+ q_values = policy_net(torch.tensor(obs, dtype=torch.float32, device=device).unsqueeze(0))
601
+ mask_np = current_info.get('action_mask', np.ones(act_dim, dtype=bool))
602
+ mask = torch.tensor(mask_np, device=device, dtype=torch.bool).unsqueeze(0)
603
+ masked_q = torch.where(mask, q_values, torch.full_like(q_values, -1e9))
604
+ action_greedy = int(torch.argmax(masked_q, dim=1).item())
605
+ if (global_step < args.learning_starts) and (np.random.rand() < 0.5):
606
+ valid = np.where(mask_np)[0]
607
+ if len(valid) > 0:
608
+ action = int(np.random.choice(valid))
609
+ else:
610
+ action = int(np.random.randint(0, act_dim))
611
+ else:
612
+ action = action_greedy
613
+
614
+ next_obs, reward, terminated, truncated, info = env.step(action)
615
+ done = bool(terminated) or bool(truncated)
616
+
617
+ # === 训练用 Reward (已正则化) ===
618
+ # 环境配置了 use_log_reward=True,所以这里的 reward 已经是 log scale
619
+ train_r = float(reward)
620
+
621
+ # 将经验推入 N-step Buffer
622
+ n_out = nbuf.push(obs.astype(np.float32), int(action), float(train_r), bool(done), next_obs.astype(np.float32))
623
+ if n_out is not None:
624
+ s0, a0, Rn, dN, sN = n_out
625
+
626
+ # === 数据增强 (8x) ===
627
+ aug_batch = augment_transition(s0, a0, Rn, dN, sN)
628
+ for sample in aug_batch:
629
+ _s, _a, _r, _d, _ns = sample
630
+ rb.add(_s, _a, _r, _d, _ns)
631
+
632
+ obs = next_obs
633
+ current_info = info or {}
634
+
635
+ # === Logging 用 Reward (Raw Score) ===
636
+ # 优先使用 info['raw_reward'],如果没有则回退 (理论上一定有)
637
+ raw_r = float(info.get('raw_reward', reward))
638
+ ep_return += raw_r
639
+ # 记录累计分数轨迹
640
+ try:
641
+ ep_scores.append(float(info.get('score', 0.0)))
642
+ except Exception:
643
+ pass
644
+
645
+ try:
646
+ step_reward_window.append(float(train_r))
647
+ except Exception:
648
+ pass
649
+ ep_len += 1
650
+ global_step += 1
651
+
652
+ if (global_step > args.learning_starts) and rb.can_sample(args.batch_size) and (global_step % args.train_frequency == 0):
653
+ frac = min(1.0, global_step / float(max(1, args.per_beta_frames)))
654
+ beta = args.per_beta_start + (1.0 - args.per_beta_start) * frac
655
+
656
+ batch_obs, batch_act, batch_rew, batch_done, batch_next_obs, idx_leaves, weights = rb.sample(args.batch_size, beta)
657
+ b_obs = torch.tensor(batch_obs, dtype=torch.float32, device=device)
658
+ b_act = torch.tensor(batch_act, dtype=torch.int64, device=device)
659
+ b_rew = torch.tensor(batch_rew, dtype=torch.float32, device=device)
660
+ b_done = torch.tensor(batch_done, dtype=torch.float32, device=device)
661
+ b_next_obs = torch.tensor(batch_next_obs, dtype=torch.float32, device=device)
662
+ b_w = torch.tensor(weights, dtype=torch.float32, device=device)
663
+
664
+ with torch.no_grad():
665
+ next_actions = policy_net(b_next_obs).argmax(dim=1)
666
+ next_q = target_net(b_next_obs).gather(1, next_actions.view(-1, 1)).squeeze(1)
667
+ target_q = b_rew + (args.gamma ** args.n_step) * (1.0 - b_done) * next_q
668
+
669
+ current_q = policy_net(b_obs).gather(1, b_act.view(-1, 1)).squeeze(1)
670
+ td_error = target_q - current_q
671
+ per_loss = torch.abs(td_error).detach().cpu().numpy()
672
+ loss_unreduced = torch.nn.functional.smooth_l1_loss(current_q, target_q, reduction='none')
673
+ loss = (b_w * loss_unreduced).mean()
674
+
675
+ optimizer.zero_grad()
676
+ loss.backward()
677
+ nn.utils.clip_grad_norm_(policy_net.parameters(), max_norm=10.0)
678
+ optimizer.step()
679
+
680
+ policy_net.reset_noise()
681
+ target_net.reset_noise()
682
+
683
+ rb.update_priorities(idx_leaves, td_error.detach().cpu().numpy())
684
+
685
+ if args.track:
686
+ try:
687
+ import wandb
688
+ try:
689
+ avg_reward_val = float(np.mean(step_reward_window)) if len(step_reward_window) > 0 else 0.0
690
+ except Exception:
691
+ avg_reward_val = 0.0
692
+ wandb.log({
693
+ "global_step": int(global_step),
694
+ "train/loss": float(loss.item()),
695
+ "train/value_loss": None,
696
+ "train/policy_loss": None,
697
+ "train/entropy": None,
698
+ "losses/explained_variance": None,
699
+ "charts/avg_reward": avg_reward_val,
700
+ "charts/avg_value": None,
701
+ "train/learning_rate": float(optimizer.param_groups[0]["lr"]),
702
+ "charts/epsilon": float(epsilon),
703
+ "perf/SPS": int(global_step / (time.time() - start_time)),
704
+ }, step=global_step)
705
+ except Exception:
706
+ pass
707
+
708
+ if global_step % args.target_network_frequency == 0:
709
+ target_net.load_state_dict(policy_net.state_dict())
710
+
711
+ if done:
712
+ succ = bool((info or {}).get('success', False))
713
+ max_tile = int((info or {}).get('max_tile', 0))
714
+ # 计算该局的 score_mean 和 final_score
715
+ try:
716
+ score_mean = float(np.mean(ep_scores)) if len(ep_scores) > 0 else 0.0
717
+ except Exception:
718
+ score_mean = 0.0
719
+ try:
720
+ final_score = float(ep_scores[-1]) if len(ep_scores) > 0 else 0.0
721
+ except Exception:
722
+ final_score = 0.0
723
+
724
+ # 更新滑动窗口
725
+ ep_success_window.append(1.0 if succ else 0.0)
726
+ ep_return_window.append(float(ep_return)) # Raw Score
727
+
728
+ # 处理 N-step buffer 剩余部分 (同样做 augmentation)
729
+ for out_tr in nbuf.flush():
730
+ s0, a0, Rn, dN, sN = out_tr
731
+ aug_batch = augment_transition(s0, a0, Rn, dN, sN)
732
+ for sample in aug_batch:
733
+ _s, _a, _r, _d, _ns = sample
734
+ rb.add(_s, _a, _r, _d, _ns)
735
+
736
+ try:
737
+ if max_tile is not None:
738
+ print(f"global_step={global_step}, episodic_return={ep_return:.1f}, length={ep_len}, max_tile={int(max_tile)}, success={succ}")
739
+ else:
740
+ print(f"global_step={global_step}, episodic_return={ep_return:.1f}, length={ep_len}, success={succ}")
741
+ except Exception:
742
+ pass
743
+
744
+ if args.track:
745
+ try:
746
+ import wandb
747
+ # 计算 avg_episode_return (Raw)
748
+ avg_ep_ret = float(np.mean(ep_return_window)) if len(ep_return_window) > 0 else 0.0
749
+
750
+ wandb.log({
751
+ "global_step": int(global_step),
752
+ "rollout/episodic_return": float(ep_return),
753
+ "rollout/episodic_length": int(ep_len),
754
+ "rollout/success": float(1.0 if succ else 0.0),
755
+ "rollout/max_tile": int(max_tile),
756
+ # 新增:每局按步均值的累计分与最终累计分
757
+ "rollout/score_mean": score_mean,
758
+ "rollout/final_score": final_score,
759
+ "rollout/success_rate_100": float(np.mean(ep_success_window)) if len(ep_success_window) > 0 else None,
760
+ # mirror PPO charts/* keys
761
+ "charts/episodic_return": float(ep_return),
762
+ "charts/episodic_length": int(ep_len),
763
+ "charts/success": float(1.0 if succ else 0.0),
764
+ "charts/max_tile": int(max_tile),
765
+ # 新增:charts 前缀版本
766
+ "charts/score_mean": score_mean,
767
+ "charts/final_score": final_score,
768
+ "charts/avg_episode_return": avg_ep_ret,
769
+ }, step=global_step)
770
+ except Exception:
771
+ pass
772
+ obs, info = env.reset()
773
+ current_info = info or {}
774
+ ep_return, ep_len = 0.0, 0
775
+ ep_scores = []
776
+
777
+ if global_step % 1000 == 0:
778
+ sps = int(global_step / (time.time() - start_time))
779
+ sr100 = float(np.mean(ep_success_window)) if len(ep_success_window) > 0 else 0.0
780
+ print(f"Step {global_step} | SPS: {sps} | Epsilon: {epsilon:.3f} | SR@100: {sr100:.3f}")
781
+
782
+ if (global_step % eval_every_steps == 0):
783
+ try:
784
+ def eval_thunk():
785
+ return make_env(run_name, args.seed + 9999, args, False)
786
+ collect_eval_trajectories(policy_net, eval_thunk, n_episodes=args.eval_episodes, step_tag=global_step)
787
+ if args.track:
788
+ try:
789
+ import wandb
790
+ mpath = Path(f"runs/{run_name}/trajectories/step_{global_step}/metrics.json")
791
+ if mpath.exists():
792
+ with mpath.open("r") as mf:
793
+ metrics = json.load(mf)
794
+ wandb.log({
795
+ "eval/success_rate": metrics.get("success_rate"),
796
+ "eval/avg_return": metrics.get("avg_return"),
797
+ "eval/std_return": metrics.get("std_return"),
798
+ "eval/episodes": metrics.get("episodes"),
799
+ }, step=global_step)
800
+ except Exception:
801
+ pass
802
+ print(f"Collected {args.eval_episodes} eval trajectories at step {global_step}")
803
+ except Exception as e:
804
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
805
+
806
+ env.close()
cleanrl/cleanrl/ppg_procgen.py ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/ppg/#ppg_procgenpy
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+
7
+ import gym
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.optim as optim
12
+ import tyro
13
+ from procgen import ProcgenEnv
14
+ from torch import distributions as td
15
+ from torch.distributions.categorical import Categorical
16
+ from torch.utils.tensorboard import SummaryWriter
17
+
18
+
19
+ @dataclass
20
+ class Args:
21
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
22
+ """the name of this experiment"""
23
+ seed: int = 1
24
+ """seed of the experiment"""
25
+ torch_deterministic: bool = True
26
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
27
+ cuda: bool = True
28
+ """if toggled, cuda will be enabled by default"""
29
+ track: bool = False
30
+ """if toggled, this experiment will be tracked with Weights and Biases"""
31
+ wandb_project_name: str = "cleanRL"
32
+ """the wandb's project name"""
33
+ wandb_entity: str = None
34
+ """the entity (team) of wandb's project"""
35
+ capture_video: bool = False
36
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
37
+
38
+ # Algorithm specific arguments
39
+ env_id: str = "starpilot"
40
+ """the id of the environment"""
41
+ total_timesteps: int = int(25e6)
42
+ """total timesteps of the experiments"""
43
+ learning_rate: float = 5e-4
44
+ """the learning rate of the optimizer"""
45
+ num_envs: int = 64
46
+ """the number of parallel game environments"""
47
+ num_steps: int = 256
48
+ """the number of steps to run in each environment per policy rollout"""
49
+ anneal_lr: bool = False
50
+ """Toggle learning rate annealing for policy and value networks"""
51
+ gamma: float = 0.999
52
+ """the discount factor gamma"""
53
+ gae_lambda: float = 0.95
54
+ """the lambda for the general advantage estimation"""
55
+ num_minibatches: int = 8
56
+ """the number of mini-batches"""
57
+ adv_norm_fullbatch: bool = True
58
+ """Toggle full batch advantage normalization as used in PPG code"""
59
+ clip_coef: float = 0.2
60
+ """the surrogate clipping coefficient"""
61
+ clip_vloss: bool = True
62
+ """Toggles whether or not to use a clipped loss for the value function, as per the paper."""
63
+ ent_coef: float = 0.01
64
+ """coefficient of the entropy"""
65
+ vf_coef: float = 0.5
66
+ """coefficient of the value function"""
67
+ max_grad_norm: float = 0.5
68
+ """the maximum norm for the gradient clipping"""
69
+ target_kl: float = None
70
+ """the target KL divergence threshold"""
71
+
72
+ # PPG specific arguments
73
+ n_iteration: int = 32
74
+ """N_pi: the number of policy update in the policy phase """
75
+ e_policy: int = 1
76
+ """E_pi: the number of policy update in the policy phase """
77
+ v_value: int = 1
78
+ """E_V: the number of policy update in the policy phase """
79
+ e_auxiliary: int = 6
80
+ """E_aux:the K epochs to update the policy"""
81
+ beta_clone: float = 1.0
82
+ """the behavior cloning coefficient"""
83
+ num_aux_rollouts: int = 4
84
+ """the number of mini batch in the auxiliary phase"""
85
+ n_aux_grad_accum: int = 1
86
+ """the number of gradient accumulation in mini batch"""
87
+
88
+ # to be filled in runtime
89
+ batch_size: int = 0
90
+ """the batch size (computed in runtime)"""
91
+ minibatch_size: int = 0
92
+ """the mini-batch size (computed in runtime)"""
93
+ num_iterations: int = 0
94
+ """the number of iterations (computed in runtime)"""
95
+ num_phases: int = 0
96
+ """the number of phases (computed in runtime)"""
97
+ aux_batch_rollouts: int = 0
98
+ """the number of rollouts in the auxiliary phase (computed in runtime)"""
99
+
100
+
101
+ def layer_init_normed(layer, norm_dim, scale=1.0):
102
+ with torch.no_grad():
103
+ layer.weight.data *= scale / layer.weight.norm(dim=norm_dim, p=2, keepdim=True)
104
+ layer.bias *= 0
105
+ return layer
106
+
107
+
108
+ def flatten01(arr):
109
+ return arr.reshape((-1, *arr.shape[2:]))
110
+
111
+
112
+ def unflatten01(arr, targetshape):
113
+ return arr.reshape((*targetshape, *arr.shape[1:]))
114
+
115
+
116
+ def flatten_unflatten_test():
117
+ a = torch.rand(400, 30, 100, 100, 5)
118
+ b = flatten01(a)
119
+ c = unflatten01(b, a.shape[:2])
120
+ assert torch.equal(a, c)
121
+
122
+
123
+ # taken from https://github.com/AIcrowd/neurips2020-procgen-starter-kit/blob/142d09586d2272a17f44481a115c4bd817cf6a94/models/impala_cnn_torch.py
124
+ class ResidualBlock(nn.Module):
125
+ def __init__(self, channels, scale):
126
+ super().__init__()
127
+ # scale = (1/3**0.5 * 1/2**0.5)**0.5 # For default IMPALA CNN this is the final scale value in the PPG code
128
+ scale = np.sqrt(scale)
129
+ conv0 = nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=3, padding=1)
130
+ self.conv0 = layer_init_normed(conv0, norm_dim=(1, 2, 3), scale=scale)
131
+ conv1 = nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=3, padding=1)
132
+ self.conv1 = layer_init_normed(conv1, norm_dim=(1, 2, 3), scale=scale)
133
+
134
+ def forward(self, x):
135
+ inputs = x
136
+ x = nn.functional.relu(x)
137
+ x = self.conv0(x)
138
+ x = nn.functional.relu(x)
139
+ x = self.conv1(x)
140
+ return x + inputs
141
+
142
+
143
+ class ConvSequence(nn.Module):
144
+ def __init__(self, input_shape, out_channels, scale):
145
+ super().__init__()
146
+ self._input_shape = input_shape
147
+ self._out_channels = out_channels
148
+ conv = nn.Conv2d(in_channels=self._input_shape[0], out_channels=self._out_channels, kernel_size=3, padding=1)
149
+ self.conv = layer_init_normed(conv, norm_dim=(1, 2, 3), scale=1.0)
150
+ nblocks = 2 # Set to the number of residual blocks
151
+ scale = scale / np.sqrt(nblocks)
152
+ self.res_block0 = ResidualBlock(self._out_channels, scale=scale)
153
+ self.res_block1 = ResidualBlock(self._out_channels, scale=scale)
154
+
155
+ def forward(self, x):
156
+ x = self.conv(x)
157
+ x = nn.functional.max_pool2d(x, kernel_size=3, stride=2, padding=1)
158
+ x = self.res_block0(x)
159
+ x = self.res_block1(x)
160
+ assert x.shape[1:] == self.get_output_shape()
161
+ return x
162
+
163
+ def get_output_shape(self):
164
+ _c, h, w = self._input_shape
165
+ return (self._out_channels, (h + 1) // 2, (w + 1) // 2)
166
+
167
+
168
+ class Agent(nn.Module):
169
+ def __init__(self, envs):
170
+ super().__init__()
171
+ h, w, c = envs.single_observation_space.shape
172
+ shape = (c, h, w)
173
+ conv_seqs = []
174
+ chans = [16, 32, 32]
175
+ scale = 1 / np.sqrt(len(chans)) # Not fully sure about the logic behind this but its used in PPG code
176
+ for out_channels in chans:
177
+ conv_seq = ConvSequence(shape, out_channels, scale=scale)
178
+ shape = conv_seq.get_output_shape()
179
+ conv_seqs.append(conv_seq)
180
+
181
+ encodertop = nn.Linear(in_features=shape[0] * shape[1] * shape[2], out_features=256)
182
+ encodertop = layer_init_normed(encodertop, norm_dim=1, scale=1.4)
183
+ conv_seqs += [
184
+ nn.Flatten(),
185
+ nn.ReLU(),
186
+ encodertop,
187
+ nn.ReLU(),
188
+ ]
189
+ self.network = nn.Sequential(*conv_seqs)
190
+ self.actor = layer_init_normed(nn.Linear(256, envs.single_action_space.n), norm_dim=1, scale=0.1)
191
+ self.critic = layer_init_normed(nn.Linear(256, 1), norm_dim=1, scale=0.1)
192
+ self.aux_critic = layer_init_normed(nn.Linear(256, 1), norm_dim=1, scale=0.1)
193
+
194
+ def get_action_and_value(self, x, action=None):
195
+ hidden = self.network(x.permute((0, 3, 1, 2)) / 255.0) # "bhwc" -> "bchw"
196
+ logits = self.actor(hidden)
197
+ probs = Categorical(logits=logits)
198
+ if action is None:
199
+ action = probs.sample()
200
+ return action, probs.log_prob(action), probs.entropy(), self.critic(hidden.detach())
201
+
202
+ def get_value(self, x):
203
+ return self.critic(self.network(x.permute((0, 3, 1, 2)) / 255.0)) # "bhwc" -> "bchw"
204
+
205
+ # PPG logic:
206
+ def get_pi_value_and_aux_value(self, x):
207
+ hidden = self.network(x.permute((0, 3, 1, 2)) / 255.0)
208
+ return Categorical(logits=self.actor(hidden)), self.critic(hidden.detach()), self.aux_critic(hidden)
209
+
210
+ def get_pi(self, x):
211
+ return Categorical(logits=self.actor(self.network(x.permute((0, 3, 1, 2)) / 255.0)))
212
+
213
+
214
+ if __name__ == "__main__":
215
+ args = tyro.cli(Args)
216
+ args.batch_size = int(args.num_envs * args.num_steps)
217
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
218
+ args.num_iterations = args.total_timesteps // args.batch_size
219
+ args.num_phases = int(args.num_iterations // args.n_iteration)
220
+ args.aux_batch_rollouts = int(args.num_envs * args.n_iteration)
221
+ assert args.v_value == 1, "Multiple value epoch (v_value != 1) is not supported yet"
222
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
223
+ if args.track:
224
+ import wandb
225
+
226
+ wandb.init(
227
+ project=args.wandb_project_name,
228
+ entity=args.wandb_entity,
229
+ sync_tensorboard=True,
230
+ config=vars(args),
231
+ name=run_name,
232
+ monitor_gym=True,
233
+ save_code=True,
234
+ )
235
+ writer = SummaryWriter(f"runs/{run_name}")
236
+ writer.add_text(
237
+ "hyperparameters",
238
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
239
+ )
240
+
241
+ flatten_unflatten_test() # Try not to mess with the flatten unflatten logic
242
+
243
+ # TRY NOT TO MODIFY: seeding
244
+ random.seed(args.seed)
245
+ np.random.seed(args.seed)
246
+ torch.manual_seed(args.seed)
247
+ torch.backends.cudnn.deterministic = args.torch_deterministic
248
+
249
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
250
+
251
+ # env setup
252
+ envs = ProcgenEnv(num_envs=args.num_envs, env_name=args.env_id, num_levels=0, start_level=0, distribution_mode="easy")
253
+ envs = gym.wrappers.TransformObservation(envs, lambda obs: obs["rgb"])
254
+ envs.single_action_space = envs.action_space
255
+ envs.single_observation_space = envs.observation_space["rgb"]
256
+ envs.is_vector_env = True
257
+ envs = gym.wrappers.RecordEpisodeStatistics(envs)
258
+ if args.capture_video:
259
+ envs = gym.wrappers.RecordVideo(envs, f"videos/{run_name}")
260
+ envs = gym.wrappers.NormalizeReward(envs, gamma=args.gamma)
261
+ envs = gym.wrappers.TransformReward(envs, lambda reward: np.clip(reward, -10, 10))
262
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
263
+
264
+ agent = Agent(envs).to(device)
265
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-8)
266
+
267
+ # ALGO Logic: Storage setup
268
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
269
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
270
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
271
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
272
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
273
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
274
+ aux_obs = torch.zeros(
275
+ (args.num_steps, args.aux_batch_rollouts) + envs.single_observation_space.shape, dtype=torch.uint8
276
+ ) # Saves lot system RAM
277
+ aux_returns = torch.zeros((args.num_steps, args.aux_batch_rollouts))
278
+
279
+ # TRY NOT TO MODIFY: start the game
280
+ global_step = 0
281
+ start_time = time.time()
282
+ next_obs = torch.Tensor(envs.reset()).to(device)
283
+ next_done = torch.zeros(args.num_envs).to(device)
284
+
285
+ for phase in range(1, args.num_phases + 1):
286
+
287
+ # POLICY PHASE
288
+ for update in range(1, args.n_iteration + 1):
289
+ # Annealing the rate if instructed to do so.
290
+ if args.anneal_lr:
291
+ frac = 1.0 - (update - 1.0) / args.num_iterations
292
+ lrnow = frac * args.learning_rate
293
+ optimizer.param_groups[0]["lr"] = lrnow
294
+
295
+ for step in range(0, args.num_steps):
296
+ global_step += 1 * args.num_envs
297
+ obs[step] = next_obs
298
+ dones[step] = next_done
299
+
300
+ # ALGO LOGIC: action logic
301
+ with torch.no_grad():
302
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
303
+ values[step] = value.flatten()
304
+ actions[step] = action
305
+ logprobs[step] = logprob
306
+
307
+ # TRY NOT TO MODIFY: execute the game and log data.
308
+ next_obs, reward, done, info = envs.step(action.cpu().numpy())
309
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
310
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(done).to(device)
311
+
312
+ for item in info:
313
+ if "episode" in item.keys():
314
+ print(f"global_step={global_step}, episodic_return={item['episode']['r']}")
315
+ writer.add_scalar("charts/episodic_return", item["episode"]["r"], global_step)
316
+ writer.add_scalar("charts/episodic_length", item["episode"]["l"], global_step)
317
+ break
318
+
319
+ # bootstrap value if not done
320
+ with torch.no_grad():
321
+ next_value = agent.get_value(next_obs).reshape(1, -1)
322
+ advantages = torch.zeros_like(rewards).to(device)
323
+ lastgaelam = 0
324
+ for t in reversed(range(args.num_steps)):
325
+ if t == args.num_steps - 1:
326
+ nextnonterminal = 1.0 - next_done
327
+ nextvalues = next_value
328
+ else:
329
+ nextnonterminal = 1.0 - dones[t + 1]
330
+ nextvalues = values[t + 1]
331
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
332
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
333
+ returns = advantages + values
334
+
335
+ # flatten the batch
336
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
337
+ b_logprobs = logprobs.reshape(-1)
338
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
339
+ b_advantages = advantages.reshape(-1)
340
+ b_returns = returns.reshape(-1)
341
+ b_values = values.reshape(-1)
342
+
343
+ # PPG code does full batch advantage normalization
344
+ if args.adv_norm_fullbatch:
345
+ b_advantages = (b_advantages - b_advantages.mean()) / (b_advantages.std() + 1e-8)
346
+
347
+ # Optimizing the policy and value network
348
+ b_inds = np.arange(args.batch_size)
349
+ clipfracs = []
350
+ for epoch in range(args.e_policy):
351
+ np.random.shuffle(b_inds)
352
+ for start in range(0, args.batch_size, args.minibatch_size):
353
+ end = start + args.minibatch_size
354
+ mb_inds = b_inds[start:end]
355
+
356
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
357
+ logratio = newlogprob - b_logprobs[mb_inds]
358
+ ratio = logratio.exp()
359
+
360
+ with torch.no_grad():
361
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
362
+ old_approx_kl = (-logratio).mean()
363
+ approx_kl = ((ratio - 1) - logratio).mean()
364
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
365
+
366
+ mb_advantages = b_advantages[mb_inds]
367
+
368
+ # Policy loss
369
+ pg_loss1 = -mb_advantages * ratio
370
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
371
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
372
+
373
+ # Value loss
374
+ newvalue = newvalue.view(-1)
375
+ if args.clip_vloss:
376
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
377
+ v_clipped = b_values[mb_inds] + torch.clamp(
378
+ newvalue - b_values[mb_inds],
379
+ -args.clip_coef,
380
+ args.clip_coef,
381
+ )
382
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
383
+ v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped)
384
+ v_loss = 0.5 * v_loss_max.mean()
385
+ else:
386
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
387
+
388
+ entropy_loss = entropy.mean()
389
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
390
+
391
+ optimizer.zero_grad()
392
+ loss.backward()
393
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
394
+ optimizer.step()
395
+
396
+ if args.target_kl is not None and approx_kl > args.target_kl:
397
+ break
398
+
399
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
400
+ var_y = np.var(y_true)
401
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
402
+
403
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
404
+ writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step)
405
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
406
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
407
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
408
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
409
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
410
+ writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step)
411
+ writer.add_scalar("losses/explained_variance", explained_var, global_step)
412
+ print("SPS:", int(global_step / (time.time() - start_time)))
413
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
414
+
415
+ # PPG Storage - Rollouts are saved without flattening for sampling full rollouts later:
416
+ storage_slice = slice(args.num_envs * (update - 1), args.num_envs * update)
417
+ aux_obs[:, storage_slice] = obs.cpu().clone().to(torch.uint8)
418
+ aux_returns[:, storage_slice] = returns.cpu().clone()
419
+
420
+ # AUXILIARY PHASE
421
+ aux_inds = np.arange(args.aux_batch_rollouts)
422
+
423
+ # Build the old policy on the aux buffer before distilling to the network
424
+ aux_pi = torch.zeros((args.num_steps, args.aux_batch_rollouts, envs.single_action_space.n))
425
+ for i, start in enumerate(range(0, args.aux_batch_rollouts, args.num_aux_rollouts)):
426
+ end = start + args.num_aux_rollouts
427
+ aux_minibatch_ind = aux_inds[start:end]
428
+ m_aux_obs = aux_obs[:, aux_minibatch_ind].to(torch.float32).to(device)
429
+ m_obs_shape = m_aux_obs.shape
430
+ m_aux_obs = flatten01(m_aux_obs)
431
+ with torch.no_grad():
432
+ pi_logits = agent.get_pi(m_aux_obs).logits.cpu().clone()
433
+ aux_pi[:, aux_minibatch_ind] = unflatten01(pi_logits, m_obs_shape[:2])
434
+ del m_aux_obs
435
+
436
+ for auxiliary_update in range(1, args.e_auxiliary + 1):
437
+ print(f"aux epoch {auxiliary_update}")
438
+ np.random.shuffle(aux_inds)
439
+ for i, start in enumerate(range(0, args.aux_batch_rollouts, args.num_aux_rollouts)):
440
+ end = start + args.num_aux_rollouts
441
+ aux_minibatch_ind = aux_inds[start:end]
442
+ try:
443
+ m_aux_obs = aux_obs[:, aux_minibatch_ind].to(device)
444
+ m_obs_shape = m_aux_obs.shape
445
+ m_aux_obs = flatten01(m_aux_obs) # Sample full rollouts for PPG instead of random indexes
446
+ m_aux_returns = aux_returns[:, aux_minibatch_ind].to(torch.float32).to(device)
447
+ m_aux_returns = flatten01(m_aux_returns)
448
+
449
+ new_pi, new_values, new_aux_values = agent.get_pi_value_and_aux_value(m_aux_obs)
450
+
451
+ new_values = new_values.view(-1)
452
+ new_aux_values = new_aux_values.view(-1)
453
+ old_pi_logits = flatten01(aux_pi[:, aux_minibatch_ind]).to(device)
454
+ old_pi = Categorical(logits=old_pi_logits)
455
+ kl_loss = td.kl_divergence(old_pi, new_pi).mean()
456
+
457
+ real_value_loss = 0.5 * ((new_values - m_aux_returns) ** 2).mean()
458
+ aux_value_loss = 0.5 * ((new_aux_values - m_aux_returns) ** 2).mean()
459
+ joint_loss = aux_value_loss + args.beta_clone * kl_loss
460
+
461
+ loss = (joint_loss + real_value_loss) / args.n_aux_grad_accum
462
+ loss.backward()
463
+
464
+ if (i + 1) % args.n_aux_grad_accum == 0:
465
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
466
+ optimizer.step()
467
+ optimizer.zero_grad() # This cannot be outside, else gradients won't accumulate
468
+
469
+ except RuntimeError as e:
470
+ raise Exception(
471
+ "if running out of CUDA memory, try a higher --n-aux-grad-accum, which trades more time for less gpu memory"
472
+ ) from e
473
+
474
+ del m_aux_obs, m_aux_returns
475
+ writer.add_scalar("losses/aux/kl_loss", kl_loss.mean().item(), global_step)
476
+ writer.add_scalar("losses/aux/aux_value_loss", aux_value_loss.item(), global_step)
477
+ writer.add_scalar("losses/aux/real_value_loss", real_value_loss.item(), global_step)
478
+
479
+ envs.close()
480
+ writer.close()
cleanrl/cleanrl/ppo.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/ppo/#ppopy
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+
7
+ import gymnasium as gym
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.optim as optim
12
+ import tyro
13
+ from torch.distributions.categorical import Categorical
14
+ from torch.utils.tensorboard import SummaryWriter
15
+
16
+
17
+ @dataclass
18
+ class Args:
19
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
20
+ """the name of this experiment"""
21
+ seed: int = 1
22
+ """seed of the experiment"""
23
+ torch_deterministic: bool = True
24
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
25
+ cuda: bool = True
26
+ """if toggled, cuda will be enabled by default"""
27
+ track: bool = False
28
+ """if toggled, this experiment will be tracked with Weights and Biases"""
29
+ wandb_project_name: str = "cleanRL"
30
+ """the wandb's project name"""
31
+ wandb_entity: str = None
32
+ """the entity (team) of wandb's project"""
33
+ capture_video: bool = False
34
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
35
+
36
+ # Algorithm specific arguments
37
+ env_id: str = "CartPole-v1"
38
+ """the id of the environment"""
39
+ total_timesteps: int = 500000
40
+ """total timesteps of the experiments"""
41
+ learning_rate: float = 2.5e-4
42
+ """the learning rate of the optimizer"""
43
+ num_envs: int = 4
44
+ """the number of parallel game environments"""
45
+ num_steps: int = 128
46
+ """the number of steps to run in each environment per policy rollout"""
47
+ anneal_lr: bool = True
48
+ """Toggle learning rate annealing for policy and value networks"""
49
+ gamma: float = 0.99
50
+ """the discount factor gamma"""
51
+ gae_lambda: float = 0.95
52
+ """the lambda for the general advantage estimation"""
53
+ num_minibatches: int = 4
54
+ """the number of mini-batches"""
55
+ update_epochs: int = 4
56
+ """the K epochs to update the policy"""
57
+ norm_adv: bool = True
58
+ """Toggles advantages normalization"""
59
+ clip_coef: float = 0.2
60
+ """the surrogate clipping coefficient"""
61
+ clip_vloss: bool = True
62
+ """Toggles whether or not to use a clipped loss for the value function, as per the paper."""
63
+ ent_coef: float = 0.01
64
+ """coefficient of the entropy"""
65
+ vf_coef: float = 0.5
66
+ """coefficient of the value function"""
67
+ max_grad_norm: float = 0.5
68
+ """the maximum norm for the gradient clipping"""
69
+ target_kl: float = None
70
+ """the target KL divergence threshold"""
71
+
72
+ # to be filled in runtime
73
+ batch_size: int = 0
74
+ """the batch size (computed in runtime)"""
75
+ minibatch_size: int = 0
76
+ """the mini-batch size (computed in runtime)"""
77
+ num_iterations: int = 0
78
+ """the number of iterations (computed in runtime)"""
79
+
80
+
81
+ def make_env(env_id, idx, capture_video, run_name):
82
+ def thunk():
83
+ if capture_video and idx == 0:
84
+ env = gym.make(env_id, render_mode="rgb_array")
85
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
86
+ else:
87
+ env = gym.make(env_id)
88
+ env = gym.wrappers.RecordEpisodeStatistics(env)
89
+ return env
90
+
91
+ return thunk
92
+
93
+
94
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
95
+ torch.nn.init.orthogonal_(layer.weight, std)
96
+ torch.nn.init.constant_(layer.bias, bias_const)
97
+ return layer
98
+
99
+
100
+ class Agent(nn.Module):
101
+ def __init__(self, envs):
102
+ super().__init__()
103
+ self.critic = nn.Sequential(
104
+ layer_init(nn.Linear(np.array(envs.single_observation_space.shape).prod(), 64)),
105
+ nn.Tanh(),
106
+ layer_init(nn.Linear(64, 64)),
107
+ nn.Tanh(),
108
+ layer_init(nn.Linear(64, 1), std=1.0),
109
+ )
110
+ self.actor = nn.Sequential(
111
+ layer_init(nn.Linear(np.array(envs.single_observation_space.shape).prod(), 64)),
112
+ nn.Tanh(),
113
+ layer_init(nn.Linear(64, 64)),
114
+ nn.Tanh(),
115
+ layer_init(nn.Linear(64, envs.single_action_space.n), std=0.01),
116
+ )
117
+
118
+ def get_value(self, x):
119
+ return self.critic(x)
120
+
121
+ def get_action_and_value(self, x, action=None):
122
+ logits = self.actor(x)
123
+ probs = Categorical(logits=logits)
124
+ if action is None:
125
+ action = probs.sample()
126
+ return action, probs.log_prob(action), probs.entropy(), self.critic(x)
127
+
128
+
129
+ if __name__ == "__main__":
130
+ args = tyro.cli(Args)
131
+ args.batch_size = int(args.num_envs * args.num_steps)
132
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
133
+ args.num_iterations = args.total_timesteps // args.batch_size
134
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
135
+ if args.track:
136
+ import wandb
137
+
138
+ wandb.init(
139
+ project=args.wandb_project_name,
140
+ entity=args.wandb_entity,
141
+ sync_tensorboard=True,
142
+ config=vars(args),
143
+ name=run_name,
144
+ monitor_gym=True,
145
+ save_code=True,
146
+ )
147
+ writer = SummaryWriter(f"runs/{run_name}")
148
+ writer.add_text(
149
+ "hyperparameters",
150
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
151
+ )
152
+
153
+ # TRY NOT TO MODIFY: seeding
154
+ random.seed(args.seed)
155
+ np.random.seed(args.seed)
156
+ torch.manual_seed(args.seed)
157
+ torch.backends.cudnn.deterministic = args.torch_deterministic
158
+
159
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
160
+
161
+ # env setup
162
+ envs = gym.vector.SyncVectorEnv(
163
+ [make_env(args.env_id, i, args.capture_video, run_name) for i in range(args.num_envs)],
164
+ )
165
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
166
+
167
+ agent = Agent(envs).to(device)
168
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
169
+
170
+ # ALGO Logic: Storage setup
171
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
172
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
173
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
174
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
175
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
176
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
177
+
178
+ # TRY NOT TO MODIFY: start the game
179
+ global_step = 0
180
+ start_time = time.time()
181
+ next_obs, _ = envs.reset(seed=args.seed)
182
+ next_obs = torch.Tensor(next_obs).to(device)
183
+ next_done = torch.zeros(args.num_envs).to(device)
184
+
185
+ for iteration in range(1, args.num_iterations + 1):
186
+ # Annealing the rate if instructed to do so.
187
+ if args.anneal_lr:
188
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
189
+ lrnow = frac * args.learning_rate
190
+ optimizer.param_groups[0]["lr"] = lrnow
191
+
192
+ for step in range(0, args.num_steps):
193
+ global_step += args.num_envs
194
+ obs[step] = next_obs
195
+ dones[step] = next_done
196
+
197
+ # ALGO LOGIC: action logic
198
+ with torch.no_grad():
199
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
200
+ values[step] = value.flatten()
201
+ actions[step] = action
202
+ logprobs[step] = logprob
203
+
204
+ # TRY NOT TO MODIFY: execute the game and log data.
205
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
206
+ next_done = np.logical_or(terminations, truncations)
207
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
208
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
209
+
210
+ if "final_info" in infos:
211
+ for info in infos["final_info"]:
212
+ if info and "episode" in info:
213
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
214
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
215
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
216
+
217
+ # bootstrap value if not done
218
+ with torch.no_grad():
219
+ next_value = agent.get_value(next_obs).reshape(1, -1)
220
+ advantages = torch.zeros_like(rewards).to(device)
221
+ lastgaelam = 0
222
+ for t in reversed(range(args.num_steps)):
223
+ if t == args.num_steps - 1:
224
+ nextnonterminal = 1.0 - next_done
225
+ nextvalues = next_value
226
+ else:
227
+ nextnonterminal = 1.0 - dones[t + 1]
228
+ nextvalues = values[t + 1]
229
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
230
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
231
+ returns = advantages + values
232
+
233
+ # flatten the batch
234
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
235
+ b_logprobs = logprobs.reshape(-1)
236
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
237
+ b_advantages = advantages.reshape(-1)
238
+ b_returns = returns.reshape(-1)
239
+ b_values = values.reshape(-1)
240
+
241
+ # Optimizing the policy and value network
242
+ b_inds = np.arange(args.batch_size)
243
+ clipfracs = []
244
+ for epoch in range(args.update_epochs):
245
+ np.random.shuffle(b_inds)
246
+ for start in range(0, args.batch_size, args.minibatch_size):
247
+ end = start + args.minibatch_size
248
+ mb_inds = b_inds[start:end]
249
+
250
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
251
+ logratio = newlogprob - b_logprobs[mb_inds]
252
+ ratio = logratio.exp()
253
+
254
+ with torch.no_grad():
255
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
256
+ old_approx_kl = (-logratio).mean()
257
+ approx_kl = ((ratio - 1) - logratio).mean()
258
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
259
+
260
+ mb_advantages = b_advantages[mb_inds]
261
+ if args.norm_adv:
262
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
263
+
264
+ # Policy loss
265
+ pg_loss1 = -mb_advantages * ratio
266
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
267
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
268
+
269
+ # Value loss
270
+ newvalue = newvalue.view(-1)
271
+ if args.clip_vloss:
272
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
273
+ v_clipped = b_values[mb_inds] + torch.clamp(
274
+ newvalue - b_values[mb_inds],
275
+ -args.clip_coef,
276
+ args.clip_coef,
277
+ )
278
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
279
+ v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped)
280
+ v_loss = 0.5 * v_loss_max.mean()
281
+ else:
282
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
283
+
284
+ entropy_loss = entropy.mean()
285
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
286
+
287
+ optimizer.zero_grad()
288
+ loss.backward()
289
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
290
+ optimizer.step()
291
+
292
+ if args.target_kl is not None and approx_kl > args.target_kl:
293
+ break
294
+
295
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
296
+ var_y = np.var(y_true)
297
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
298
+
299
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
300
+ writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step)
301
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
302
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
303
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
304
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
305
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
306
+ writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step)
307
+ writer.add_scalar("losses/explained_variance", explained_var, global_step)
308
+ print("SPS:", int(global_step / (time.time() - start_time)))
309
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
310
+
311
+ envs.close()
312
+ writer.close()
cleanrl/cleanrl/ppo_2048.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PPO (CNN actor-critic) for RAGEN 2048, matching NoisyNet DQN args and wandb logging
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Dict, Any, Tuple
8
+ from collections import deque
9
+
10
+ import gymnasium as gym
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.optim as optim
15
+ import torch.nn.functional as F
16
+ import tyro
17
+ import json
18
+
19
+ import sys
20
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../'))
21
+
22
+ # env and config
23
+ from ragen.env.game_2048.env import Game2048Env
24
+ from ragen.env.game_2048.config import Game2048EnvConfig
25
+
26
+
27
+ class Game2048Wrapper(gym.Env):
28
+ metadata = {"render_modes": ["text"]}
29
+
30
+ def __init__(self, env: Game2048Env, n_channels: int = 16):
31
+ super().__init__()
32
+ self._env = env
33
+ self._n_channels = int(n_channels)
34
+ self.observation_space = gym.spaces.Box(low=0.0, high=1.0, shape=(self._n_channels, 4, 4), dtype=np.float32)
35
+ self.action_space = self._env.action_space
36
+ self._last_info: Dict[str, Any] | None = None
37
+
38
+ def _encode_grid(self, grid: np.ndarray) -> np.ndarray:
39
+ grid_flat = grid.flatten()
40
+ with np.errstate(divide='ignore'):
41
+ power_grid = np.log2(grid_flat, where=(grid_flat > 0)).astype(int)
42
+ power_grid[grid_flat == 0] = 0
43
+ power_grid = np.clip(power_grid, 0, self._n_channels - 1)
44
+ one_hot = np.eye(self._n_channels)[power_grid]
45
+ obs = one_hot.reshape(4, 4, self._n_channels).transpose(2, 0, 1)
46
+ return obs.astype(np.float32)
47
+
48
+ def reset(self, *, seed: int | None = None, options: Dict[str, Any] | None = None):
49
+ text_obs, info = self._env.reset(seed=seed, options=options)
50
+ self._last_info = info
51
+ grid = info.get('grid', np.zeros((4, 4), dtype=np.int64))
52
+ obs = self._encode_grid(grid)
53
+ ret_info = {k: v for k, v in (info or {}).items() if k != 'grid'}
54
+ try:
55
+ ret_info['max_tile'] = int(np.max(grid))
56
+ except Exception:
57
+ ret_info['max_tile'] = int(ret_info.get('max_tile', 0))
58
+ return obs, ret_info
59
+
60
+ def step(self, action: int):
61
+ text_obs, reward, done, info = self._env.step(int(action))
62
+ self._last_info = info
63
+ grid = info.get('grid', np.zeros((4, 4), dtype=np.int64))
64
+ obs = self._encode_grid(grid)
65
+ ret_info = {k: v for k, v in (info or {}).items() if k != 'grid'}
66
+ try:
67
+ ret_info['max_tile'] = int(np.max(grid))
68
+ except Exception:
69
+ ret_info['max_tile'] = int(ret_info.get('max_tile', 0))
70
+ terminated = bool(done)
71
+ truncated = False
72
+ return obs, float(reward), terminated, truncated, ret_info
73
+
74
+ def get_action_mask(self) -> np.ndarray:
75
+ if self._last_info is None:
76
+ return np.ones((4,), dtype=bool)
77
+ mask = self._last_info.get('action_mask', None)
78
+ if mask is None:
79
+ return np.ones((4,), dtype=bool)
80
+ return np.asarray(mask, dtype=bool)
81
+
82
+ def render(self):
83
+ return self._env.render()
84
+
85
+ def close(self):
86
+ self._env.close()
87
+
88
+
89
+ @dataclass
90
+ class Args:
91
+ # mirror DQN args for wandb compatibility
92
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
93
+ seed: int = 1
94
+ torch_deterministic: bool = True
95
+ cuda: bool = True
96
+ track: bool = True
97
+ wandb_project_name: str = "2048-RL"
98
+ wandb_entity: str | None = None
99
+ capture_video: bool = False
100
+
101
+ # Algorithm identifiers
102
+ env_id: str = "Game2048PPO"
103
+ total_timesteps: int = 3_000_000
104
+ learning_rate: float = 2.5e-4
105
+ gamma: float = 0.997
106
+
107
+ # DQN-only args kept for wandb/backward-compat (unused here)
108
+ batch_size: int = 512
109
+ buffer_size: int = 2400_000
110
+ target_network_frequency: int = 15000
111
+ train_frequency: int = 4
112
+ learning_starts: int = 20_000
113
+ start_e: float = 1.0
114
+ end_e: float = 0.05
115
+ exploration_fraction: float = 0.8
116
+ dueling: bool = True
117
+ n_step: int = 10
118
+ per_alpha: float = 0.5
119
+ per_beta_start: float = 0.4
120
+ per_beta_frames: int = 1_000_000
121
+ per_eps: float = 1e-6
122
+
123
+ # Env config
124
+ two_prob: float = 0.9
125
+ max_steps_env: int = 1000
126
+
127
+ # Eval config
128
+ eval_splits: int = 1
129
+ eval_episodes: int = 400
130
+
131
+ # PPO specific
132
+ num_steps: int = 256
133
+ num_minibatches: int = 8
134
+ update_epochs: int = 4
135
+ gae_lambda: float = 0.95
136
+ clip_coef: float = 0.2
137
+ ent_coef: float = 0.01
138
+ vf_coef: float = 0.5
139
+ max_grad_norm: float = 0.5
140
+ anneal_lr: bool = True
141
+
142
+
143
+ def make_env(run_name: str, seed: int, args: Args, capture_video: bool = False):
144
+ cfg = Game2048EnvConfig(size=4, two_prob=args.two_prob, use_log_reward=True)
145
+ base = Game2048Env(cfg)
146
+ env = Game2048Wrapper(base)
147
+ env = gym.wrappers.TimeLimit(env, max_episode_steps=args.max_steps_env)
148
+ env = gym.wrappers.RecordEpisodeStatistics(env)
149
+ if capture_video:
150
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
151
+ return env
152
+
153
+
154
+ class ActorCriticCNN(nn.Module):
155
+ def __init__(self, obs_shape: Tuple[int, int, int], act_dim: int):
156
+ super().__init__()
157
+ c, h, w = obs_shape
158
+ self.features = nn.Sequential(
159
+ nn.Conv2d(c, 64, 2, 1, 0),
160
+ nn.ReLU(),
161
+ nn.Conv2d(64, 128, 2, 1, 1),
162
+ nn.ReLU(),
163
+ nn.Conv2d(128, 128, 2, 1, 0),
164
+ nn.ReLU(),
165
+ nn.Flatten(),
166
+ )
167
+ with torch.no_grad():
168
+ fc_in = int(self.features(torch.zeros(1, *obs_shape)).shape[1])
169
+ self.pi = nn.Sequential(
170
+ nn.Linear(fc_in, 512), nn.ReLU(), nn.Linear(512, act_dim)
171
+ )
172
+ self.v = nn.Sequential(
173
+ nn.Linear(fc_in, 512), nn.ReLU(), nn.Linear(512, 1)
174
+ )
175
+
176
+ def get_value(self, x):
177
+ x = self.features(x)
178
+ return self.v(x).squeeze(-1)
179
+
180
+ def get_action_and_value(self, x, action=None, action_mask=None):
181
+ x = self.features(x)
182
+ logits = self.pi(x)
183
+ if action_mask is not None:
184
+ mask = action_mask.bool()
185
+ logits = torch.where(mask, logits, torch.full_like(logits, -1e9))
186
+ probs = torch.distributions.Categorical(logits=logits)
187
+ if action is None:
188
+ action = probs.sample()
189
+ return action, probs.log_prob(action), probs.entropy(), self.v(x).squeeze(-1)
190
+
191
+
192
+ if __name__ == "__main__":
193
+ args = tyro.cli(Args)
194
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
195
+
196
+ if args.track:
197
+ import wandb
198
+ wandb.init(
199
+ project=args.wandb_project_name,
200
+ entity=args.wandb_entity,
201
+ config=vars(args),
202
+ name=run_name,
203
+ monitor_gym=True,
204
+ save_code=True,
205
+ )
206
+ try:
207
+ wandb.define_metric("global_step")
208
+ for prefix in ["train/*", "rollout/*", "eval/*", "losses/*", "charts/*", "perf/*"]:
209
+ wandb.define_metric(prefix, step_metric="global_step")
210
+ except Exception:
211
+ pass
212
+
213
+ random.seed(args.seed)
214
+ np.random.seed(args.seed)
215
+ torch.manual_seed(args.seed)
216
+ torch.backends.cudnn.deterministic = args.torch_deterministic
217
+
218
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
219
+
220
+ env = make_env(run_name, args.seed, args, args.capture_video)
221
+ obs_shape = env.observation_space.shape
222
+ act_dim = env.action_space.n
223
+
224
+ agent = ActorCriticCNN(obs_shape, act_dim).to(device)
225
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
226
+
227
+ # Storage
228
+ num_steps = args.num_steps
229
+ obs = np.zeros((num_steps,) + obs_shape, dtype=np.float32)
230
+ actions = np.zeros((num_steps,), dtype=np.int64)
231
+ logprobs = np.zeros((num_steps,), dtype=np.float32)
232
+ rewards = np.zeros((num_steps,), dtype=np.float32)
233
+ dones = np.zeros((num_steps,), dtype=np.float32)
234
+ values = np.zeros((num_steps,), dtype=np.float32)
235
+ masks_buf = np.zeros((num_steps, act_dim), dtype=bool)
236
+
237
+ global_step = 0
238
+ start_time = time.time()
239
+
240
+ next_obs, info = env.reset(seed=args.seed)
241
+ current_info = info or {}
242
+ next_done = False
243
+
244
+ ep_return = 0.0
245
+ ep_len = 0
246
+ ep_success_window = deque(maxlen=100)
247
+ ep_return_window = deque(maxlen=100)
248
+ step_reward_window = deque(maxlen=2048)
249
+
250
+ eval_every_steps = max(1, args.total_timesteps // args.eval_splits)
251
+
252
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes: int, step_tag: int):
253
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
254
+ out_dir.mkdir(parents=True, exist_ok=True)
255
+ out_path = out_dir / "trajectories.jsonl"
256
+ env_eval = make_env_fn()
257
+ collected = 0
258
+ summary_returns = []
259
+ summary_success = []
260
+ with out_path.open("w") as f:
261
+ while collected < n_episodes:
262
+ state, info = env_eval.reset(seed=args.seed + 100000 + collected)
263
+ current_info = info or {}
264
+ traj_states = [np.asarray(state).tolist()]
265
+ traj_actions = []
266
+ traj_rewards = []
267
+ traj_dones = []
268
+ traj_success = []
269
+ done = False
270
+ step_count = 0
271
+ max_eval_steps = getattr(env_eval, '_max_episode_steps', None) or args.max_steps_env
272
+ while not done:
273
+ with torch.no_grad():
274
+ s = torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0)
275
+ mask_np = current_info.get('action_mask', np.ones(act_dim, dtype=bool))
276
+ mask = torch.tensor(mask_np, dtype=torch.bool, device=device).unsqueeze(0)
277
+ logits = agent_model.pi(agent_model.features(s))
278
+ logits = torch.where(mask, logits, torch.full_like(logits, -1e9))
279
+ action = int(torch.argmax(logits, dim=1).item())
280
+ next_state, reward, terminated, truncated, info = env_eval.step(action)
281
+ traj_actions.append(int(action))
282
+ raw_r = info.get('raw_reward', reward) if info else reward
283
+ traj_rewards.append(float(raw_r))
284
+ step_count += 1
285
+ d = bool(terminated) or bool(truncated) or (step_count >= max_eval_steps)
286
+ traj_dones.append(d)
287
+ traj_success.append(bool((info or {}).get('success', False)))
288
+ state = next_state
289
+ current_info = info or {}
290
+ traj_states.append(np.asarray(state).tolist())
291
+ done = d
292
+ ep_ret = float(sum(traj_rewards))
293
+ ep_succ = bool(any(traj_success))
294
+ record = {
295
+ "states": traj_states,
296
+ "actions": traj_actions,
297
+ "rewards": traj_rewards,
298
+ "dones": traj_dones,
299
+ "success": traj_success,
300
+ "episode_return": ep_ret,
301
+ "episode_success": ep_succ,
302
+ }
303
+ f.write(json.dumps(record) + "\n")
304
+ collected += 1
305
+ summary_returns.append(ep_ret)
306
+ summary_success.append(1.0 if ep_succ else 0.0)
307
+ env_eval.close()
308
+ try:
309
+ metrics = {
310
+ "global_step": int(step_tag),
311
+ "episodes": int(n_episodes),
312
+ "success_rate": float(np.mean(summary_success)) if len(summary_success) else 0.0,
313
+ "avg_return": float(np.mean(summary_returns)) if len(summary_returns) else 0.0,
314
+ "std_return": float(np.std(summary_returns)) if len(summary_returns) else 0.0,
315
+ }
316
+ with (out_dir / "metrics.json").open("w") as mf:
317
+ json.dump(metrics, mf)
318
+ except Exception as e:
319
+ print(f"Warning: failed to write eval metrics: {e}")
320
+
321
+ num_updates = args.total_timesteps // num_steps
322
+
323
+ for update in range(1, num_updates + 1):
324
+ if args.anneal_lr:
325
+ frac = 1.0 - (update - 1.0) / float(max(1, num_updates))
326
+ lrnow = args.learning_rate * frac
327
+ for pg in optimizer.param_groups:
328
+ pg['lr'] = lrnow
329
+
330
+ for step in range(num_steps):
331
+ obs[step] = next_obs
332
+ dones[step] = float(next_done)
333
+ with torch.no_grad():
334
+ s = torch.tensor(next_obs, dtype=torch.float32, device=device).unsqueeze(0)
335
+ mask_np = current_info.get('action_mask', np.ones(act_dim, dtype=bool))
336
+ masks_buf[step] = mask_np
337
+ mask = torch.tensor(mask_np, dtype=torch.bool, device=device).unsqueeze(0)
338
+ a, lp, ent, val = agent.get_action_and_value(s, action_mask=mask)
339
+ action = int(a.item())
340
+ next_obs, reward, terminated, truncated, info = env.step(action)
341
+ done = bool(terminated) or bool(truncated)
342
+
343
+ rewards[step] = float(reward) # training reward (log-scale per env)
344
+ actions[step] = action
345
+ logprobs[step] = float(lp.item())
346
+ values[step] = float(val.item())
347
+
348
+ # logging raw reward for charts
349
+ raw_r = float((info or {}).get('raw_reward', reward))
350
+ ep_return += raw_r
351
+ try:
352
+ step_reward_window.append(float(reward))
353
+ except Exception:
354
+ pass
355
+ ep_len += 1
356
+ global_step += 1
357
+
358
+ if done:
359
+ succ = bool((info or {}).get('success', False))
360
+ max_tile = int((info or {}).get('max_tile', 0))
361
+ ep_success_window.append(1.0 if succ else 0.0)
362
+ ep_return_window.append(float(ep_return))
363
+ try:
364
+ if max_tile is not None:
365
+ print(f"global_step={global_step}, episodic_return={ep_return:.1f}, length={ep_len}, max_tile={int(max_tile)}, success={succ}")
366
+ else:
367
+ print(f"global_step={global_step}, episodic_return={ep_return:.1f}, length={ep_len}, success={succ}")
368
+ except Exception:
369
+ pass
370
+ if args.track:
371
+ try:
372
+ import wandb
373
+ avg_ep_ret = float(np.mean(ep_return_window)) if len(ep_return_window) > 0 else 0.0
374
+ wandb.log({
375
+ "global_step": int(global_step),
376
+ "rollout/episodic_return": float(ep_return),
377
+ "rollout/episodic_length": int(ep_len),
378
+ "rollout/success": float(1.0 if succ else 0.0),
379
+ "rollout/max_tile": int(max_tile),
380
+ "rollout/success_rate_100": float(np.mean(ep_success_window)) if len(ep_success_window) > 0 else None,
381
+ "charts/episodic_return": float(ep_return),
382
+ "charts/episodic_length": int(ep_len),
383
+ "charts/success": float(1.0 if succ else 0.0),
384
+ "charts/max_tile": int(max_tile),
385
+ "charts/avg_episode_return": avg_ep_ret,
386
+ }, step=global_step)
387
+ except Exception:
388
+ pass
389
+ next_obs, info = env.reset()
390
+ current_info = info or {}
391
+ ep_return, ep_len = 0.0, 0
392
+ else:
393
+ current_info = info or {}
394
+ next_done = False
395
+
396
+ if global_step % 1000 == 0:
397
+ sps = int(global_step / (time.time() - start_time))
398
+ sr100 = float(np.mean(ep_success_window)) if len(ep_success_window) > 0 else 0.0
399
+ print(f"Step {global_step} | SPS: {sps} | SR@100: {sr100:.3f}")
400
+
401
+ if (global_step % eval_every_steps == 0):
402
+ try:
403
+ def eval_thunk():
404
+ return make_env(run_name, args.seed + 9999, args, False)
405
+ collect_eval_trajectories(agent, eval_thunk, n_episodes=args.eval_episodes, step_tag=global_step)
406
+ if args.track:
407
+ try:
408
+ import wandb
409
+ mpath = Path(f"runs/{run_name}/trajectories/step_{global_step}/metrics.json")
410
+ if mpath.exists():
411
+ with mpath.open("r") as mf:
412
+ metrics = json.load(mf)
413
+ wandb.log({
414
+ "eval/success_rate": metrics.get("success_rate"),
415
+ "eval/avg_return": metrics.get("avg_return"),
416
+ "eval/std_return": metrics.get("std_return"),
417
+ "eval/episodes": metrics.get("episodes"),
418
+ }, step=global_step)
419
+ except Exception:
420
+ pass
421
+ print(f"Collected {args.eval_episodes} eval trajectories at step {global_step}")
422
+ except Exception as e:
423
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
424
+
425
+ # Compute GAE
426
+ with torch.no_grad():
427
+ s = torch.tensor(next_obs, dtype=torch.float32, device=device).unsqueeze(0)
428
+ next_value = agent.get_value(s).item()
429
+ advantages = np.zeros_like(rewards)
430
+ lastgaelam = 0.0
431
+ for t in reversed(range(num_steps)):
432
+ if t == num_steps - 1:
433
+ nextnonterminal = 1.0 - next_done
434
+ nextvalues = next_value
435
+ else:
436
+ nextnonterminal = 1.0 - dones[t + 1]
437
+ nextvalues = values[t + 1]
438
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
439
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
440
+ returns = advantages + values
441
+
442
+ # Flatten
443
+ b_obs = torch.tensor(obs, dtype=torch.float32, device=device)
444
+ b_actions = torch.tensor(actions, dtype=torch.int64, device=device)
445
+ b_logprobs = torch.tensor(logprobs, dtype=torch.float32, device=device)
446
+ b_returns = torch.tensor(returns, dtype=torch.float32, device=device)
447
+ b_values = torch.tensor(values, dtype=torch.float32, device=device)
448
+ b_advantages = torch.tensor(advantages, dtype=torch.float32, device=device)
449
+ b_masks = torch.tensor(masks_buf, dtype=torch.bool, device=device)
450
+
451
+ b_advantages = (b_advantages - b_advantages.mean()) / (b_advantages.std() + 1e-8)
452
+
453
+ # PPO epochs
454
+ batch_size = num_steps
455
+ minibatch_size = batch_size // args.num_minibatches
456
+ inds = np.arange(batch_size)
457
+ for epoch in range(args.update_epochs):
458
+ np.random.shuffle(inds)
459
+ for start in range(0, batch_size, minibatch_size):
460
+ end = start + minibatch_size
461
+ mb_inds = inds[start:end]
462
+
463
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(
464
+ b_obs[mb_inds], action=b_actions[mb_inds], action_mask=b_masks[mb_inds]
465
+ )
466
+ logratio = newlogprob - b_logprobs[mb_inds]
467
+ ratio = logratio.exp()
468
+ with torch.no_grad():
469
+ approx_kl = ((ratio - 1) - logratio).mean().item()
470
+ mb_adv = b_advantages[mb_inds]
471
+ pg_loss1 = -mb_adv * ratio
472
+ pg_loss2 = -mb_adv * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
473
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
474
+
475
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
476
+ v_clipped = b_values[mb_inds] + torch.clamp(
477
+ newvalue - b_values[mb_inds], -args.clip_coef, args.clip_coef
478
+ )
479
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
480
+ v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped).mean()
481
+ v_loss = 0.5 * v_loss_max
482
+
483
+ entropy_loss = entropy.mean()
484
+ loss = pg_loss - args.ent_coef * entropy_loss + args.vf_coef * v_loss
485
+
486
+ optimizer.zero_grad()
487
+ loss.backward()
488
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
489
+ optimizer.step()
490
+
491
+ if args.track:
492
+ try:
493
+ import wandb
494
+ try:
495
+ avg_reward_val = float(np.mean(step_reward_window)) if len(step_reward_window) > 0 else 0.0
496
+ except Exception:
497
+ avg_reward_val = 0.0
498
+ wandb.log({
499
+ "global_step": int(global_step),
500
+ "train/loss": float(loss.item()),
501
+ "train/value_loss": float(v_loss.item()),
502
+ "train/policy_loss": float(pg_loss.item()),
503
+ "train/entropy": float(entropy_loss.item()),
504
+ "losses/explained_variance": None,
505
+ "charts/avg_reward": avg_reward_val,
506
+ "charts/avg_value": float(b_values.mean().item()) if b_values.numel() > 0 else None,
507
+ "train/learning_rate": float(optimizer.param_groups[0]["lr"]),
508
+ "charts/epsilon": None,
509
+ "perf/SPS": int(global_step / (time.time() - start_time)),
510
+ }, step=global_step)
511
+ except Exception:
512
+ pass
513
+
514
+ env.close()
cleanrl/cleanrl/ppo_atari.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/ppo/#ppo_ataripy
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+
7
+ import gymnasium as gym
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.optim as optim
12
+ import tyro
13
+ from torch.distributions.categorical import Categorical
14
+ from torch.utils.tensorboard import SummaryWriter
15
+
16
+ from cleanrl_utils.atari_wrappers import ( # isort:skip
17
+ ClipRewardEnv,
18
+ EpisodicLifeEnv,
19
+ FireResetEnv,
20
+ MaxAndSkipEnv,
21
+ NoopResetEnv,
22
+ )
23
+
24
+
25
+ @dataclass
26
+ class Args:
27
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
28
+ """the name of this experiment"""
29
+ seed: int = 1
30
+ """seed of the experiment"""
31
+ torch_deterministic: bool = True
32
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
33
+ cuda: bool = True
34
+ """if toggled, cuda will be enabled by default"""
35
+ track: bool = False
36
+ """if toggled, this experiment will be tracked with Weights and Biases"""
37
+ wandb_project_name: str = "cleanRL"
38
+ """the wandb's project name"""
39
+ wandb_entity: str = None
40
+ """the entity (team) of wandb's project"""
41
+ capture_video: bool = False
42
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
43
+
44
+ # Algorithm specific arguments
45
+ env_id: str = "BreakoutNoFrameskip-v4"
46
+ """the id of the environment"""
47
+ total_timesteps: int = 10000000
48
+ """total timesteps of the experiments"""
49
+ learning_rate: float = 2.5e-4
50
+ """the learning rate of the optimizer"""
51
+ num_envs: int = 8
52
+ """the number of parallel game environments"""
53
+ num_steps: int = 128
54
+ """the number of steps to run in each environment per policy rollout"""
55
+ anneal_lr: bool = True
56
+ """Toggle learning rate annealing for policy and value networks"""
57
+ gamma: float = 0.99
58
+ """the discount factor gamma"""
59
+ gae_lambda: float = 0.95
60
+ """the lambda for the general advantage estimation"""
61
+ num_minibatches: int = 4
62
+ """the number of mini-batches"""
63
+ update_epochs: int = 4
64
+ """the K epochs to update the policy"""
65
+ norm_adv: bool = True
66
+ """Toggles advantages normalization"""
67
+ clip_coef: float = 0.1
68
+ """the surrogate clipping coefficient"""
69
+ clip_vloss: bool = True
70
+ """Toggles whether or not to use a clipped loss for the value function, as per the paper."""
71
+ ent_coef: float = 0.01
72
+ """coefficient of the entropy"""
73
+ vf_coef: float = 0.5
74
+ """coefficient of the value function"""
75
+ max_grad_norm: float = 0.5
76
+ """the maximum norm for the gradient clipping"""
77
+ target_kl: float = None
78
+ """the target KL divergence threshold"""
79
+
80
+ # to be filled in runtime
81
+ batch_size: int = 0
82
+ """the batch size (computed in runtime)"""
83
+ minibatch_size: int = 0
84
+ """the mini-batch size (computed in runtime)"""
85
+ num_iterations: int = 0
86
+ """the number of iterations (computed in runtime)"""
87
+
88
+
89
+ def make_env(env_id, idx, capture_video, run_name):
90
+ def thunk():
91
+ if capture_video and idx == 0:
92
+ env = gym.make(env_id, render_mode="rgb_array")
93
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
94
+ else:
95
+ env = gym.make(env_id)
96
+ env = gym.wrappers.RecordEpisodeStatistics(env)
97
+ env = NoopResetEnv(env, noop_max=30)
98
+ env = MaxAndSkipEnv(env, skip=4)
99
+ env = EpisodicLifeEnv(env)
100
+ if "FIRE" in env.unwrapped.get_action_meanings():
101
+ env = FireResetEnv(env)
102
+ env = ClipRewardEnv(env)
103
+ env = gym.wrappers.ResizeObservation(env, (84, 84))
104
+ env = gym.wrappers.GrayScaleObservation(env)
105
+ env = gym.wrappers.FrameStack(env, 4)
106
+ return env
107
+
108
+ return thunk
109
+
110
+
111
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
112
+ torch.nn.init.orthogonal_(layer.weight, std)
113
+ torch.nn.init.constant_(layer.bias, bias_const)
114
+ return layer
115
+
116
+
117
+ class Agent(nn.Module):
118
+ def __init__(self, envs):
119
+ super().__init__()
120
+ self.network = nn.Sequential(
121
+ layer_init(nn.Conv2d(4, 32, 8, stride=4)),
122
+ nn.ReLU(),
123
+ layer_init(nn.Conv2d(32, 64, 4, stride=2)),
124
+ nn.ReLU(),
125
+ layer_init(nn.Conv2d(64, 64, 3, stride=1)),
126
+ nn.ReLU(),
127
+ nn.Flatten(),
128
+ layer_init(nn.Linear(64 * 7 * 7, 512)),
129
+ nn.ReLU(),
130
+ )
131
+ self.actor = layer_init(nn.Linear(512, envs.single_action_space.n), std=0.01)
132
+ self.critic = layer_init(nn.Linear(512, 1), std=1)
133
+
134
+ def get_value(self, x):
135
+ return self.critic(self.network(x / 255.0))
136
+
137
+ def get_action_and_value(self, x, action=None):
138
+ hidden = self.network(x / 255.0)
139
+ logits = self.actor(hidden)
140
+ probs = Categorical(logits=logits)
141
+ if action is None:
142
+ action = probs.sample()
143
+ return action, probs.log_prob(action), probs.entropy(), self.critic(hidden)
144
+
145
+
146
+ if __name__ == "__main__":
147
+ args = tyro.cli(Args)
148
+ args.batch_size = int(args.num_envs * args.num_steps)
149
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
150
+ args.num_iterations = args.total_timesteps // args.batch_size
151
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
152
+ if args.track:
153
+ import wandb
154
+
155
+ wandb.init(
156
+ project=args.wandb_project_name,
157
+ entity=args.wandb_entity,
158
+ sync_tensorboard=True,
159
+ config=vars(args),
160
+ name=run_name,
161
+ monitor_gym=True,
162
+ save_code=True,
163
+ )
164
+ writer = SummaryWriter(f"runs/{run_name}")
165
+ writer.add_text(
166
+ "hyperparameters",
167
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
168
+ )
169
+
170
+ # TRY NOT TO MODIFY: seeding
171
+ random.seed(args.seed)
172
+ np.random.seed(args.seed)
173
+ torch.manual_seed(args.seed)
174
+ torch.backends.cudnn.deterministic = args.torch_deterministic
175
+
176
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
177
+
178
+ # env setup
179
+ envs = gym.vector.SyncVectorEnv(
180
+ [make_env(args.env_id, i, args.capture_video, run_name) for i in range(args.num_envs)],
181
+ )
182
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
183
+
184
+ agent = Agent(envs).to(device)
185
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
186
+
187
+ # ALGO Logic: Storage setup
188
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
189
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
190
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
191
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
192
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
193
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
194
+
195
+ # TRY NOT TO MODIFY: start the game
196
+ global_step = 0
197
+ start_time = time.time()
198
+ next_obs, _ = envs.reset(seed=args.seed)
199
+ next_obs = torch.Tensor(next_obs).to(device)
200
+ next_done = torch.zeros(args.num_envs).to(device)
201
+
202
+ for iteration in range(1, args.num_iterations + 1):
203
+ # Annealing the rate if instructed to do so.
204
+ if args.anneal_lr:
205
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
206
+ lrnow = frac * args.learning_rate
207
+ optimizer.param_groups[0]["lr"] = lrnow
208
+
209
+ for step in range(0, args.num_steps):
210
+ global_step += args.num_envs
211
+ obs[step] = next_obs
212
+ dones[step] = next_done
213
+
214
+ # ALGO LOGIC: action logic
215
+ with torch.no_grad():
216
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
217
+ values[step] = value.flatten()
218
+ actions[step] = action
219
+ logprobs[step] = logprob
220
+
221
+ # TRY NOT TO MODIFY: execute the game and log data.
222
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
223
+ next_done = np.logical_or(terminations, truncations)
224
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
225
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
226
+
227
+ if "final_info" in infos:
228
+ for info in infos["final_info"]:
229
+ if info and "episode" in info:
230
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
231
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
232
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
233
+
234
+ # bootstrap value if not done
235
+ with torch.no_grad():
236
+ next_value = agent.get_value(next_obs).reshape(1, -1)
237
+ advantages = torch.zeros_like(rewards).to(device)
238
+ lastgaelam = 0
239
+ for t in reversed(range(args.num_steps)):
240
+ if t == args.num_steps - 1:
241
+ nextnonterminal = 1.0 - next_done
242
+ nextvalues = next_value
243
+ else:
244
+ nextnonterminal = 1.0 - dones[t + 1]
245
+ nextvalues = values[t + 1]
246
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
247
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
248
+ returns = advantages + values
249
+
250
+ # flatten the batch
251
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
252
+ b_logprobs = logprobs.reshape(-1)
253
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
254
+ b_advantages = advantages.reshape(-1)
255
+ b_returns = returns.reshape(-1)
256
+ b_values = values.reshape(-1)
257
+
258
+ # Optimizing the policy and value network
259
+ b_inds = np.arange(args.batch_size)
260
+ clipfracs = []
261
+ for epoch in range(args.update_epochs):
262
+ np.random.shuffle(b_inds)
263
+ for start in range(0, args.batch_size, args.minibatch_size):
264
+ end = start + args.minibatch_size
265
+ mb_inds = b_inds[start:end]
266
+
267
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
268
+ logratio = newlogprob - b_logprobs[mb_inds]
269
+ ratio = logratio.exp()
270
+
271
+ with torch.no_grad():
272
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
273
+ old_approx_kl = (-logratio).mean()
274
+ approx_kl = ((ratio - 1) - logratio).mean()
275
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
276
+
277
+ mb_advantages = b_advantages[mb_inds]
278
+ if args.norm_adv:
279
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
280
+
281
+ # Policy loss
282
+ pg_loss1 = -mb_advantages * ratio
283
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
284
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
285
+
286
+ # Value loss
287
+ newvalue = newvalue.view(-1)
288
+ if args.clip_vloss:
289
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
290
+ v_clipped = b_values[mb_inds] + torch.clamp(
291
+ newvalue - b_values[mb_inds],
292
+ -args.clip_coef,
293
+ args.clip_coef,
294
+ )
295
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
296
+ v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped)
297
+ v_loss = 0.5 * v_loss_max.mean()
298
+ else:
299
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
300
+
301
+ entropy_loss = entropy.mean()
302
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
303
+
304
+ optimizer.zero_grad()
305
+ loss.backward()
306
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
307
+ optimizer.step()
308
+
309
+ if args.target_kl is not None and approx_kl > args.target_kl:
310
+ break
311
+
312
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
313
+ var_y = np.var(y_true)
314
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
315
+
316
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
317
+ writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step)
318
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
319
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
320
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
321
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
322
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
323
+ writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step)
324
+ writer.add_scalar("losses/explained_variance", explained_var, global_step)
325
+ print("SPS:", int(global_step / (time.time() - start_time)))
326
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
327
+
328
+ envs.close()
329
+ writer.close()
cleanrl/cleanrl/ppo_atari_envpool.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/ppo/#ppo_atari_envpoolpy
2
+ import os
3
+ import random
4
+ import time
5
+ from collections import deque
6
+ from dataclasses import dataclass
7
+
8
+ import envpool
9
+ import gym
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.optim as optim
14
+ import tyro
15
+ from torch.distributions.categorical import Categorical
16
+ from torch.utils.tensorboard import SummaryWriter
17
+
18
+
19
+ @dataclass
20
+ class Args:
21
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
22
+ """the name of this experiment"""
23
+ seed: int = 1
24
+ """seed of the experiment"""
25
+ torch_deterministic: bool = True
26
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
27
+ cuda: bool = True
28
+ """if toggled, cuda will be enabled by default"""
29
+ track: bool = False
30
+ """if toggled, this experiment will be tracked with Weights and Biases"""
31
+ wandb_project_name: str = "cleanRL"
32
+ """the wandb's project name"""
33
+ wandb_entity: str = None
34
+ """the entity (team) of wandb's project"""
35
+ capture_video: bool = False
36
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
37
+
38
+ # Algorithm specific arguments
39
+ env_id: str = "Breakout-v5"
40
+ """the id of the environment"""
41
+ total_timesteps: int = 10000000
42
+ """total timesteps of the experiments"""
43
+ learning_rate: float = 2.5e-4
44
+ """the learning rate of the optimizer"""
45
+ num_envs: int = 8
46
+ """the number of parallel game environments"""
47
+ num_steps: int = 128
48
+ """the number of steps to run in each environment per policy rollout"""
49
+ anneal_lr: bool = True
50
+ """Toggle learning rate annealing for policy and value networks"""
51
+ gamma: float = 0.99
52
+ """the discount factor gamma"""
53
+ gae_lambda: float = 0.95
54
+ """the lambda for the general advantage estimation"""
55
+ num_minibatches: int = 4
56
+ """the number of mini-batches"""
57
+ update_epochs: int = 4
58
+ """the K epochs to update the policy"""
59
+ norm_adv: bool = True
60
+ """Toggles advantages normalization"""
61
+ clip_coef: float = 0.1
62
+ """the surrogate clipping coefficient"""
63
+ clip_vloss: bool = True
64
+ """Toggles whether or not to use a clipped loss for the value function, as per the paper."""
65
+ ent_coef: float = 0.01
66
+ """coefficient of the entropy"""
67
+ vf_coef: float = 0.5
68
+ """coefficient of the value function"""
69
+ max_grad_norm: float = 0.5
70
+ """the maximum norm for the gradient clipping"""
71
+ target_kl: float = None
72
+ """the target KL divergence threshold"""
73
+
74
+ # to be filled in runtime
75
+ batch_size: int = 0
76
+ """the batch size (computed in runtime)"""
77
+ minibatch_size: int = 0
78
+ """the mini-batch size (computed in runtime)"""
79
+ num_iterations: int = 0
80
+ """the number of iterations (computed in runtime)"""
81
+
82
+
83
+ class RecordEpisodeStatistics(gym.Wrapper):
84
+ def __init__(self, env, deque_size=100):
85
+ super().__init__(env)
86
+ self.num_envs = getattr(env, "num_envs", 1)
87
+ self.episode_returns = None
88
+ self.episode_lengths = None
89
+
90
+ def reset(self, **kwargs):
91
+ observations = super().reset(**kwargs)
92
+ self.episode_returns = np.zeros(self.num_envs, dtype=np.float32)
93
+ self.episode_lengths = np.zeros(self.num_envs, dtype=np.int32)
94
+ self.lives = np.zeros(self.num_envs, dtype=np.int32)
95
+ self.returned_episode_returns = np.zeros(self.num_envs, dtype=np.float32)
96
+ self.returned_episode_lengths = np.zeros(self.num_envs, dtype=np.int32)
97
+ return observations
98
+
99
+ def step(self, action):
100
+ observations, rewards, dones, infos = super().step(action)
101
+ self.episode_returns += infos["reward"]
102
+ self.episode_lengths += 1
103
+ self.returned_episode_returns[:] = self.episode_returns
104
+ self.returned_episode_lengths[:] = self.episode_lengths
105
+ self.episode_returns *= 1 - infos["terminated"]
106
+ self.episode_lengths *= 1 - infos["terminated"]
107
+ infos["r"] = self.returned_episode_returns
108
+ infos["l"] = self.returned_episode_lengths
109
+ return (
110
+ observations,
111
+ rewards,
112
+ dones,
113
+ infos,
114
+ )
115
+
116
+
117
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
118
+ torch.nn.init.orthogonal_(layer.weight, std)
119
+ torch.nn.init.constant_(layer.bias, bias_const)
120
+ return layer
121
+
122
+
123
+ class Agent(nn.Module):
124
+ def __init__(self, envs):
125
+ super().__init__()
126
+ self.network = nn.Sequential(
127
+ layer_init(nn.Conv2d(4, 32, 8, stride=4)),
128
+ nn.ReLU(),
129
+ layer_init(nn.Conv2d(32, 64, 4, stride=2)),
130
+ nn.ReLU(),
131
+ layer_init(nn.Conv2d(64, 64, 3, stride=1)),
132
+ nn.ReLU(),
133
+ nn.Flatten(),
134
+ layer_init(nn.Linear(64 * 7 * 7, 512)),
135
+ nn.ReLU(),
136
+ )
137
+ self.actor = layer_init(nn.Linear(512, envs.single_action_space.n), std=0.01)
138
+ self.critic = layer_init(nn.Linear(512, 1), std=1)
139
+
140
+ def get_value(self, x):
141
+ return self.critic(self.network(x / 255.0))
142
+
143
+ def get_action_and_value(self, x, action=None):
144
+ hidden = self.network(x / 255.0)
145
+ logits = self.actor(hidden)
146
+ probs = Categorical(logits=logits)
147
+ if action is None:
148
+ action = probs.sample()
149
+ return action, probs.log_prob(action), probs.entropy(), self.critic(hidden)
150
+
151
+
152
+ if __name__ == "__main__":
153
+ args = tyro.cli(Args)
154
+ args.batch_size = int(args.num_envs * args.num_steps)
155
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
156
+ args.num_iterations = args.total_timesteps // args.batch_size
157
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
158
+ if args.track:
159
+ import wandb
160
+
161
+ wandb.init(
162
+ project=args.wandb_project_name,
163
+ entity=args.wandb_entity,
164
+ sync_tensorboard=True,
165
+ config=vars(args),
166
+ name=run_name,
167
+ monitor_gym=True,
168
+ save_code=True,
169
+ )
170
+ writer = SummaryWriter(f"runs/{run_name}")
171
+ writer.add_text(
172
+ "hyperparameters",
173
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
174
+ )
175
+
176
+ # TRY NOT TO MODIFY: seeding
177
+ random.seed(args.seed)
178
+ np.random.seed(args.seed)
179
+ torch.manual_seed(args.seed)
180
+ torch.backends.cudnn.deterministic = args.torch_deterministic
181
+
182
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
183
+
184
+ # env setup
185
+ envs = envpool.make(
186
+ args.env_id,
187
+ env_type="gym",
188
+ num_envs=args.num_envs,
189
+ episodic_life=True,
190
+ reward_clip=True,
191
+ seed=args.seed,
192
+ )
193
+ envs.num_envs = args.num_envs
194
+ envs.single_action_space = envs.action_space
195
+ envs.single_observation_space = envs.observation_space
196
+ envs = RecordEpisodeStatistics(envs)
197
+ assert isinstance(envs.action_space, gym.spaces.Discrete), "only discrete action space is supported"
198
+
199
+ agent = Agent(envs).to(device)
200
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
201
+
202
+ # ALGO Logic: Storage setup
203
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
204
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
205
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
206
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
207
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
208
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
209
+ avg_returns = deque(maxlen=20)
210
+
211
+ # TRY NOT TO MODIFY: start the game
212
+ global_step = 0
213
+ start_time = time.time()
214
+ next_obs = torch.Tensor(envs.reset()).to(device)
215
+ next_done = torch.zeros(args.num_envs).to(device)
216
+
217
+ for iteration in range(1, args.num_iterations + 1):
218
+ # Annealing the rate if instructed to do so.
219
+ if args.anneal_lr:
220
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
221
+ lrnow = frac * args.learning_rate
222
+ optimizer.param_groups[0]["lr"] = lrnow
223
+
224
+ for step in range(0, args.num_steps):
225
+ global_step += args.num_envs
226
+ obs[step] = next_obs
227
+ dones[step] = next_done
228
+
229
+ # ALGO LOGIC: action logic
230
+ with torch.no_grad():
231
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
232
+ values[step] = value.flatten()
233
+ actions[step] = action
234
+ logprobs[step] = logprob
235
+
236
+ # TRY NOT TO MODIFY: execute the game and log data.
237
+ next_obs, reward, next_done, info = envs.step(action.cpu().numpy())
238
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
239
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
240
+
241
+ for idx, d in enumerate(next_done):
242
+ if d and info["lives"][idx] == 0:
243
+ print(f"global_step={global_step}, episodic_return={info['r'][idx]}")
244
+ avg_returns.append(info["r"][idx])
245
+ writer.add_scalar("charts/avg_episodic_return", np.average(avg_returns), global_step)
246
+ writer.add_scalar("charts/episodic_return", info["r"][idx], global_step)
247
+ writer.add_scalar("charts/episodic_length", info["l"][idx], global_step)
248
+
249
+ # bootstrap value if not done
250
+ with torch.no_grad():
251
+ next_value = agent.get_value(next_obs).reshape(1, -1)
252
+ advantages = torch.zeros_like(rewards).to(device)
253
+ lastgaelam = 0
254
+ for t in reversed(range(args.num_steps)):
255
+ if t == args.num_steps - 1:
256
+ nextnonterminal = 1.0 - next_done
257
+ nextvalues = next_value
258
+ else:
259
+ nextnonterminal = 1.0 - dones[t + 1]
260
+ nextvalues = values[t + 1]
261
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
262
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
263
+ returns = advantages + values
264
+
265
+ # flatten the batch
266
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
267
+ b_logprobs = logprobs.reshape(-1)
268
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
269
+ b_advantages = advantages.reshape(-1)
270
+ b_returns = returns.reshape(-1)
271
+ b_values = values.reshape(-1)
272
+
273
+ # Optimizing the policy and value network
274
+ b_inds = np.arange(args.batch_size)
275
+ clipfracs = []
276
+ for epoch in range(args.update_epochs):
277
+ np.random.shuffle(b_inds)
278
+ for start in range(0, args.batch_size, args.minibatch_size):
279
+ end = start + args.minibatch_size
280
+ mb_inds = b_inds[start:end]
281
+
282
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
283
+ logratio = newlogprob - b_logprobs[mb_inds]
284
+ ratio = logratio.exp()
285
+
286
+ with torch.no_grad():
287
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
288
+ old_approx_kl = (-logratio).mean()
289
+ approx_kl = ((ratio - 1) - logratio).mean()
290
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
291
+
292
+ mb_advantages = b_advantages[mb_inds]
293
+ if args.norm_adv:
294
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
295
+
296
+ # Policy loss
297
+ pg_loss1 = -mb_advantages * ratio
298
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
299
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
300
+
301
+ # Value loss
302
+ newvalue = newvalue.view(-1)
303
+ if args.clip_vloss:
304
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
305
+ v_clipped = b_values[mb_inds] + torch.clamp(
306
+ newvalue - b_values[mb_inds],
307
+ -args.clip_coef,
308
+ args.clip_coef,
309
+ )
310
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
311
+ v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped)
312
+ v_loss = 0.5 * v_loss_max.mean()
313
+ else:
314
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
315
+
316
+ entropy_loss = entropy.mean()
317
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
318
+
319
+ optimizer.zero_grad()
320
+ loss.backward()
321
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
322
+ optimizer.step()
323
+
324
+ if args.target_kl is not None and approx_kl > args.target_kl:
325
+ break
326
+
327
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
328
+ var_y = np.var(y_true)
329
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
330
+
331
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
332
+ writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step)
333
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
334
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
335
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
336
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
337
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
338
+ writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step)
339
+ writer.add_scalar("losses/explained_variance", explained_var, global_step)
340
+ print("SPS:", int(global_step / (time.time() - start_time)))
341
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
342
+
343
+ envs.close()
344
+ writer.close()
cleanrl/cleanrl/ppo_atari_envpool_xla_jax.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/ppo/#ppo_atari_envpool_xla_jaxpy
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+ from typing import Sequence
7
+
8
+ import envpool
9
+ import flax
10
+ import flax.linen as nn
11
+ import gym
12
+ import jax
13
+ import jax.numpy as jnp
14
+ import numpy as np
15
+ import optax
16
+ import tyro
17
+ from flax.linen.initializers import constant, orthogonal
18
+ from flax.training.train_state import TrainState
19
+ from torch.utils.tensorboard import SummaryWriter
20
+
21
+ # Fix weird OOM https://github.com/google/jax/discussions/6332#discussioncomment-1279991
22
+ os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.6"
23
+ # Fix CUDNN non-determinisim; https://github.com/google/jax/issues/4823#issuecomment-952835771
24
+ os.environ["TF_XLA_FLAGS"] = "--xla_gpu_autotune_level=2 --xla_gpu_deterministic_reductions"
25
+ os.environ["TF_CUDNN DETERMINISTIC"] = "1"
26
+
27
+
28
+ @dataclass
29
+ class Args:
30
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
31
+ """the name of this experiment"""
32
+ seed: int = 1
33
+ """seed of the experiment"""
34
+ torch_deterministic: bool = True
35
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
36
+ cuda: bool = True
37
+ """if toggled, cuda will be enabled by default"""
38
+ track: bool = False
39
+ """if toggled, this experiment will be tracked with Weights and Biases"""
40
+ wandb_project_name: str = "cleanRL"
41
+ """the wandb's project name"""
42
+ wandb_entity: str = None
43
+ """the entity (team) of wandb's project"""
44
+ capture_video: bool = False
45
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
46
+
47
+ # Algorithm specific arguments
48
+ env_id: str = "Breakout-v5"
49
+ """the id of the environment"""
50
+ total_timesteps: int = 10000000
51
+ """total timesteps of the experiments"""
52
+ learning_rate: float = 2.5e-4
53
+ """the learning rate of the optimizer"""
54
+ num_envs: int = 8
55
+ """the number of parallel game environments"""
56
+ num_steps: int = 128
57
+ """the number of steps to run in each environment per policy rollout"""
58
+ anneal_lr: bool = True
59
+ """Toggle learning rate annealing for policy and value networks"""
60
+ gamma: float = 0.99
61
+ """the discount factor gamma"""
62
+ gae_lambda: float = 0.95
63
+ """the lambda for the general advantage estimation"""
64
+ num_minibatches: int = 4
65
+ """the number of mini-batches"""
66
+ update_epochs: int = 4
67
+ """the K epochs to update the policy"""
68
+ norm_adv: bool = True
69
+ """Toggles advantages normalization"""
70
+ clip_coef: float = 0.1
71
+ """the surrogate clipping coefficient"""
72
+ clip_vloss: bool = True
73
+ """Toggles whether or not to use a clipped loss for the value function, as per the paper."""
74
+ ent_coef: float = 0.01
75
+ """coefficient of the entropy"""
76
+ vf_coef: float = 0.5
77
+ """coefficient of the value function"""
78
+ max_grad_norm: float = 0.5
79
+ """the maximum norm for the gradient clipping"""
80
+ target_kl: float = None
81
+ """the target KL divergence threshold"""
82
+
83
+ # to be filled in runtime
84
+ batch_size: int = 0
85
+ """the batch size (computed in runtime)"""
86
+ minibatch_size: int = 0
87
+ """the mini-batch size (computed in runtime)"""
88
+ num_iterations: int = 0
89
+ """the number of iterations (computed in runtime)"""
90
+
91
+
92
+ class Network(nn.Module):
93
+ @nn.compact
94
+ def __call__(self, x):
95
+ x = jnp.transpose(x, (0, 2, 3, 1))
96
+ x = x / (255.0)
97
+ x = nn.Conv(
98
+ 32,
99
+ kernel_size=(8, 8),
100
+ strides=(4, 4),
101
+ padding="VALID",
102
+ kernel_init=orthogonal(np.sqrt(2)),
103
+ bias_init=constant(0.0),
104
+ )(x)
105
+ x = nn.relu(x)
106
+ x = nn.Conv(
107
+ 64,
108
+ kernel_size=(4, 4),
109
+ strides=(2, 2),
110
+ padding="VALID",
111
+ kernel_init=orthogonal(np.sqrt(2)),
112
+ bias_init=constant(0.0),
113
+ )(x)
114
+ x = nn.relu(x)
115
+ x = nn.Conv(
116
+ 64,
117
+ kernel_size=(3, 3),
118
+ strides=(1, 1),
119
+ padding="VALID",
120
+ kernel_init=orthogonal(np.sqrt(2)),
121
+ bias_init=constant(0.0),
122
+ )(x)
123
+ x = nn.relu(x)
124
+ x = x.reshape((x.shape[0], -1))
125
+ x = nn.Dense(512, kernel_init=orthogonal(np.sqrt(2)), bias_init=constant(0.0))(x)
126
+ x = nn.relu(x)
127
+ return x
128
+
129
+
130
+ class Critic(nn.Module):
131
+ @nn.compact
132
+ def __call__(self, x):
133
+ return nn.Dense(1, kernel_init=orthogonal(1), bias_init=constant(0.0))(x)
134
+
135
+
136
+ class Actor(nn.Module):
137
+ action_dim: Sequence[int]
138
+
139
+ @nn.compact
140
+ def __call__(self, x):
141
+ return nn.Dense(self.action_dim, kernel_init=orthogonal(0.01), bias_init=constant(0.0))(x)
142
+
143
+
144
+ @flax.struct.dataclass
145
+ class AgentParams:
146
+ network_params: flax.core.FrozenDict
147
+ actor_params: flax.core.FrozenDict
148
+ critic_params: flax.core.FrozenDict
149
+
150
+
151
+ @flax.struct.dataclass
152
+ class Storage:
153
+ obs: jnp.array
154
+ actions: jnp.array
155
+ logprobs: jnp.array
156
+ dones: jnp.array
157
+ values: jnp.array
158
+ advantages: jnp.array
159
+ returns: jnp.array
160
+ rewards: jnp.array
161
+
162
+
163
+ @flax.struct.dataclass
164
+ class EpisodeStatistics:
165
+ episode_returns: jnp.array
166
+ episode_lengths: jnp.array
167
+ returned_episode_returns: jnp.array
168
+ returned_episode_lengths: jnp.array
169
+
170
+
171
+ if __name__ == "__main__":
172
+ args = tyro.cli(Args)
173
+ args.batch_size = int(args.num_envs * args.num_steps)
174
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
175
+ args.num_iterations = args.total_timesteps // args.batch_size
176
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
177
+ if args.track:
178
+ import wandb
179
+
180
+ wandb.init(
181
+ project=args.wandb_project_name,
182
+ entity=args.wandb_entity,
183
+ sync_tensorboard=True,
184
+ config=vars(args),
185
+ name=run_name,
186
+ monitor_gym=True,
187
+ save_code=True,
188
+ )
189
+ writer = SummaryWriter(f"runs/{run_name}")
190
+ writer.add_text(
191
+ "hyperparameters",
192
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
193
+ )
194
+
195
+ # TRY NOT TO MODIFY: seeding
196
+ random.seed(args.seed)
197
+ np.random.seed(args.seed)
198
+ key = jax.random.PRNGKey(args.seed)
199
+ key, network_key, actor_key, critic_key = jax.random.split(key, 4)
200
+
201
+ # env setup
202
+ envs = envpool.make(
203
+ args.env_id,
204
+ env_type="gym",
205
+ num_envs=args.num_envs,
206
+ episodic_life=True,
207
+ reward_clip=True,
208
+ seed=args.seed,
209
+ )
210
+ envs.num_envs = args.num_envs
211
+ envs.single_action_space = envs.action_space
212
+ envs.single_observation_space = envs.observation_space
213
+ envs.is_vector_env = True
214
+ episode_stats = EpisodeStatistics(
215
+ episode_returns=jnp.zeros(args.num_envs, dtype=jnp.float32),
216
+ episode_lengths=jnp.zeros(args.num_envs, dtype=jnp.int32),
217
+ returned_episode_returns=jnp.zeros(args.num_envs, dtype=jnp.float32),
218
+ returned_episode_lengths=jnp.zeros(args.num_envs, dtype=jnp.int32),
219
+ )
220
+ handle, recv, send, step_env = envs.xla()
221
+
222
+ def step_env_wrappeed(episode_stats, handle, action):
223
+ handle, (next_obs, reward, next_done, info) = step_env(handle, action)
224
+ new_episode_return = episode_stats.episode_returns + info["reward"]
225
+ new_episode_length = episode_stats.episode_lengths + 1
226
+ episode_stats = episode_stats.replace(
227
+ episode_returns=(new_episode_return) * (1 - info["terminated"]) * (1 - info["TimeLimit.truncated"]),
228
+ episode_lengths=(new_episode_length) * (1 - info["terminated"]) * (1 - info["TimeLimit.truncated"]),
229
+ # only update the `returned_episode_returns` if the episode is done
230
+ returned_episode_returns=jnp.where(
231
+ info["terminated"] + info["TimeLimit.truncated"], new_episode_return, episode_stats.returned_episode_returns
232
+ ),
233
+ returned_episode_lengths=jnp.where(
234
+ info["terminated"] + info["TimeLimit.truncated"], new_episode_length, episode_stats.returned_episode_lengths
235
+ ),
236
+ )
237
+ return episode_stats, handle, (next_obs, reward, next_done, info)
238
+
239
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
240
+
241
+ def linear_schedule(count):
242
+ # anneal learning rate linearly after one training iteration which contains
243
+ # (args.num_minibatches * args.update_epochs) gradient updates
244
+ frac = 1.0 - (count // (args.num_minibatches * args.update_epochs)) / args.num_iterations
245
+ return args.learning_rate * frac
246
+
247
+ network = Network()
248
+ actor = Actor(action_dim=envs.single_action_space.n)
249
+ critic = Critic()
250
+ network_params = network.init(network_key, np.array([envs.single_observation_space.sample()]))
251
+ agent_state = TrainState.create(
252
+ apply_fn=None,
253
+ params=AgentParams(
254
+ network_params,
255
+ actor.init(actor_key, network.apply(network_params, np.array([envs.single_observation_space.sample()]))),
256
+ critic.init(critic_key, network.apply(network_params, np.array([envs.single_observation_space.sample()]))),
257
+ ),
258
+ tx=optax.chain(
259
+ optax.clip_by_global_norm(args.max_grad_norm),
260
+ optax.inject_hyperparams(optax.adam)(
261
+ learning_rate=linear_schedule if args.anneal_lr else args.learning_rate, eps=1e-5
262
+ ),
263
+ ),
264
+ )
265
+ network.apply = jax.jit(network.apply)
266
+ actor.apply = jax.jit(actor.apply)
267
+ critic.apply = jax.jit(critic.apply)
268
+
269
+ # ALGO Logic: Storage setup
270
+ storage = Storage(
271
+ obs=jnp.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape),
272
+ actions=jnp.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape, dtype=jnp.int32),
273
+ logprobs=jnp.zeros((args.num_steps, args.num_envs)),
274
+ dones=jnp.zeros((args.num_steps, args.num_envs)),
275
+ values=jnp.zeros((args.num_steps, args.num_envs)),
276
+ advantages=jnp.zeros((args.num_steps, args.num_envs)),
277
+ returns=jnp.zeros((args.num_steps, args.num_envs)),
278
+ rewards=jnp.zeros((args.num_steps, args.num_envs)),
279
+ )
280
+
281
+ @jax.jit
282
+ def get_action_and_value(
283
+ agent_state: TrainState,
284
+ next_obs: np.ndarray,
285
+ next_done: np.ndarray,
286
+ storage: Storage,
287
+ step: int,
288
+ key: jax.random.PRNGKey,
289
+ ):
290
+ """sample action, calculate value, logprob, entropy, and update storage"""
291
+ hidden = network.apply(agent_state.params.network_params, next_obs)
292
+ logits = actor.apply(agent_state.params.actor_params, hidden)
293
+ # sample action: Gumbel-softmax trick
294
+ # see https://stats.stackexchange.com/questions/359442/sampling-from-a-categorical-distribution
295
+ key, subkey = jax.random.split(key)
296
+ u = jax.random.uniform(subkey, shape=logits.shape)
297
+ action = jnp.argmax(logits - jnp.log(-jnp.log(u)), axis=1)
298
+ logprob = jax.nn.log_softmax(logits)[jnp.arange(action.shape[0]), action]
299
+ value = critic.apply(agent_state.params.critic_params, hidden)
300
+ storage = storage.replace(
301
+ obs=storage.obs.at[step].set(next_obs),
302
+ dones=storage.dones.at[step].set(next_done),
303
+ actions=storage.actions.at[step].set(action),
304
+ logprobs=storage.logprobs.at[step].set(logprob),
305
+ values=storage.values.at[step].set(value.squeeze()),
306
+ )
307
+ return storage, action, key
308
+
309
+ @jax.jit
310
+ def get_action_and_value2(
311
+ params: flax.core.FrozenDict,
312
+ x: np.ndarray,
313
+ action: np.ndarray,
314
+ ):
315
+ """calculate value, logprob of supplied `action`, and entropy"""
316
+ hidden = network.apply(params.network_params, x)
317
+ logits = actor.apply(params.actor_params, hidden)
318
+ logprob = jax.nn.log_softmax(logits)[jnp.arange(action.shape[0]), action]
319
+ # normalize the logits https://gregorygundersen.com/blog/2020/02/09/log-sum-exp/
320
+ logits = logits - jax.scipy.special.logsumexp(logits, axis=-1, keepdims=True)
321
+ logits = logits.clip(min=jnp.finfo(logits.dtype).min)
322
+ p_log_p = logits * jax.nn.softmax(logits)
323
+ entropy = -p_log_p.sum(-1)
324
+ value = critic.apply(params.critic_params, hidden).squeeze()
325
+ return logprob, entropy, value
326
+
327
+ @jax.jit
328
+ def compute_gae(
329
+ agent_state: TrainState,
330
+ next_obs: np.ndarray,
331
+ next_done: np.ndarray,
332
+ storage: Storage,
333
+ ):
334
+ storage = storage.replace(advantages=storage.advantages.at[:].set(0.0))
335
+ next_value = critic.apply(
336
+ agent_state.params.critic_params, network.apply(agent_state.params.network_params, next_obs)
337
+ ).squeeze()
338
+ lastgaelam = 0
339
+ for t in reversed(range(args.num_steps)):
340
+ if t == args.num_steps - 1:
341
+ nextnonterminal = 1.0 - next_done
342
+ nextvalues = next_value
343
+ else:
344
+ nextnonterminal = 1.0 - storage.dones[t + 1]
345
+ nextvalues = storage.values[t + 1]
346
+ delta = storage.rewards[t] + args.gamma * nextvalues * nextnonterminal - storage.values[t]
347
+ lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
348
+ storage = storage.replace(advantages=storage.advantages.at[t].set(lastgaelam))
349
+ storage = storage.replace(returns=storage.advantages + storage.values)
350
+ return storage
351
+
352
+ @jax.jit
353
+ def update_ppo(
354
+ agent_state: TrainState,
355
+ storage: Storage,
356
+ key: jax.random.PRNGKey,
357
+ ):
358
+ b_obs = storage.obs.reshape((-1,) + envs.single_observation_space.shape)
359
+ b_logprobs = storage.logprobs.reshape(-1)
360
+ b_actions = storage.actions.reshape((-1,) + envs.single_action_space.shape)
361
+ b_advantages = storage.advantages.reshape(-1)
362
+ b_returns = storage.returns.reshape(-1)
363
+
364
+ def ppo_loss(params, x, a, logp, mb_advantages, mb_returns):
365
+ newlogprob, entropy, newvalue = get_action_and_value2(params, x, a)
366
+ logratio = newlogprob - logp
367
+ ratio = jnp.exp(logratio)
368
+ approx_kl = ((ratio - 1) - logratio).mean()
369
+
370
+ if args.norm_adv:
371
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
372
+
373
+ # Policy loss
374
+ pg_loss1 = -mb_advantages * ratio
375
+ pg_loss2 = -mb_advantages * jnp.clip(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
376
+ pg_loss = jnp.maximum(pg_loss1, pg_loss2).mean()
377
+
378
+ # Value loss
379
+ v_loss = 0.5 * ((newvalue - mb_returns) ** 2).mean()
380
+
381
+ entropy_loss = entropy.mean()
382
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
383
+ return loss, (pg_loss, v_loss, entropy_loss, jax.lax.stop_gradient(approx_kl))
384
+
385
+ ppo_loss_grad_fn = jax.value_and_grad(ppo_loss, has_aux=True)
386
+ for _ in range(args.update_epochs):
387
+ key, subkey = jax.random.split(key)
388
+ b_inds = jax.random.permutation(subkey, args.batch_size, independent=True)
389
+ for start in range(0, args.batch_size, args.minibatch_size):
390
+ end = start + args.minibatch_size
391
+ mb_inds = b_inds[start:end]
392
+ (loss, (pg_loss, v_loss, entropy_loss, approx_kl)), grads = ppo_loss_grad_fn(
393
+ agent_state.params,
394
+ b_obs[mb_inds],
395
+ b_actions[mb_inds],
396
+ b_logprobs[mb_inds],
397
+ b_advantages[mb_inds],
398
+ b_returns[mb_inds],
399
+ )
400
+ agent_state = agent_state.apply_gradients(grads=grads)
401
+ return agent_state, loss, pg_loss, v_loss, entropy_loss, approx_kl, key
402
+
403
+ # TRY NOT TO MODIFY: start the game
404
+ global_step = 0
405
+ start_time = time.time()
406
+ next_obs = envs.reset()
407
+ next_done = np.zeros(args.num_envs)
408
+
409
+ @jax.jit
410
+ def rollout(agent_state, episode_stats, next_obs, next_done, storage, key, handle, global_step):
411
+ for step in range(0, args.num_steps):
412
+ global_step += args.num_envs
413
+ storage, action, key = get_action_and_value(agent_state, next_obs, next_done, storage, step, key)
414
+
415
+ # TRY NOT TO MODIFY: execute the game and log data.
416
+ episode_stats, handle, (next_obs, reward, next_done, _) = step_env_wrappeed(episode_stats, handle, action)
417
+ storage = storage.replace(rewards=storage.rewards.at[step].set(reward))
418
+ return agent_state, episode_stats, next_obs, next_done, storage, key, handle, global_step
419
+
420
+ for iteration in range(1, args.num_iterations + 1):
421
+ iteration_time_start = time.time()
422
+ agent_state, episode_stats, next_obs, next_done, storage, key, handle, global_step = rollout(
423
+ agent_state, episode_stats, next_obs, next_done, storage, key, handle, global_step
424
+ )
425
+ storage = compute_gae(agent_state, next_obs, next_done, storage)
426
+ agent_state, loss, pg_loss, v_loss, entropy_loss, approx_kl, key = update_ppo(
427
+ agent_state,
428
+ storage,
429
+ key,
430
+ )
431
+ avg_episodic_return = np.mean(jax.device_get(episode_stats.returned_episode_returns))
432
+ print(f"global_step={global_step}, avg_episodic_return={avg_episodic_return}")
433
+
434
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
435
+ writer.add_scalar("charts/avg_episodic_return", avg_episodic_return, global_step)
436
+ writer.add_scalar(
437
+ "charts/avg_episodic_length", np.mean(jax.device_get(episode_stats.returned_episode_lengths)), global_step
438
+ )
439
+ writer.add_scalar("charts/learning_rate", agent_state.opt_state[1].hyperparams["learning_rate"].item(), global_step)
440
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
441
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
442
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
443
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
444
+ writer.add_scalar("losses/loss", loss.item(), global_step)
445
+ print("SPS:", int(global_step / (time.time() - start_time)))
446
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
447
+ writer.add_scalar(
448
+ "charts/SPS_update", int(args.num_envs * args.num_steps / (time.time() - iteration_time_start)), global_step
449
+ )
450
+
451
+ envs.close()
452
+ writer.close()
cleanrl/cleanrl/ppo_atari_envpool_xla_jax_scan.py ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/ppo/#ppo_atari_envpool_xla_jaxpy
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+ from functools import partial
7
+ from typing import Sequence
8
+
9
+ import envpool
10
+ import flax
11
+ import flax.linen as nn
12
+ import gym
13
+ import jax
14
+ import jax.numpy as jnp
15
+ import numpy as np
16
+ import optax
17
+ import tyro
18
+ from flax.linen.initializers import constant, orthogonal
19
+ from flax.training.train_state import TrainState
20
+ from torch.utils.tensorboard import SummaryWriter
21
+
22
+ # Fix weird OOM https://github.com/google/jax/discussions/6332#discussioncomment-1279991
23
+ os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.6"
24
+ # Fix CUDNN non-determinisim; https://github.com/google/jax/issues/4823#issuecomment-952835771
25
+ os.environ["TF_XLA_FLAGS"] = "--xla_gpu_autotune_level=2 --xla_gpu_deterministic_reductions"
26
+ os.environ["TF_CUDNN DETERMINISTIC"] = "1"
27
+
28
+
29
+ @dataclass
30
+ class Args:
31
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
32
+ """the name of this experiment"""
33
+ seed: int = 1
34
+ """seed of the experiment"""
35
+ torch_deterministic: bool = True
36
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
37
+ cuda: bool = True
38
+ """if toggled, cuda will be enabled by default"""
39
+ track: bool = False
40
+ """if toggled, this experiment will be tracked with Weights and Biases"""
41
+ wandb_project_name: str = "cleanRL"
42
+ """the wandb's project name"""
43
+ wandb_entity: str = None
44
+ """the entity (team) of wandb's project"""
45
+ capture_video: bool = False
46
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
47
+ save_model: bool = False
48
+ """whether to save model into the `runs/{run_name}` folder"""
49
+ upload_model: bool = False
50
+ """whether to upload the saved model to huggingface"""
51
+ hf_entity: str = ""
52
+ """the user or org name of the model repository from the Hugging Face Hub"""
53
+
54
+ # Algorithm specific arguments
55
+ env_id: str = "Breakout-v5"
56
+ """the id of the environment"""
57
+ total_timesteps: int = 10000000
58
+ """total timesteps of the experiments"""
59
+ learning_rate: float = 2.5e-4
60
+ """the learning rate of the optimizer"""
61
+ num_envs: int = 8
62
+ """the number of parallel game environments"""
63
+ num_steps: int = 128
64
+ """the number of steps to run in each environment per policy rollout"""
65
+ anneal_lr: bool = True
66
+ """Toggle learning rate annealing for policy and value networks"""
67
+ gamma: float = 0.99
68
+ """the discount factor gamma"""
69
+ gae_lambda: float = 0.95
70
+ """the lambda for the general advantage estimation"""
71
+ num_minibatches: int = 4
72
+ """the number of mini-batches"""
73
+ update_epochs: int = 4
74
+ """the K epochs to update the policy"""
75
+ norm_adv: bool = True
76
+ """Toggles advantages normalization"""
77
+ clip_coef: float = 0.1
78
+ """the surrogate clipping coefficient"""
79
+ clip_vloss: bool = True
80
+ """Toggles whether or not to use a clipped loss for the value function, as per the paper."""
81
+ ent_coef: float = 0.01
82
+ """coefficient of the entropy"""
83
+ vf_coef: float = 0.5
84
+ """coefficient of the value function"""
85
+ max_grad_norm: float = 0.5
86
+ """the maximum norm for the gradient clipping"""
87
+ target_kl: float = None
88
+ """the target KL divergence threshold"""
89
+
90
+ # to be filled in runtime
91
+ batch_size: int = 0
92
+ """the batch size (computed in runtime)"""
93
+ minibatch_size: int = 0
94
+ """the mini-batch size (computed in runtime)"""
95
+ num_iterations: int = 0
96
+ """the number of iterations (computed in runtime)"""
97
+
98
+
99
+ def make_env(env_id, seed, num_envs):
100
+ def thunk():
101
+ envs = envpool.make(
102
+ env_id,
103
+ env_type="gym",
104
+ num_envs=num_envs,
105
+ episodic_life=True,
106
+ reward_clip=True,
107
+ seed=seed,
108
+ )
109
+ envs.num_envs = num_envs
110
+ envs.single_action_space = envs.action_space
111
+ envs.single_observation_space = envs.observation_space
112
+ envs.is_vector_env = True
113
+ return envs
114
+
115
+ return thunk
116
+
117
+
118
+ class Network(nn.Module):
119
+ @nn.compact
120
+ def __call__(self, x):
121
+ x = jnp.transpose(x, (0, 2, 3, 1))
122
+ x = x / (255.0)
123
+ x = nn.Conv(
124
+ 32,
125
+ kernel_size=(8, 8),
126
+ strides=(4, 4),
127
+ padding="VALID",
128
+ kernel_init=orthogonal(np.sqrt(2)),
129
+ bias_init=constant(0.0),
130
+ )(x)
131
+ x = nn.relu(x)
132
+ x = nn.Conv(
133
+ 64,
134
+ kernel_size=(4, 4),
135
+ strides=(2, 2),
136
+ padding="VALID",
137
+ kernel_init=orthogonal(np.sqrt(2)),
138
+ bias_init=constant(0.0),
139
+ )(x)
140
+ x = nn.relu(x)
141
+ x = nn.Conv(
142
+ 64,
143
+ kernel_size=(3, 3),
144
+ strides=(1, 1),
145
+ padding="VALID",
146
+ kernel_init=orthogonal(np.sqrt(2)),
147
+ bias_init=constant(0.0),
148
+ )(x)
149
+ x = nn.relu(x)
150
+ x = x.reshape((x.shape[0], -1))
151
+ x = nn.Dense(512, kernel_init=orthogonal(np.sqrt(2)), bias_init=constant(0.0))(x)
152
+ x = nn.relu(x)
153
+ return x
154
+
155
+
156
+ class Critic(nn.Module):
157
+ @nn.compact
158
+ def __call__(self, x):
159
+ return nn.Dense(1, kernel_init=orthogonal(1), bias_init=constant(0.0))(x)
160
+
161
+
162
+ class Actor(nn.Module):
163
+ action_dim: Sequence[int]
164
+
165
+ @nn.compact
166
+ def __call__(self, x):
167
+ return nn.Dense(self.action_dim, kernel_init=orthogonal(0.01), bias_init=constant(0.0))(x)
168
+
169
+
170
+ @flax.struct.dataclass
171
+ class AgentParams:
172
+ network_params: flax.core.FrozenDict
173
+ actor_params: flax.core.FrozenDict
174
+ critic_params: flax.core.FrozenDict
175
+
176
+
177
+ @flax.struct.dataclass
178
+ class Storage:
179
+ obs: jnp.array
180
+ actions: jnp.array
181
+ logprobs: jnp.array
182
+ dones: jnp.array
183
+ values: jnp.array
184
+ advantages: jnp.array
185
+ returns: jnp.array
186
+ rewards: jnp.array
187
+
188
+
189
+ @flax.struct.dataclass
190
+ class EpisodeStatistics:
191
+ episode_returns: jnp.array
192
+ episode_lengths: jnp.array
193
+ returned_episode_returns: jnp.array
194
+ returned_episode_lengths: jnp.array
195
+
196
+
197
+ if __name__ == "__main__":
198
+ args = tyro.cli(Args)
199
+ args.batch_size = int(args.num_envs * args.num_steps)
200
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
201
+ args.num_iterations = args.total_timesteps // args.batch_size
202
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
203
+ if args.track:
204
+ import wandb
205
+
206
+ wandb.init(
207
+ project=args.wandb_project_name,
208
+ entity=args.wandb_entity,
209
+ sync_tensorboard=True,
210
+ config=vars(args),
211
+ name=run_name,
212
+ monitor_gym=True,
213
+ save_code=True,
214
+ )
215
+ writer = SummaryWriter(f"runs/{run_name}")
216
+ writer.add_text(
217
+ "hyperparameters",
218
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
219
+ )
220
+
221
+ # TRY NOT TO MODIFY: seeding
222
+ random.seed(args.seed)
223
+ np.random.seed(args.seed)
224
+ key = jax.random.PRNGKey(args.seed)
225
+ key, network_key, actor_key, critic_key = jax.random.split(key, 4)
226
+
227
+ # env setup
228
+ envs = make_env(args.env_id, args.seed, args.num_envs)()
229
+ episode_stats = EpisodeStatistics(
230
+ episode_returns=jnp.zeros(args.num_envs, dtype=jnp.float32),
231
+ episode_lengths=jnp.zeros(args.num_envs, dtype=jnp.int32),
232
+ returned_episode_returns=jnp.zeros(args.num_envs, dtype=jnp.float32),
233
+ returned_episode_lengths=jnp.zeros(args.num_envs, dtype=jnp.int32),
234
+ )
235
+ handle, recv, send, step_env = envs.xla()
236
+
237
+ def step_env_wrappeed(episode_stats, handle, action):
238
+ handle, (next_obs, reward, next_done, info) = step_env(handle, action)
239
+ new_episode_return = episode_stats.episode_returns + info["reward"]
240
+ new_episode_length = episode_stats.episode_lengths + 1
241
+ episode_stats = episode_stats.replace(
242
+ episode_returns=(new_episode_return) * (1 - info["terminated"]) * (1 - info["TimeLimit.truncated"]),
243
+ episode_lengths=(new_episode_length) * (1 - info["terminated"]) * (1 - info["TimeLimit.truncated"]),
244
+ # only update the `returned_episode_returns` if the episode is done
245
+ returned_episode_returns=jnp.where(
246
+ info["terminated"] + info["TimeLimit.truncated"], new_episode_return, episode_stats.returned_episode_returns
247
+ ),
248
+ returned_episode_lengths=jnp.where(
249
+ info["terminated"] + info["TimeLimit.truncated"], new_episode_length, episode_stats.returned_episode_lengths
250
+ ),
251
+ )
252
+ return episode_stats, handle, (next_obs, reward, next_done, info)
253
+
254
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
255
+
256
+ def linear_schedule(count):
257
+ # anneal learning rate linearly after one training iteration which contains
258
+ # (args.num_minibatches * args.update_epochs) gradient updates
259
+ frac = 1.0 - (count // (args.num_minibatches * args.update_epochs)) / args.num_iterations
260
+ return args.learning_rate * frac
261
+
262
+ network = Network()
263
+ actor = Actor(action_dim=envs.single_action_space.n)
264
+ critic = Critic()
265
+ network_params = network.init(network_key, np.array([envs.single_observation_space.sample()]))
266
+ agent_state = TrainState.create(
267
+ apply_fn=None,
268
+ params=AgentParams(
269
+ network_params,
270
+ actor.init(actor_key, network.apply(network_params, np.array([envs.single_observation_space.sample()]))),
271
+ critic.init(critic_key, network.apply(network_params, np.array([envs.single_observation_space.sample()]))),
272
+ ),
273
+ tx=optax.chain(
274
+ optax.clip_by_global_norm(args.max_grad_norm),
275
+ optax.inject_hyperparams(optax.adam)(
276
+ learning_rate=linear_schedule if args.anneal_lr else args.learning_rate, eps=1e-5
277
+ ),
278
+ ),
279
+ )
280
+ network.apply = jax.jit(network.apply)
281
+ actor.apply = jax.jit(actor.apply)
282
+ critic.apply = jax.jit(critic.apply)
283
+
284
+ @jax.jit
285
+ def get_action_and_value(
286
+ agent_state: TrainState,
287
+ next_obs: np.ndarray,
288
+ key: jax.random.PRNGKey,
289
+ ):
290
+ """sample action, calculate value, logprob, entropy, and update storage"""
291
+ hidden = network.apply(agent_state.params.network_params, next_obs)
292
+ logits = actor.apply(agent_state.params.actor_params, hidden)
293
+ # sample action: Gumbel-softmax trick
294
+ # see https://stats.stackexchange.com/questions/359442/sampling-from-a-categorical-distribution
295
+ key, subkey = jax.random.split(key)
296
+ u = jax.random.uniform(subkey, shape=logits.shape)
297
+ action = jnp.argmax(logits - jnp.log(-jnp.log(u)), axis=1)
298
+ logprob = jax.nn.log_softmax(logits)[jnp.arange(action.shape[0]), action]
299
+ value = critic.apply(agent_state.params.critic_params, hidden)
300
+ return action, logprob, value.squeeze(1), key
301
+
302
+ @jax.jit
303
+ def get_action_and_value2(
304
+ params: flax.core.FrozenDict,
305
+ x: np.ndarray,
306
+ action: np.ndarray,
307
+ ):
308
+ """calculate value, logprob of supplied `action`, and entropy"""
309
+ hidden = network.apply(params.network_params, x)
310
+ logits = actor.apply(params.actor_params, hidden)
311
+ logprob = jax.nn.log_softmax(logits)[jnp.arange(action.shape[0]), action]
312
+ # normalize the logits https://gregorygundersen.com/blog/2020/02/09/log-sum-exp/
313
+ logits = logits - jax.scipy.special.logsumexp(logits, axis=-1, keepdims=True)
314
+ logits = logits.clip(min=jnp.finfo(logits.dtype).min)
315
+ p_log_p = logits * jax.nn.softmax(logits)
316
+ entropy = -p_log_p.sum(-1)
317
+ value = critic.apply(params.critic_params, hidden).squeeze()
318
+ return logprob, entropy, value
319
+
320
+ def compute_gae_once(carry, inp, gamma, gae_lambda):
321
+ advantages = carry
322
+ nextdone, nextvalues, curvalues, reward = inp
323
+ nextnonterminal = 1.0 - nextdone
324
+
325
+ delta = reward + gamma * nextvalues * nextnonterminal - curvalues
326
+ advantages = delta + gamma * gae_lambda * nextnonterminal * advantages
327
+ return advantages, advantages
328
+
329
+ compute_gae_once = partial(compute_gae_once, gamma=args.gamma, gae_lambda=args.gae_lambda)
330
+
331
+ @jax.jit
332
+ def compute_gae(
333
+ agent_state: TrainState,
334
+ next_obs: np.ndarray,
335
+ next_done: np.ndarray,
336
+ storage: Storage,
337
+ ):
338
+ next_value = critic.apply(
339
+ agent_state.params.critic_params, network.apply(agent_state.params.network_params, next_obs)
340
+ ).squeeze()
341
+
342
+ advantages = jnp.zeros((args.num_envs,))
343
+ dones = jnp.concatenate([storage.dones, next_done[None, :]], axis=0)
344
+ values = jnp.concatenate([storage.values, next_value[None, :]], axis=0)
345
+ _, advantages = jax.lax.scan(
346
+ compute_gae_once, advantages, (dones[1:], values[1:], values[:-1], storage.rewards), reverse=True
347
+ )
348
+ storage = storage.replace(
349
+ advantages=advantages,
350
+ returns=advantages + storage.values,
351
+ )
352
+ return storage
353
+
354
+ def ppo_loss(params, x, a, logp, mb_advantages, mb_returns):
355
+ newlogprob, entropy, newvalue = get_action_and_value2(params, x, a)
356
+ logratio = newlogprob - logp
357
+ ratio = jnp.exp(logratio)
358
+ approx_kl = ((ratio - 1) - logratio).mean()
359
+
360
+ if args.norm_adv:
361
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
362
+
363
+ # Policy loss
364
+ pg_loss1 = -mb_advantages * ratio
365
+ pg_loss2 = -mb_advantages * jnp.clip(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
366
+ pg_loss = jnp.maximum(pg_loss1, pg_loss2).mean()
367
+
368
+ # Value loss
369
+ v_loss = 0.5 * ((newvalue - mb_returns) ** 2).mean()
370
+
371
+ entropy_loss = entropy.mean()
372
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
373
+ return loss, (pg_loss, v_loss, entropy_loss, jax.lax.stop_gradient(approx_kl))
374
+
375
+ ppo_loss_grad_fn = jax.value_and_grad(ppo_loss, has_aux=True)
376
+
377
+ @jax.jit
378
+ def update_ppo(
379
+ agent_state: TrainState,
380
+ storage: Storage,
381
+ key: jax.random.PRNGKey,
382
+ ):
383
+ def update_epoch(carry, unused_inp):
384
+ agent_state, key = carry
385
+ key, subkey = jax.random.split(key)
386
+
387
+ def flatten(x):
388
+ return x.reshape((-1,) + x.shape[2:])
389
+
390
+ # taken from: https://github.com/google/brax/blob/main/brax/training/agents/ppo/train.py
391
+ def convert_data(x: jnp.ndarray):
392
+ x = jax.random.permutation(subkey, x)
393
+ x = jnp.reshape(x, (args.num_minibatches, -1) + x.shape[1:])
394
+ return x
395
+
396
+ flatten_storage = jax.tree_map(flatten, storage)
397
+ shuffled_storage = jax.tree_map(convert_data, flatten_storage)
398
+
399
+ def update_minibatch(agent_state, minibatch):
400
+ (loss, (pg_loss, v_loss, entropy_loss, approx_kl)), grads = ppo_loss_grad_fn(
401
+ agent_state.params,
402
+ minibatch.obs,
403
+ minibatch.actions,
404
+ minibatch.logprobs,
405
+ minibatch.advantages,
406
+ minibatch.returns,
407
+ )
408
+ agent_state = agent_state.apply_gradients(grads=grads)
409
+ return agent_state, (loss, pg_loss, v_loss, entropy_loss, approx_kl, grads)
410
+
411
+ agent_state, (loss, pg_loss, v_loss, entropy_loss, approx_kl, grads) = jax.lax.scan(
412
+ update_minibatch, agent_state, shuffled_storage
413
+ )
414
+ return (agent_state, key), (loss, pg_loss, v_loss, entropy_loss, approx_kl, grads)
415
+
416
+ (agent_state, key), (loss, pg_loss, v_loss, entropy_loss, approx_kl, grads) = jax.lax.scan(
417
+ update_epoch, (agent_state, key), (), length=args.update_epochs
418
+ )
419
+ return agent_state, loss, pg_loss, v_loss, entropy_loss, approx_kl, key
420
+
421
+ # TRY NOT TO MODIFY: start the game
422
+ global_step = 0
423
+ start_time = time.time()
424
+ next_obs = envs.reset()
425
+ next_done = jnp.zeros(args.num_envs, dtype=jax.numpy.bool_)
426
+
427
+ # based on https://github.dev/google/evojax/blob/0625d875262011d8e1b6aa32566b236f44b4da66/evojax/sim_mgr.py
428
+ def step_once(carry, step, env_step_fn):
429
+ agent_state, episode_stats, obs, done, key, handle = carry
430
+ action, logprob, value, key = get_action_and_value(agent_state, obs, key)
431
+
432
+ episode_stats, handle, (next_obs, reward, next_done, _) = env_step_fn(episode_stats, handle, action)
433
+ storage = Storage(
434
+ obs=obs,
435
+ actions=action,
436
+ logprobs=logprob,
437
+ dones=done,
438
+ values=value,
439
+ rewards=reward,
440
+ returns=jnp.zeros_like(reward),
441
+ advantages=jnp.zeros_like(reward),
442
+ )
443
+ return ((agent_state, episode_stats, next_obs, next_done, key, handle), storage)
444
+
445
+ def rollout(agent_state, episode_stats, next_obs, next_done, key, handle, step_once_fn, max_steps):
446
+ (agent_state, episode_stats, next_obs, next_done, key, handle), storage = jax.lax.scan(
447
+ step_once_fn, (agent_state, episode_stats, next_obs, next_done, key, handle), (), max_steps
448
+ )
449
+ return agent_state, episode_stats, next_obs, next_done, storage, key, handle
450
+
451
+ rollout = partial(rollout, step_once_fn=partial(step_once, env_step_fn=step_env_wrappeed), max_steps=args.num_steps)
452
+
453
+ for iteration in range(1, args.num_iterations + 1):
454
+ iteration_time_start = time.time()
455
+ agent_state, episode_stats, next_obs, next_done, storage, key, handle = rollout(
456
+ agent_state, episode_stats, next_obs, next_done, key, handle
457
+ )
458
+ global_step += args.num_steps * args.num_envs
459
+ storage = compute_gae(agent_state, next_obs, next_done, storage)
460
+ agent_state, loss, pg_loss, v_loss, entropy_loss, approx_kl, key = update_ppo(
461
+ agent_state,
462
+ storage,
463
+ key,
464
+ )
465
+ avg_episodic_return = np.mean(jax.device_get(episode_stats.returned_episode_returns))
466
+ print(f"global_step={global_step}, avg_episodic_return={avg_episodic_return}")
467
+
468
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
469
+ writer.add_scalar("charts/avg_episodic_return", avg_episodic_return, global_step)
470
+ writer.add_scalar(
471
+ "charts/avg_episodic_length", np.mean(jax.device_get(episode_stats.returned_episode_lengths)), global_step
472
+ )
473
+ writer.add_scalar("charts/learning_rate", agent_state.opt_state[1].hyperparams["learning_rate"].item(), global_step)
474
+ writer.add_scalar("losses/value_loss", v_loss[-1, -1].item(), global_step)
475
+ writer.add_scalar("losses/policy_loss", pg_loss[-1, -1].item(), global_step)
476
+ writer.add_scalar("losses/entropy", entropy_loss[-1, -1].item(), global_step)
477
+ writer.add_scalar("losses/approx_kl", approx_kl[-1, -1].item(), global_step)
478
+ writer.add_scalar("losses/loss", loss[-1, -1].item(), global_step)
479
+ print("SPS:", int(global_step / (time.time() - start_time)))
480
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
481
+ writer.add_scalar(
482
+ "charts/SPS_update", int(args.num_envs * args.num_steps / (time.time() - iteration_time_start)), global_step
483
+ )
484
+
485
+ if args.save_model:
486
+ model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
487
+ with open(model_path, "wb") as f:
488
+ f.write(
489
+ flax.serialization.to_bytes(
490
+ [
491
+ vars(args),
492
+ [
493
+ agent_state.params.network_params,
494
+ agent_state.params.actor_params,
495
+ agent_state.params.critic_params,
496
+ ],
497
+ ]
498
+ )
499
+ )
500
+ print(f"model saved to {model_path}")
501
+ from cleanrl_utils.evals.ppo_envpool_jax_eval import evaluate
502
+
503
+ episodic_returns = evaluate(
504
+ model_path,
505
+ make_env,
506
+ args.env_id,
507
+ eval_episodes=10,
508
+ run_name=f"{run_name}-eval",
509
+ Model=(Network, Actor, Critic),
510
+ )
511
+ for idx, episodic_return in enumerate(episodic_returns):
512
+ writer.add_scalar("eval/episodic_return", episodic_return, idx)
513
+
514
+ if args.upload_model:
515
+ from cleanrl_utils.huggingface import push_to_hub
516
+
517
+ repo_name = f"{args.env_id}-{args.exp_name}-seed{args.seed}"
518
+ repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
519
+ push_to_hub(args, episodic_returns, repo_id, "PPO", f"runs/{run_name}", f"videos/{run_name}-eval")
520
+
521
+ envs.close()
522
+ writer.close()
cleanrl/cleanrl/ppo_atari_lstm.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/ppo/#ppo_atari_lstmpy
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+
7
+ import gymnasium as gym
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.optim as optim
12
+ import tyro
13
+ from torch.distributions.categorical import Categorical
14
+ from torch.utils.tensorboard import SummaryWriter
15
+
16
+ from cleanrl_utils.atari_wrappers import ( # isort:skip
17
+ ClipRewardEnv,
18
+ EpisodicLifeEnv,
19
+ FireResetEnv,
20
+ MaxAndSkipEnv,
21
+ NoopResetEnv,
22
+ )
23
+
24
+
25
+ @dataclass
26
+ class Args:
27
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
28
+ """the name of this experiment"""
29
+ seed: int = 1
30
+ """seed of the experiment"""
31
+ torch_deterministic: bool = True
32
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
33
+ cuda: bool = True
34
+ """if toggled, cuda will be enabled by default"""
35
+ track: bool = False
36
+ """if toggled, this experiment will be tracked with Weights and Biases"""
37
+ wandb_project_name: str = "cleanRL"
38
+ """the wandb's project name"""
39
+ wandb_entity: str = None
40
+ """the entity (team) of wandb's project"""
41
+ capture_video: bool = False
42
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
43
+
44
+ # Algorithm specific arguments
45
+ env_id: str = "BreakoutNoFrameskip-v4"
46
+ """the id of the environment"""
47
+ total_timesteps: int = 10000000
48
+ """total timesteps of the experiments"""
49
+ learning_rate: float = 2.5e-4
50
+ """the learning rate of the optimizer"""
51
+ num_envs: int = 8
52
+ """the number of parallel game environments"""
53
+ num_steps: int = 128
54
+ """the number of steps to run in each environment per policy rollout"""
55
+ anneal_lr: bool = True
56
+ """Toggle learning rate annealing for policy and value networks"""
57
+ gamma: float = 0.99
58
+ """the discount factor gamma"""
59
+ gae_lambda: float = 0.95
60
+ """the lambda for the general advantage estimation"""
61
+ num_minibatches: int = 4
62
+ """the number of mini-batches"""
63
+ update_epochs: int = 4
64
+ """the K epochs to update the policy"""
65
+ norm_adv: bool = True
66
+ """Toggles advantages normalization"""
67
+ clip_coef: float = 0.1
68
+ """the surrogate clipping coefficient"""
69
+ clip_vloss: bool = True
70
+ """Toggles whether or not to use a clipped loss for the value function, as per the paper."""
71
+ ent_coef: float = 0.01
72
+ """coefficient of the entropy"""
73
+ vf_coef: float = 0.5
74
+ """coefficient of the value function"""
75
+ max_grad_norm: float = 0.5
76
+ """the maximum norm for the gradient clipping"""
77
+ target_kl: float = None
78
+ """the target KL divergence threshold"""
79
+
80
+ # to be filled in runtime
81
+ batch_size: int = 0
82
+ """the batch size (computed in runtime)"""
83
+ minibatch_size: int = 0
84
+ """the mini-batch size (computed in runtime)"""
85
+ num_iterations: int = 0
86
+ """the number of iterations (computed in runtime)"""
87
+
88
+
89
+ def make_env(env_id, idx, capture_video, run_name):
90
+ def thunk():
91
+ if capture_video and idx == 0:
92
+ env = gym.make(env_id, render_mode="rgb_array")
93
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
94
+ else:
95
+ env = gym.make(env_id)
96
+ env = gym.wrappers.RecordEpisodeStatistics(env)
97
+ env = NoopResetEnv(env, noop_max=30)
98
+ env = MaxAndSkipEnv(env, skip=4)
99
+ env = EpisodicLifeEnv(env)
100
+ if "FIRE" in env.unwrapped.get_action_meanings():
101
+ env = FireResetEnv(env)
102
+ env = ClipRewardEnv(env)
103
+ env = gym.wrappers.ResizeObservation(env, (84, 84))
104
+ env = gym.wrappers.GrayScaleObservation(env)
105
+ env = gym.wrappers.FrameStack(env, 1)
106
+ return env
107
+
108
+ return thunk
109
+
110
+
111
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
112
+ torch.nn.init.orthogonal_(layer.weight, std)
113
+ torch.nn.init.constant_(layer.bias, bias_const)
114
+ return layer
115
+
116
+
117
+ class Agent(nn.Module):
118
+ def __init__(self, envs):
119
+ super().__init__()
120
+ self.network = nn.Sequential(
121
+ layer_init(nn.Conv2d(1, 32, 8, stride=4)),
122
+ nn.ReLU(),
123
+ layer_init(nn.Conv2d(32, 64, 4, stride=2)),
124
+ nn.ReLU(),
125
+ layer_init(nn.Conv2d(64, 64, 3, stride=1)),
126
+ nn.ReLU(),
127
+ nn.Flatten(),
128
+ layer_init(nn.Linear(64 * 7 * 7, 512)),
129
+ nn.ReLU(),
130
+ )
131
+ self.lstm = nn.LSTM(512, 128)
132
+ for name, param in self.lstm.named_parameters():
133
+ if "bias" in name:
134
+ nn.init.constant_(param, 0)
135
+ elif "weight" in name:
136
+ nn.init.orthogonal_(param, 1.0)
137
+ self.actor = layer_init(nn.Linear(128, envs.single_action_space.n), std=0.01)
138
+ self.critic = layer_init(nn.Linear(128, 1), std=1)
139
+
140
+ def get_states(self, x, lstm_state, done):
141
+ hidden = self.network(x / 255.0)
142
+
143
+ # LSTM logic
144
+ batch_size = lstm_state[0].shape[1]
145
+ hidden = hidden.reshape((-1, batch_size, self.lstm.input_size))
146
+ done = done.reshape((-1, batch_size))
147
+ new_hidden = []
148
+ for h, d in zip(hidden, done):
149
+ h, lstm_state = self.lstm(
150
+ h.unsqueeze(0),
151
+ (
152
+ (1.0 - d).view(1, -1, 1) * lstm_state[0],
153
+ (1.0 - d).view(1, -1, 1) * lstm_state[1],
154
+ ),
155
+ )
156
+ new_hidden += [h]
157
+ new_hidden = torch.flatten(torch.cat(new_hidden), 0, 1)
158
+ return new_hidden, lstm_state
159
+
160
+ def get_value(self, x, lstm_state, done):
161
+ hidden, _ = self.get_states(x, lstm_state, done)
162
+ return self.critic(hidden)
163
+
164
+ def get_action_and_value(self, x, lstm_state, done, action=None):
165
+ hidden, lstm_state = self.get_states(x, lstm_state, done)
166
+ logits = self.actor(hidden)
167
+ probs = Categorical(logits=logits)
168
+ if action is None:
169
+ action = probs.sample()
170
+ return action, probs.log_prob(action), probs.entropy(), self.critic(hidden), lstm_state
171
+
172
+
173
+ if __name__ == "__main__":
174
+ args = tyro.cli(Args)
175
+ args.batch_size = int(args.num_envs * args.num_steps)
176
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
177
+ args.num_iterations = args.total_timesteps // args.batch_size
178
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
179
+ if args.track:
180
+ import wandb
181
+
182
+ wandb.init(
183
+ project=args.wandb_project_name,
184
+ entity=args.wandb_entity,
185
+ sync_tensorboard=True,
186
+ config=vars(args),
187
+ name=run_name,
188
+ monitor_gym=True,
189
+ save_code=True,
190
+ )
191
+ writer = SummaryWriter(f"runs/{run_name}")
192
+ writer.add_text(
193
+ "hyperparameters",
194
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
195
+ )
196
+
197
+ # TRY NOT TO MODIFY: seeding
198
+ random.seed(args.seed)
199
+ np.random.seed(args.seed)
200
+ torch.manual_seed(args.seed)
201
+ torch.backends.cudnn.deterministic = args.torch_deterministic
202
+
203
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
204
+
205
+ # env setup
206
+ envs = gym.vector.SyncVectorEnv(
207
+ [make_env(args.env_id, i, args.capture_video, run_name) for i in range(args.num_envs)],
208
+ )
209
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
210
+
211
+ agent = Agent(envs).to(device)
212
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
213
+
214
+ # ALGO Logic: Storage setup
215
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
216
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
217
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
218
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
219
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
220
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
221
+
222
+ # TRY NOT TO MODIFY: start the game
223
+ global_step = 0
224
+ start_time = time.time()
225
+ next_obs, _ = envs.reset(seed=args.seed)
226
+ next_obs = torch.Tensor(next_obs).to(device)
227
+ next_done = torch.zeros(args.num_envs).to(device)
228
+ next_lstm_state = (
229
+ torch.zeros(agent.lstm.num_layers, args.num_envs, agent.lstm.hidden_size).to(device),
230
+ torch.zeros(agent.lstm.num_layers, args.num_envs, agent.lstm.hidden_size).to(device),
231
+ ) # hidden and cell states (see https://youtu.be/8HyCNIVRbSU)
232
+
233
+ for iteration in range(1, args.num_iterations + 1):
234
+ initial_lstm_state = (next_lstm_state[0].clone(), next_lstm_state[1].clone())
235
+ # Annealing the rate if instructed to do so.
236
+ if args.anneal_lr:
237
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
238
+ lrnow = frac * args.learning_rate
239
+ optimizer.param_groups[0]["lr"] = lrnow
240
+
241
+ for step in range(0, args.num_steps):
242
+ global_step += args.num_envs
243
+ obs[step] = next_obs
244
+ dones[step] = next_done
245
+
246
+ # ALGO LOGIC: action logic
247
+ with torch.no_grad():
248
+ action, logprob, _, value, next_lstm_state = agent.get_action_and_value(next_obs, next_lstm_state, next_done)
249
+ values[step] = value.flatten()
250
+ actions[step] = action
251
+ logprobs[step] = logprob
252
+
253
+ # TRY NOT TO MODIFY: execute the game and log data.
254
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
255
+ next_done = np.logical_or(terminations, truncations)
256
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
257
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
258
+
259
+ if "final_info" in infos:
260
+ for info in infos["final_info"]:
261
+ if info and "episode" in info:
262
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
263
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
264
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
265
+
266
+ # bootstrap value if not done
267
+ with torch.no_grad():
268
+ next_value = agent.get_value(
269
+ next_obs,
270
+ next_lstm_state,
271
+ next_done,
272
+ ).reshape(1, -1)
273
+ advantages = torch.zeros_like(rewards).to(device)
274
+ lastgaelam = 0
275
+ for t in reversed(range(args.num_steps)):
276
+ if t == args.num_steps - 1:
277
+ nextnonterminal = 1.0 - next_done
278
+ nextvalues = next_value
279
+ else:
280
+ nextnonterminal = 1.0 - dones[t + 1]
281
+ nextvalues = values[t + 1]
282
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
283
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
284
+ returns = advantages + values
285
+
286
+ # flatten the batch
287
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
288
+ b_logprobs = logprobs.reshape(-1)
289
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
290
+ b_dones = dones.reshape(-1)
291
+ b_advantages = advantages.reshape(-1)
292
+ b_returns = returns.reshape(-1)
293
+ b_values = values.reshape(-1)
294
+
295
+ # Optimizing the policy and value network
296
+ assert args.num_envs % args.num_minibatches == 0
297
+ envsperbatch = args.num_envs // args.num_minibatches
298
+ envinds = np.arange(args.num_envs)
299
+ flatinds = np.arange(args.batch_size).reshape(args.num_steps, args.num_envs)
300
+ clipfracs = []
301
+ for epoch in range(args.update_epochs):
302
+ np.random.shuffle(envinds)
303
+ for start in range(0, args.num_envs, envsperbatch):
304
+ end = start + envsperbatch
305
+ mbenvinds = envinds[start:end]
306
+ mb_inds = flatinds[:, mbenvinds].ravel() # be really careful about the index
307
+
308
+ _, newlogprob, entropy, newvalue, _ = agent.get_action_and_value(
309
+ b_obs[mb_inds],
310
+ (initial_lstm_state[0][:, mbenvinds], initial_lstm_state[1][:, mbenvinds]),
311
+ b_dones[mb_inds],
312
+ b_actions.long()[mb_inds],
313
+ )
314
+ logratio = newlogprob - b_logprobs[mb_inds]
315
+ ratio = logratio.exp()
316
+
317
+ with torch.no_grad():
318
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
319
+ old_approx_kl = (-logratio).mean()
320
+ approx_kl = ((ratio - 1) - logratio).mean()
321
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
322
+
323
+ mb_advantages = b_advantages[mb_inds]
324
+ if args.norm_adv:
325
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
326
+
327
+ # Policy loss
328
+ pg_loss1 = -mb_advantages * ratio
329
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
330
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
331
+
332
+ # Value loss
333
+ newvalue = newvalue.view(-1)
334
+ if args.clip_vloss:
335
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
336
+ v_clipped = b_values[mb_inds] + torch.clamp(
337
+ newvalue - b_values[mb_inds],
338
+ -args.clip_coef,
339
+ args.clip_coef,
340
+ )
341
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
342
+ v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped)
343
+ v_loss = 0.5 * v_loss_max.mean()
344
+ else:
345
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
346
+
347
+ entropy_loss = entropy.mean()
348
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
349
+
350
+ optimizer.zero_grad()
351
+ loss.backward()
352
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
353
+ optimizer.step()
354
+
355
+ if args.target_kl is not None and approx_kl > args.target_kl:
356
+ break
357
+
358
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
359
+ var_y = np.var(y_true)
360
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
361
+
362
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
363
+ writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step)
364
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
365
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
366
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
367
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
368
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
369
+ writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step)
370
+ writer.add_scalar("losses/explained_variance", explained_var, global_step)
371
+ print("SPS:", int(global_step / (time.time() - start_time)))
372
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
373
+
374
+ envs.close()
375
+ writer.close()
cleanrl/cleanrl/ppo_bandit.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PPO implementation for RAGEN Bandit environment
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+
7
+ import gymnasium as gym
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.optim as optim
12
+ import tyro
13
+ from torch.distributions.categorical import Categorical
14
+ from torch.utils.tensorboard import SummaryWriter
15
+
16
+ import sys
17
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../'))
18
+
19
+ from ragen.env.bandit.env import BanditEnv
20
+ from ragen.env.bandit.config import BanditEnvConfig
21
+ from ragen_wrappers import BanditWrapper
22
+
23
+
24
+ @dataclass
25
+ class Args:
26
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
27
+ """the name of this experiment"""
28
+ seed: int = 1
29
+ """seed of the experiment"""
30
+ torch_deterministic: bool = True
31
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
32
+ cuda: bool = True
33
+ """if toggled, cuda will be enabled by default"""
34
+ track: bool = True
35
+ """if toggled, this experiment will be tracked with Weights and Biases"""
36
+ wandb_project_name: str = "Subagent"
37
+ """the wandb's project name"""
38
+ wandb_entity: str = None
39
+ """the entity (team) of wandb's project"""
40
+ capture_video: bool = False
41
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
42
+
43
+ # Algorithm specific arguments
44
+ env_id: str = "Bandit"
45
+ """the id of the environment"""
46
+ total_timesteps: int = 10000000
47
+ """total timesteps of the experiments"""
48
+ learning_rate: float = 2.5e-4
49
+ """the learning rate of the optimizer"""
50
+ num_envs: int = 32
51
+ """the number of parallel game environments"""
52
+ num_steps: int = 512
53
+ """the number of steps to run in each environment per policy rollout"""
54
+ anneal_lr: bool = True
55
+ """Toggle learning rate annealing for policy and value networks"""
56
+ gamma: float = 0.99
57
+ """the discount factor gamma"""
58
+ gae_lambda: float = 0.95
59
+ """the lambda for the general advantage estimation"""
60
+ num_minibatches: int = 4
61
+ """the number of mini-batches"""
62
+ update_epochs: int = 4
63
+ """the K epochs to update the policy"""
64
+ norm_adv: bool = True
65
+ """Toggles advantages normalization"""
66
+ clip_coef: float = 0.2
67
+ """the surrogate clipping coefficient"""
68
+ clip_vloss: bool = True
69
+ """Toggles whether or not to use a clipped loss for the value function, as per the paper."""
70
+ ent_coef: float = 0.01
71
+ """coefficient of the entropy"""
72
+ vf_coef: float = 0.5
73
+ """coefficient of the value function"""
74
+ max_grad_norm: float = 0.5
75
+ """the maximum norm for the gradient clipping"""
76
+ target_kl: float = None
77
+ """the target KL divergence threshold"""
78
+
79
+ # to be filled in runtime
80
+ batch_size: int = 0
81
+ """the batch size (computed in runtime)"""
82
+ minibatch_size: int = 0
83
+ """the mini-batch size (computed in runtime)"""
84
+ num_iterations: int = 0
85
+ """the number of iterations (computed in runtime)"""
86
+
87
+
88
+ def make_env(env_id, idx, capture_video, run_name, seed):
89
+ def thunk():
90
+ config = BanditEnvConfig()
91
+ env = BanditEnv(config)
92
+ env = BanditWrapper(env)
93
+ env = gym.wrappers.RecordEpisodeStatistics(env)
94
+ if capture_video and idx == 0:
95
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
96
+ return env
97
+ return thunk
98
+
99
+
100
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
101
+ torch.nn.init.orthogonal_(layer.weight, std)
102
+ torch.nn.init.constant_(layer.bias, bias_const)
103
+ return layer
104
+
105
+
106
+ class Agent(nn.Module):
107
+ def __init__(self, envs):
108
+ super().__init__()
109
+ obs_shape = np.array(envs.single_observation_space.shape).prod()
110
+ self.critic = nn.Sequential(
111
+ layer_init(nn.Linear(obs_shape, 64)),
112
+ nn.Tanh(),
113
+ layer_init(nn.Linear(64, 64)),
114
+ nn.Tanh(),
115
+ layer_init(nn.Linear(64, 1), std=1.0),
116
+ )
117
+ self.actor = nn.Sequential(
118
+ layer_init(nn.Linear(obs_shape, 64)),
119
+ nn.Tanh(),
120
+ layer_init(nn.Linear(64, 64)),
121
+ nn.Tanh(),
122
+ layer_init(nn.Linear(64, envs.single_action_space.n), std=0.01),
123
+ )
124
+
125
+ def get_value(self, x):
126
+ return self.critic(x)
127
+
128
+ def get_action_and_value(self, x, action=None):
129
+ logits = self.actor(x)
130
+ probs = Categorical(logits=logits)
131
+ if action is None:
132
+ action = probs.sample()
133
+ return action, probs.log_prob(action), probs.entropy(), self.critic(x)
134
+
135
+
136
+ if __name__ == "__main__":
137
+ args = tyro.cli(Args)
138
+ args.batch_size = int(args.num_envs * args.num_steps)
139
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
140
+ args.num_iterations = args.total_timesteps // args.batch_size
141
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
142
+ if args.track:
143
+ import wandb
144
+
145
+ wandb.init(
146
+ project=args.wandb_project_name,
147
+ entity=args.wandb_entity,
148
+ sync_tensorboard=True,
149
+ config=vars(args),
150
+ name=run_name,
151
+ monitor_gym=True,
152
+ save_code=True,
153
+ )
154
+ writer = SummaryWriter(f"runs/{run_name}")
155
+ writer.add_text(
156
+ "hyperparameters",
157
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
158
+ )
159
+
160
+ # TRY NOT TO MODIFY: seeding
161
+ random.seed(args.seed)
162
+ np.random.seed(args.seed)
163
+ torch.manual_seed(args.seed)
164
+ torch.backends.cudnn.deterministic = args.torch_deterministic
165
+
166
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
167
+
168
+ # env setup
169
+ envs = gym.vector.SyncVectorEnv(
170
+ [make_env(args.env_id, i, args.capture_video, run_name, args.seed + i) for i in range(args.num_envs)],
171
+ )
172
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
173
+
174
+ agent = Agent(envs).to(device)
175
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
176
+
177
+ # ALGO Logic: Storage setup
178
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
179
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
180
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
181
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
182
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
183
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
184
+
185
+ # TRY NOT TO MODIFY: start the game
186
+ global_step = 0
187
+ start_time = time.time()
188
+ next_obs, _ = envs.reset(seed=args.seed)
189
+ next_obs = torch.Tensor(next_obs).to(device)
190
+ next_done = torch.zeros(args.num_envs).to(device)
191
+
192
+ for iteration in range(1, args.num_iterations + 1):
193
+ # Annealing the rate if instructed to do so.
194
+ if args.anneal_lr:
195
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
196
+ lrnow = frac * args.learning_rate
197
+ optimizer.param_groups[0]["lr"] = lrnow
198
+
199
+ for step in range(0, args.num_steps):
200
+ global_step += args.num_envs
201
+ obs[step] = next_obs
202
+ dones[step] = next_done
203
+
204
+ # ALGO LOGIC: action logic
205
+ with torch.no_grad():
206
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
207
+ values[step] = value.flatten()
208
+ actions[step] = action
209
+ logprobs[step] = logprob
210
+
211
+ # TRY NOT TO MODIFY: execute the game and log data.
212
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
213
+ next_done = np.logical_or(terminations, truncations)
214
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
215
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
216
+
217
+ if "final_info" in infos:
218
+ for info in infos["final_info"]:
219
+ if info and "episode" in info:
220
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
221
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
222
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
223
+
224
+ # bootstrap value if not done
225
+ with torch.no_grad():
226
+ next_value = agent.get_value(next_obs).reshape(1, -1)
227
+ advantages = torch.zeros_like(rewards).to(device)
228
+ lastgaelam = 0
229
+ for t in reversed(range(args.num_steps)):
230
+ if t == args.num_steps - 1:
231
+ nextnonterminal = 1.0 - next_done
232
+ nextvalues = next_value
233
+ else:
234
+ nextnonterminal = 1.0 - dones[t + 1]
235
+ nextvalues = values[t + 1]
236
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
237
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
238
+ returns = advantages + values
239
+
240
+ # flatten the batch
241
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
242
+ b_logprobs = logprobs.reshape(-1)
243
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
244
+ b_advantages = advantages.reshape(-1)
245
+ b_returns = returns.reshape(-1)
246
+ b_values = values.reshape(-1)
247
+
248
+ # Optimizing the policy and value network
249
+ b_inds = np.arange(args.batch_size)
250
+ clipfracs = []
251
+ for epoch in range(args.update_epochs):
252
+ np.random.shuffle(b_inds)
253
+ for start in range(0, args.batch_size, args.minibatch_size):
254
+ end = start + args.minibatch_size
255
+ mb_inds = b_inds[start:end]
256
+
257
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
258
+ logratio = newlogprob - b_logprobs[mb_inds]
259
+ ratio = logratio.exp()
260
+
261
+ with torch.no_grad():
262
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
263
+ old_approx_kl = (-logratio).mean()
264
+ approx_kl = ((ratio - 1) - logratio).mean()
265
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
266
+
267
+ mb_advantages = b_advantages[mb_inds]
268
+ if args.norm_adv:
269
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
270
+
271
+ # Policy loss
272
+ pg_loss1 = -mb_advantages * ratio
273
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
274
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
275
+
276
+ # Value loss
277
+ newvalue = newvalue.view(-1)
278
+ if args.clip_vloss:
279
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
280
+ v_clipped = b_values[mb_inds] + torch.clamp(
281
+ newvalue - b_values[mb_inds],
282
+ -args.clip_coef,
283
+ args.clip_coef,
284
+ )
285
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
286
+ v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped)
287
+ v_loss = 0.5 * v_loss_max.mean()
288
+ else:
289
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
290
+
291
+ entropy_loss = entropy.mean()
292
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
293
+
294
+ optimizer.zero_grad()
295
+ loss.backward()
296
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
297
+ optimizer.step()
298
+
299
+ if args.target_kl is not None and approx_kl > args.target_kl:
300
+ break
301
+
302
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
303
+ var_y = np.var(y_true)
304
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
305
+
306
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
307
+ writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step)
308
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
309
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
310
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
311
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
312
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
313
+ writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step)
314
+ writer.add_scalar("losses/explained_variance", explained_var, global_step)
315
+
316
+ # Additional useful metrics
317
+ writer.add_scalar("charts/avg_reward", rewards.mean().item(), global_step)
318
+ writer.add_scalar("charts/avg_value", values.mean().item(), global_step)
319
+ writer.add_scalar("charts/max_reward", rewards.max().item(), global_step)
320
+ writer.add_scalar("charts/min_reward", rewards.min().item(), global_step)
321
+
322
+ # Console output with key metrics
323
+ sps = int(global_step / (time.time() - start_time))
324
+ progress = 100 * iteration / args.num_iterations
325
+ print(f"[{progress:5.1f}%] Iter {iteration:4d}/{args.num_iterations} | "
326
+ f"SPS: {sps:5d} | "
327
+ f"Reward: {rewards.mean().item():6.3f} | "
328
+ f"Value: {values.mean().item():6.3f} | "
329
+ f"VLoss: {v_loss.item():.4f} | "
330
+ f"PLoss: {pg_loss.item():.4f} | "
331
+ f"Ent: {entropy_loss.item():.4f}")
332
+ writer.add_scalar("charts/SPS", sps, global_step)
333
+
334
+ envs.close()
335
+ writer.close()
cleanrl/cleanrl/ppo_bandit_small.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PPO with small MLP for RAGEN Bandit using the existing env (no env edits)
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Any, Dict
8
+ import json
9
+
10
+ import gymnasium as gym
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.optim as optim
15
+ import tyro
16
+ from torch.distributions.categorical import Categorical
17
+
18
+ import sys
19
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../'))
20
+
21
+ from ragen.env.bandit.env import BanditEnv
22
+ from ragen.env.bandit.config import BanditEnvConfig
23
+ from ragen.env.base import BaseDiscreteActionEnv
24
+ from ragen_wrappers import BanditWrapper
25
+
26
+
27
+ @dataclass
28
+ class Args:
29
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
30
+ seed: int = 1
31
+ torch_deterministic: bool = True
32
+ cuda: bool = True
33
+ track: bool = True
34
+ wandb_project_name: str = "cleanRL"
35
+ wandb_entity: str | None = None
36
+ capture_video: bool = False
37
+
38
+ # Algorithm
39
+ env_id: str = "Bandit"
40
+ total_timesteps: int = 50_000
41
+ learning_rate: float = 3e-4
42
+ num_envs: int = 16
43
+ num_steps: int = 16
44
+ anneal_lr: bool = True
45
+ gamma: float = 0.0 # single-step bandit; no bootstrapping
46
+ gae_lambda: float = 0.95
47
+ num_minibatches: int = 4
48
+ update_epochs: int = 4
49
+ norm_adv: bool = True
50
+ clip_coef: float = 0.2
51
+ clip_vloss: bool = True
52
+ ent_coef: float = 0.01
53
+ vf_coef: float = 0.5
54
+ max_grad_norm: float = 0.5
55
+ target_kl: float | None = None
56
+
57
+ # Model size
58
+ hidden_size: int = 32
59
+ feature_dim_per_name: int = 16 # BanditWrapper setting
60
+
61
+ # runtime filled
62
+ batch_size: int = 0
63
+ minibatch_size: int = 0
64
+ num_iterations: int = 0
65
+
66
+
67
+ def make_env(idx, run_name, seed, feature_dim_per_name: int, capture_video=False):
68
+ def thunk():
69
+ cfg = BanditEnvConfig()
70
+ env = BanditEnv(cfg)
71
+ env = BanditWrapper(env, feature_dim_per_name=feature_dim_per_name)
72
+ env = gym.wrappers.RecordEpisodeStatistics(env)
73
+ if capture_video and idx == 0:
74
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
75
+ return env
76
+ return thunk
77
+
78
+
79
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
80
+ torch.nn.init.orthogonal_(layer.weight, std)
81
+ torch.nn.init.constant_(layer.bias, bias_const)
82
+ return layer
83
+
84
+
85
+ class Agent(nn.Module):
86
+ def __init__(self, envs, hidden: int):
87
+ super().__init__()
88
+ obs_shape = int(np.array(envs.single_observation_space.shape).prod())
89
+ self.critic = nn.Sequential(
90
+ layer_init(nn.Linear(obs_shape, hidden)),
91
+ nn.Tanh(),
92
+ layer_init(nn.Linear(hidden, 1), std=1.0),
93
+ )
94
+ self.actor = nn.Sequential(
95
+ layer_init(nn.Linear(obs_shape, hidden)),
96
+ nn.Tanh(),
97
+ layer_init(nn.Linear(hidden, envs.single_action_space.n), std=0.01),
98
+ )
99
+
100
+ def get_value(self, x):
101
+ return self.critic(x)
102
+
103
+ def get_action_and_value(self, x, action=None):
104
+ logits = self.actor(x)
105
+ probs = Categorical(logits=logits)
106
+ if action is None:
107
+ action = probs.sample()
108
+ return action, probs.log_prob(action), probs.entropy(), self.critic(x)
109
+
110
+
111
+ if __name__ == "__main__":
112
+ args = tyro.cli(Args)
113
+ args.batch_size = int(args.num_envs * args.num_steps)
114
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
115
+ args.num_iterations = args.total_timesteps // args.batch_size
116
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
117
+
118
+ if args.track:
119
+ import wandb
120
+ wandb.init(
121
+ project=args.wandb_project_name,
122
+ entity=args.wandb_entity,
123
+ config=vars(args),
124
+ name=run_name,
125
+ monitor_gym=True,
126
+ save_code=True,
127
+ )
128
+ try:
129
+ wandb.define_metric("global_step")
130
+ for prefix in ["train/*", "rollout/*", "eval/*", "losses/*", "charts/*", "perf/*"]:
131
+ wandb.define_metric(prefix, step_metric="global_step")
132
+ except Exception:
133
+ pass
134
+
135
+ # seeding
136
+ random.seed(args.seed)
137
+ np.random.seed(args.seed)
138
+ torch.manual_seed(args.seed)
139
+ torch.backends.cudnn.deterministic = args.torch_deterministic
140
+
141
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
142
+
143
+ # envs
144
+ envs = gym.vector.SyncVectorEnv([
145
+ make_env(i, run_name, args.seed, args.feature_dim_per_name, args.capture_video)
146
+ for i in range(args.num_envs)
147
+ ])
148
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete)
149
+
150
+ agent = Agent(envs, hidden=args.hidden_size).to(device)
151
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
152
+
153
+ # storage
154
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
155
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
156
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
157
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
158
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
159
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
160
+
161
+ # start
162
+ global_step = 0
163
+ start_time = time.time()
164
+ next_obs, _ = envs.reset(seed=args.seed)
165
+ next_obs = torch.Tensor(next_obs).to(device)
166
+ next_done = torch.zeros(args.num_envs).to(device)
167
+
168
+ eval_out_dir = Path(f"runs/{run_name}/trajectories")
169
+ eval_out_dir.mkdir(parents=True, exist_ok=True)
170
+
171
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes, step_tag):
172
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
173
+ out_dir.mkdir(parents=True, exist_ok=True)
174
+ out_path = out_dir / "trajectories.jsonl"
175
+ env = make_env_fn()
176
+ collected = 0
177
+ summary_returns = []
178
+ with out_path.open("w") as f:
179
+ while collected < n_episodes:
180
+ state, _ = env.reset(seed=args.seed + 200000 + collected)
181
+ traj_rewards = []
182
+ done = False
183
+ while not done:
184
+ with torch.no_grad():
185
+ logits = agent_model.actor(torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0))
186
+ action = int(torch.argmax(logits, dim=1).item())
187
+ next_state, reward, terminated, truncated, info = env.step(action)
188
+ traj_rewards.append(float(reward))
189
+ done = bool(terminated) or bool(truncated)
190
+ state = next_state
191
+ ep_ret = float(sum(traj_rewards))
192
+ f.write(json.dumps({"episode_return": ep_ret}) + "\n")
193
+ summary_returns.append(ep_ret)
194
+ collected += 1
195
+ env.close()
196
+ try:
197
+ metrics = {
198
+ "global_step": int(step_tag),
199
+ "episodes": int(n_episodes),
200
+ "avg_return": float(np.mean(summary_returns)) if len(summary_returns) else 0.0,
201
+ "std_return": float(np.std(summary_returns)) if len(summary_returns) else 0.0,
202
+ }
203
+ with (out_dir / "metrics.json").open("w") as mf:
204
+ json.dump(metrics, mf)
205
+ except Exception as e:
206
+ print(f"Warning: failed to write eval metrics: {e}")
207
+
208
+ eval_splits = 2
209
+ eval_episodes = 4000
210
+ eval_every_iters = max(1, (args.total_timesteps // args.batch_size) // eval_splits)
211
+
212
+ for iteration in range(1, args.num_iterations + 1):
213
+ # Anneal LR
214
+ if args.anneal_lr:
215
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
216
+ lrnow = frac * args.learning_rate
217
+ optimizer.param_groups[0]["lr"] = lrnow
218
+
219
+ for step in range(0, args.num_steps):
220
+ global_step += args.num_envs
221
+ obs[step] = next_obs
222
+ dones[step] = next_done
223
+
224
+ with torch.no_grad():
225
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
226
+ values[step] = value.flatten()
227
+ actions[step] = action
228
+ logprobs[step] = logprob
229
+
230
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
231
+ next_done = np.logical_or(terminations, truncations)
232
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
233
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
234
+
235
+ # Since gamma=0 for bandit, GAE simplifies but we keep general code
236
+ with torch.no_grad():
237
+ next_value = agent.get_value(next_obs).reshape(1, -1)
238
+ advantages = torch.zeros_like(rewards).to(device)
239
+ lastgaelam = 0
240
+ for t in reversed(range(args.num_steps)):
241
+ if t == args.num_steps - 1:
242
+ nextnonterminal = 1.0 - next_done
243
+ nextvalues = next_value
244
+ else:
245
+ nextnonterminal = 1.0 - dones[t + 1]
246
+ nextvalues = values[t + 1]
247
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
248
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
249
+ returns = advantages + values
250
+
251
+ # flatten batch
252
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
253
+ b_logprobs = logprobs.reshape(-1)
254
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
255
+ b_advantages = advantages.reshape(-1)
256
+ b_returns = returns.reshape(-1)
257
+ b_values = values.reshape(-1)
258
+
259
+ # update
260
+ b_inds = np.arange(args.batch_size)
261
+ for epoch in range(args.update_epochs):
262
+ np.random.shuffle(b_inds)
263
+ for start in range(0, args.batch_size, args.minibatch_size):
264
+ end = start + args.minibatch_size
265
+ mb_inds = b_inds[start:end]
266
+
267
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
268
+ logratio = newlogprob - b_logprobs[mb_inds]
269
+ ratio = logratio.exp()
270
+
271
+ with torch.no_grad():
272
+ old_approx_kl = (-logratio).mean()
273
+ approx_kl = ((ratio - 1) - logratio).mean()
274
+
275
+ mb_advantages = b_advantages[mb_inds]
276
+ if args.norm_adv:
277
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
278
+
279
+ pg_loss1 = -mb_advantages * ratio
280
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
281
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
282
+
283
+ newvalue = newvalue.view(-1)
284
+ if args.clip_vloss:
285
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
286
+ v_clipped = b_values[mb_inds] + torch.clamp(
287
+ newvalue - b_values[mb_inds], -args.clip_coef, args.clip_coef,
288
+ )
289
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
290
+ v_loss = 0.5 * torch.max(v_loss_unclipped, v_loss_clipped).mean()
291
+ else:
292
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
293
+
294
+ entropy_loss = entropy.mean()
295
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
296
+
297
+ optimizer.zero_grad()
298
+ loss.backward()
299
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
300
+ optimizer.step()
301
+
302
+ if args.target_kl is not None and approx_kl > args.target_kl:
303
+ break
304
+
305
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
306
+ var_y = np.var(y_true)
307
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
308
+
309
+ sps = int(global_step / (time.time() - start_time))
310
+ progress = 100 * iteration / args.num_iterations
311
+ print(f"[{progress:5.1f}%] Iter {iteration:4d}/{args.num_iterations} | "
312
+ f"SPS: {sps:5d} | "
313
+ f"Reward: {rewards.mean().item():6.3f} | "
314
+ f"Value: {values.mean().item():6.3f} | "
315
+ f"VLoss: {v_loss.item():.4f} | "
316
+ f"PLoss: {pg_loss.item():.4f} | "
317
+ f"Ent: {entropy_loss.item():.4f}")
318
+ if args.track:
319
+ try:
320
+ import wandb
321
+ wandb.log({
322
+ "global_step": int(global_step),
323
+ "train/value_loss": float(v_loss.item()),
324
+ "train/policy_loss": float(pg_loss.item()),
325
+ "train/entropy": float(entropy_loss.item()),
326
+ "losses/explained_variance": float(explained_var),
327
+ "charts/avg_reward": float(rewards.mean().item()),
328
+ "charts/avg_value": float(values.mean().item()),
329
+ "perf/SPS": int(sps),
330
+ "train/learning_rate": float(optimizer.param_groups[0]["lr"]),
331
+ }, step=global_step)
332
+ except Exception:
333
+ pass
334
+
335
+ # periodic evaluation collection
336
+ if iteration % eval_every_iters == 0:
337
+ try:
338
+ eval_thunk = make_env(0, run_name, args.seed + 9999, args.feature_dim_per_name, False)
339
+ collect_eval_trajectories(agent, eval_thunk, n_episodes=eval_episodes, step_tag=global_step)
340
+ except Exception as e:
341
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
342
+
343
+ envs.close()
cleanrl/cleanrl/ppo_blackjack_refine.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PPO for RAGEN Blackjack - Final Fixed Version
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Dict, Any, List
8
+ import json
9
+ import sys
10
+ from collections import deque
11
+
12
+ import gymnasium as gym
13
+ import numpy as np
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.optim as optim
17
+ import tyro
18
+ from torch.distributions.categorical import Categorical
19
+
20
+ # 确保能找到 ragen 模块
21
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../'))
22
+
23
+ try:
24
+ from ragen.env.blackjack.env import BlackjackEnv, hand_sum, usable_ace
25
+ from ragen.env.blackjack.config import BlackjackEnvConfig
26
+ except ImportError:
27
+ # Fallback for standalone testing if ragen is not installed
28
+ print("Warning: ragen module not found, using mocks for imports logic check only.")
29
+ pass
30
+
31
+ class BlackjackWrapper(gym.Env):
32
+ """
33
+ Direct State Access Wrapper.
34
+ 直接读取环境内部状态,效率最高且无 Bug。
35
+ """
36
+ metadata = {"render_modes": ["ansi", "human", "text"]}
37
+
38
+ def __init__(self):
39
+ super().__init__()
40
+ cfg = BlackjackEnvConfig(render_mode='text')
41
+ self._env = BlackjackEnv(cfg)
42
+ # Observation: [Player Sum, Dealer Card, Usable Ace]
43
+ self.observation_space = gym.spaces.Box(low=0.0, high=32.0, shape=(3,), dtype=np.float32)
44
+ self.action_space = gym.spaces.Discrete(2)
45
+
46
+ def _get_obs(self):
47
+ p_hand = self._env.player
48
+ d_hand = self._env.dealer
49
+ p_sum = hand_sum(p_hand)
50
+ d_show = d_hand[0] if d_hand else 0
51
+ u_ace = 1.0 if usable_ace(p_hand) else 0.0
52
+ if p_sum > 30: p_sum = 30.0
53
+ return np.array([float(p_sum), float(d_show), u_ace], dtype=np.float32)
54
+
55
+ def get_text_observation(self):
56
+ """
57
+ 生成与真实环境反馈完全一致的文本描述。
58
+ """
59
+ p_hand = self._env.player
60
+ d_hand = self._env.dealer
61
+ p_sum = hand_sum(p_hand)
62
+ # 庄家显示的牌
63
+ d_show = d_hand[0] if d_hand else "Unknown"
64
+
65
+ # 构建 Usable Ace 描述 (根据你的示例)
66
+ u_ace_str = "You possess a usable Ace." if usable_ace(p_hand) else "No usable ace."
67
+
68
+ # 严格对齐 Target Format
69
+ text = (
70
+ "=== Blackjack Game State ===\n"
71
+ f"Your Hand: {p_hand} (Total: {p_sum}).\n"
72
+ f"Note: {u_ace_str}\n"
73
+ f"Dealer's Visible Card: {d_show}.\n\n"
74
+ "Available Actions:\n"
75
+ "- Action 1: Stick (Stop)\n"
76
+ "- Action 2: Hit (Add card)"
77
+ )
78
+ return text
79
+
80
+ def reset(self, *, seed: int | None = None, options: Dict[str, Any] | None = None):
81
+ self._env.reset(seed=seed)
82
+ return self._get_obs(), {}
83
+
84
+ def step(self, action: int):
85
+ mapped = int(action) + 1
86
+ _, reward, done, info = self._env.step(mapped)
87
+ obs = self._get_obs()
88
+ info = info or {}
89
+ return obs, float(reward), bool(done), False, info
90
+
91
+ def render(self):
92
+ return self._env.render()
93
+
94
+ def close(self):
95
+ self._env.close()
96
+
97
+
98
+ @dataclass
99
+ class Args:
100
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
101
+ seed: int = 1
102
+ torch_deterministic: bool = True
103
+ cuda: bool = True
104
+ track: bool = False
105
+ wandb_project_name: str = "ragen_blackjack"
106
+ wandb_entity: str | None = None
107
+ capture_video: bool = False
108
+
109
+ env_id: str = "Blackjack"
110
+ total_timesteps: int = 1000_000
111
+ learning_rate: float = 5e-4
112
+ num_envs: int = 8
113
+ num_steps: int = 128
114
+ anneal_lr: bool = True
115
+ gamma: float = 0.85
116
+ gae_lambda: float = 0.95
117
+ num_minibatches: int = 4
118
+ update_epochs: int = 4
119
+ norm_adv: bool = True
120
+ clip_coef: float = 0.2
121
+ clip_vloss: bool = True
122
+ ent_coef: float = 0.01
123
+ vf_coef: float = 0.5
124
+ max_grad_norm: float = 0.5
125
+ target_kl: float | None = None
126
+
127
+ batch_size: int = 0
128
+ minibatch_size: int = 0
129
+ num_iterations: int = 0
130
+ eval_splits: int = 2
131
+ eval_episodes: int = 10000
132
+
133
+
134
+ def make_env(idx, run_name, seed, capture_video=False):
135
+ def thunk():
136
+ env = BlackjackWrapper()
137
+ env = gym.wrappers.TimeLimit(env, max_episode_steps=32)
138
+ if capture_video and idx == 0:
139
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
140
+ return env
141
+ return thunk
142
+
143
+
144
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
145
+ torch.nn.init.orthogonal_(layer.weight, std)
146
+ torch.nn.init.constant_(layer.bias, bias_const)
147
+ return layer
148
+
149
+
150
+ class Agent(nn.Module):
151
+ def __init__(self, envs):
152
+ super().__init__()
153
+ obs_shape = int(np.array(envs.single_observation_space.shape).prod())
154
+ hidden = 128
155
+ self.feature_extractor = nn.Sequential(
156
+ layer_init(nn.Linear(obs_shape, hidden)),
157
+ nn.Tanh(),
158
+ layer_init(nn.Linear(hidden, hidden)),
159
+ nn.Tanh(),
160
+ )
161
+ self.critic = layer_init(nn.Linear(hidden, 1), std=1.0)
162
+ self.actor = layer_init(nn.Linear(hidden, envs.single_action_space.n), std=0.01)
163
+
164
+ def get_value(self, x):
165
+ h = self.feature_extractor(x)
166
+ return self.critic(h)
167
+
168
+ def get_action_and_value(self, x, action=None):
169
+ h = self.feature_extractor(x)
170
+ logits = self.actor(h)
171
+ probs = Categorical(logits=logits)
172
+ if action is None:
173
+ action = probs.sample()
174
+ return action, probs.log_prob(action), probs.entropy(), self.critic(h)
175
+
176
+
177
+ if __name__ == "__main__":
178
+ args = tyro.cli(Args)
179
+ args.batch_size = int(args.num_envs * args.num_steps)
180
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
181
+ args.num_iterations = args.total_timesteps // args.batch_size
182
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
183
+
184
+ if args.track:
185
+ import wandb
186
+ wandb.init(
187
+ project=args.wandb_project_name,
188
+ entity=args.wandb_entity,
189
+ config=vars(args),
190
+ name=run_name,
191
+ monitor_gym=True,
192
+ save_code=True,
193
+ )
194
+
195
+ random.seed(args.seed)
196
+ np.random.seed(args.seed)
197
+ torch.manual_seed(args.seed)
198
+ torch.backends.cudnn.deterministic = args.torch_deterministic
199
+
200
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
201
+ print(f"Using device: {device}")
202
+
203
+ # Envs
204
+ envs = gym.vector.SyncVectorEnv([
205
+ make_env(i, run_name, args.seed, args.capture_video)
206
+ for i in range(args.num_envs)
207
+ ])
208
+
209
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete)
210
+
211
+ agent = Agent(envs).to(device)
212
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
213
+
214
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
215
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
216
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
217
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
218
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
219
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
220
+
221
+ global_step = 0
222
+ start_time = time.time()
223
+ next_obs, _ = envs.reset(seed=args.seed)
224
+ next_obs = torch.Tensor(next_obs).to(device)
225
+ next_done = torch.zeros(args.num_envs).to(device)
226
+
227
+ running_returns = np.zeros(args.num_envs, dtype=np.float32)
228
+
229
+ # --- 修复后的 Eval 函数 (包含文本保存) ---
230
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes, step_tag):
231
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
232
+ out_dir.mkdir(parents=True, exist_ok=True)
233
+ out_path = out_dir / "trajectories.jsonl"
234
+ env = make_env_fn()
235
+ collected = 0
236
+ summary_returns = []
237
+ summary_success = []
238
+ with out_path.open("w") as f:
239
+ while collected < n_episodes:
240
+ state, _ = env.reset(seed=args.seed + 100000 + collected)
241
+
242
+ # 初始化轨迹数据,同时保存数字状态和文本状态
243
+ traj_states = [state.tolist()]
244
+ # 注意:必须调用 env.get_text_observation(),因为 env 是被 TimeLimit 包裹的,
245
+ # 所以要访问 wrapper 方法可能需要 env.unwrapped.get_text_observation(),
246
+ # 但 make_env 中我们直接用了 BlackjackWrapper,TimeLimit 应该会透传 getattr,
247
+ # 如果报错改为 env.unwrapped.get_text_observation()
248
+ try:
249
+ init_text = env.get_text_observation()
250
+ except AttributeError:
251
+ init_text = env.unwrapped.get_text_observation()
252
+
253
+ traj_text_states = [init_text]
254
+
255
+ traj_actions = []
256
+ traj_rewards = []
257
+ traj_success = []
258
+ done = False
259
+ while not done:
260
+ with torch.no_grad():
261
+ state_tensor = torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0)
262
+ hidden = agent_model.feature_extractor(state_tensor)
263
+ logits = agent_model.actor(hidden)
264
+ action = int(torch.argmax(logits, dim=1).item())
265
+
266
+ next_state, reward, terminated, truncated, info = env.step(action)
267
+ traj_actions.append(int(action))
268
+ traj_rewards.append(float(reward))
269
+ traj_success.append(bool((info or {}).get('success', False)))
270
+
271
+ state = next_state
272
+ traj_states.append(state.tolist())
273
+
274
+ # 只有未结束时,或者为了完整性,我们通常把每一步后的状态也存下来
275
+ if not (terminated or truncated):
276
+ try:
277
+ curr_text = env.get_text_observation()
278
+ except AttributeError:
279
+ curr_text = env.unwrapped.get_text_observation()
280
+ traj_text_states.append(curr_text)
281
+
282
+ done = bool(terminated) or bool(truncated)
283
+
284
+ ep_ret = float(sum(traj_rewards))
285
+ ep_succ = bool(any(traj_success))
286
+ record = {
287
+ "states": traj_states,
288
+ "text_states": traj_text_states, # <--- 关键:保存文本状态
289
+ "actions": traj_actions,
290
+ "rewards": traj_rewards,
291
+ "success": traj_success,
292
+ "episode_return": ep_ret,
293
+ "episode_success": ep_succ,
294
+ }
295
+ f.write(json.dumps(record) + "\n")
296
+ collected += 1
297
+ summary_returns.append(ep_ret)
298
+ summary_success.append(1.0 if ep_succ else 0.0)
299
+ env.close()
300
+ return {"success_rate": np.mean(summary_success), "avg_return": np.mean(summary_returns)}
301
+
302
+ eval_every_iters = max(1, args.num_iterations // args.eval_splits)
303
+ recent_winrates = deque(maxlen=50)
304
+ winrate_ema = None
305
+
306
+ for iteration in range(1, args.num_iterations + 1):
307
+ if args.anneal_lr:
308
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
309
+ lrnow = frac * args.learning_rate
310
+ optimizer.param_groups[0]["lr"] = lrnow
311
+
312
+ iter_outcomes: List[int] = []
313
+
314
+ for step in range(0, args.num_steps):
315
+ global_step += args.num_envs
316
+ obs[step] = next_obs
317
+ dones[step] = next_done
318
+
319
+ with torch.no_grad():
320
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
321
+ values[step] = value.flatten()
322
+ actions[step] = action
323
+ logprobs[step] = logprob
324
+
325
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
326
+ next_done = np.logical_or(terminations, truncations)
327
+
328
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
329
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
330
+
331
+ running_returns += reward
332
+ for i in range(args.num_envs):
333
+ if terminations[i] or truncations[i]:
334
+ final_ret = running_returns[i]
335
+ if final_ret > 0: iter_outcomes.append(1)
336
+ elif final_ret < 0: iter_outcomes.append(-1)
337
+ else: iter_outcomes.append(0)
338
+ running_returns[i] = 0.0
339
+
340
+ with torch.no_grad():
341
+ next_value = agent.get_value(next_obs).reshape(1, -1)
342
+ advantages = torch.zeros_like(rewards).to(device)
343
+ lastgaelam = 0
344
+ for t in reversed(range(args.num_steps)):
345
+ if t == args.num_steps - 1:
346
+ nextnonterminal = 1.0 - next_done
347
+ nextvalues = next_value
348
+ else:
349
+ nextnonterminal = 1.0 - dones[t + 1]
350
+ nextvalues = values[t + 1]
351
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
352
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
353
+ returns = advantages + values
354
+
355
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
356
+ b_logprobs = logprobs.reshape(-1)
357
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
358
+ b_advantages = advantages.reshape(-1)
359
+ b_returns = returns.reshape(-1)
360
+ b_values = values.reshape(-1)
361
+
362
+ b_inds = np.arange(args.batch_size)
363
+ clipfracs = []
364
+ for epoch in range(args.update_epochs):
365
+ np.random.shuffle(b_inds)
366
+ for start in range(0, args.batch_size, args.minibatch_size):
367
+ end = start + args.minibatch_size
368
+ mb_inds = b_inds[start:end]
369
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
370
+ logratio = newlogprob - b_logprobs[mb_inds]
371
+ ratio = logratio.exp()
372
+ with torch.no_grad():
373
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
374
+ mb_advantages = b_advantages[mb_inds]
375
+ if args.norm_adv:
376
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
377
+ pg_loss1 = -mb_advantages * ratio
378
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
379
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
380
+
381
+ newvalue = newvalue.view(-1)
382
+ if args.clip_vloss:
383
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
384
+ v_clipped = b_values[mb_inds] + torch.clamp(newvalue - b_values[mb_inds], -args.clip_coef, args.clip_coef)
385
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
386
+ v_loss = 0.5 * torch.max(v_loss_unclipped, v_loss_clipped).mean()
387
+ else:
388
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
389
+
390
+ entropy_loss = entropy.mean()
391
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
392
+ optimizer.zero_grad()
393
+ loss.backward()
394
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
395
+ optimizer.step()
396
+
397
+ sps = int(global_step / (time.time() - start_time))
398
+ progress = 100 * iteration / args.num_iterations
399
+
400
+ if len(iter_outcomes) > 0:
401
+ total = len(iter_outcomes)
402
+ wr = iter_outcomes.count(1) / total
403
+ dr = iter_outcomes.count(0) / total
404
+ lr = iter_outcomes.count(-1) / total
405
+ recent_winrates.append(wr)
406
+ if winrate_ema is None: winrate_ema = wr
407
+ else: winrate_ema = 0.1 * wr + 0.9 * winrate_ema
408
+ else:
409
+ wr = dr = lr = 0.0
410
+
411
+ print(f"[{progress:5.1f}%] Iter {iteration:4d} | Rew: {rewards.mean().item():.3f} | WR: {wr:.3f} | LR: {lr:.3f} | DR: {dr:.3f}")
412
+
413
+ if args.track:
414
+ import wandb
415
+ wandb.log({
416
+ "charts/avg_reward": float(rewards.mean().item()),
417
+ "charts/win_rate": wr,
418
+ "charts/draw_rate": dr,
419
+ "charts/loss_rate": lr,
420
+ "global_step": global_step,
421
+ })
422
+
423
+ if iteration == 1 or iteration % eval_every_iters == 0:
424
+ print(f"Running evaluation...")
425
+ try:
426
+ def eval_thunk():
427
+ return make_env(0, run_name, args.seed + 9999, False)()
428
+ metrics = collect_eval_trajectories(agent, eval_thunk, n_episodes=args.eval_episodes, step_tag=global_step)
429
+ if args.track:
430
+ wandb.log({"eval/success_rate": metrics["success_rate"], "global_step": global_step})
431
+ except Exception as e:
432
+ print(f"Eval failed: {e}")
433
+ import traceback
434
+ traceback.print_exc()
435
+
436
+ envs.close()
cleanrl/cleanrl/ppo_continuous_action.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/ppo/#ppo_continuous_actionpy
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+
7
+ import gymnasium as gym
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.optim as optim
12
+ import tyro
13
+ from torch.distributions.normal import Normal
14
+ from torch.utils.tensorboard import SummaryWriter
15
+
16
+
17
+ @dataclass
18
+ class Args:
19
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
20
+ """the name of this experiment"""
21
+ seed: int = 1
22
+ """seed of the experiment"""
23
+ torch_deterministic: bool = True
24
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
25
+ cuda: bool = True
26
+ """if toggled, cuda will be enabled by default"""
27
+ track: bool = False
28
+ """if toggled, this experiment will be tracked with Weights and Biases"""
29
+ wandb_project_name: str = "cleanRL"
30
+ """the wandb's project name"""
31
+ wandb_entity: str = None
32
+ """the entity (team) of wandb's project"""
33
+ capture_video: bool = False
34
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
35
+ save_model: bool = False
36
+ """whether to save model into the `runs/{run_name}` folder"""
37
+ upload_model: bool = False
38
+ """whether to upload the saved model to huggingface"""
39
+ hf_entity: str = ""
40
+ """the user or org name of the model repository from the Hugging Face Hub"""
41
+
42
+ # Algorithm specific arguments
43
+ env_id: str = "HalfCheetah-v4"
44
+ """the id of the environment"""
45
+ total_timesteps: int = 1000000
46
+ """total timesteps of the experiments"""
47
+ learning_rate: float = 3e-4
48
+ """the learning rate of the optimizer"""
49
+ num_envs: int = 1
50
+ """the number of parallel game environments"""
51
+ num_steps: int = 2048
52
+ """the number of steps to run in each environment per policy rollout"""
53
+ anneal_lr: bool = True
54
+ """Toggle learning rate annealing for policy and value networks"""
55
+ gamma: float = 0.99
56
+ """the discount factor gamma"""
57
+ gae_lambda: float = 0.95
58
+ """the lambda for the general advantage estimation"""
59
+ num_minibatches: int = 32
60
+ """the number of mini-batches"""
61
+ update_epochs: int = 10
62
+ """the K epochs to update the policy"""
63
+ norm_adv: bool = True
64
+ """Toggles advantages normalization"""
65
+ clip_coef: float = 0.2
66
+ """the surrogate clipping coefficient"""
67
+ clip_vloss: bool = True
68
+ """Toggles whether or not to use a clipped loss for the value function, as per the paper."""
69
+ ent_coef: float = 0.0
70
+ """coefficient of the entropy"""
71
+ vf_coef: float = 0.5
72
+ """coefficient of the value function"""
73
+ max_grad_norm: float = 0.5
74
+ """the maximum norm for the gradient clipping"""
75
+ target_kl: float = None
76
+ """the target KL divergence threshold"""
77
+
78
+ # to be filled in runtime
79
+ batch_size: int = 0
80
+ """the batch size (computed in runtime)"""
81
+ minibatch_size: int = 0
82
+ """the mini-batch size (computed in runtime)"""
83
+ num_iterations: int = 0
84
+ """the number of iterations (computed in runtime)"""
85
+
86
+
87
+ def make_env(env_id, idx, capture_video, run_name, gamma):
88
+ def thunk():
89
+ if capture_video and idx == 0:
90
+ env = gym.make(env_id, render_mode="rgb_array")
91
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
92
+ else:
93
+ env = gym.make(env_id)
94
+ env = gym.wrappers.FlattenObservation(env) # deal with dm_control's Dict observation space
95
+ env = gym.wrappers.RecordEpisodeStatistics(env)
96
+ env = gym.wrappers.ClipAction(env)
97
+ env = gym.wrappers.NormalizeObservation(env)
98
+ env = gym.wrappers.TransformObservation(env, lambda obs: np.clip(obs, -10, 10))
99
+ env = gym.wrappers.NormalizeReward(env, gamma=gamma)
100
+ env = gym.wrappers.TransformReward(env, lambda reward: np.clip(reward, -10, 10))
101
+ return env
102
+
103
+ return thunk
104
+
105
+
106
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
107
+ torch.nn.init.orthogonal_(layer.weight, std)
108
+ torch.nn.init.constant_(layer.bias, bias_const)
109
+ return layer
110
+
111
+
112
+ class Agent(nn.Module):
113
+ def __init__(self, envs):
114
+ super().__init__()
115
+ self.critic = nn.Sequential(
116
+ layer_init(nn.Linear(np.array(envs.single_observation_space.shape).prod(), 64)),
117
+ nn.Tanh(),
118
+ layer_init(nn.Linear(64, 64)),
119
+ nn.Tanh(),
120
+ layer_init(nn.Linear(64, 1), std=1.0),
121
+ )
122
+ self.actor_mean = nn.Sequential(
123
+ layer_init(nn.Linear(np.array(envs.single_observation_space.shape).prod(), 64)),
124
+ nn.Tanh(),
125
+ layer_init(nn.Linear(64, 64)),
126
+ nn.Tanh(),
127
+ layer_init(nn.Linear(64, np.prod(envs.single_action_space.shape)), std=0.01),
128
+ )
129
+ self.actor_logstd = nn.Parameter(torch.zeros(1, np.prod(envs.single_action_space.shape)))
130
+
131
+ def get_value(self, x):
132
+ return self.critic(x)
133
+
134
+ def get_action_and_value(self, x, action=None):
135
+ action_mean = self.actor_mean(x)
136
+ action_logstd = self.actor_logstd.expand_as(action_mean)
137
+ action_std = torch.exp(action_logstd)
138
+ probs = Normal(action_mean, action_std)
139
+ if action is None:
140
+ action = probs.sample()
141
+ return action, probs.log_prob(action).sum(1), probs.entropy().sum(1), self.critic(x)
142
+
143
+
144
+ if __name__ == "__main__":
145
+ args = tyro.cli(Args)
146
+ args.batch_size = int(args.num_envs * args.num_steps)
147
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
148
+ args.num_iterations = args.total_timesteps // args.batch_size
149
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
150
+ if args.track:
151
+ import wandb
152
+
153
+ wandb.init(
154
+ project=args.wandb_project_name,
155
+ entity=args.wandb_entity,
156
+ sync_tensorboard=True,
157
+ config=vars(args),
158
+ name=run_name,
159
+ monitor_gym=True,
160
+ save_code=True,
161
+ )
162
+ writer = SummaryWriter(f"runs/{run_name}")
163
+ writer.add_text(
164
+ "hyperparameters",
165
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
166
+ )
167
+
168
+ # TRY NOT TO MODIFY: seeding
169
+ random.seed(args.seed)
170
+ np.random.seed(args.seed)
171
+ torch.manual_seed(args.seed)
172
+ torch.backends.cudnn.deterministic = args.torch_deterministic
173
+
174
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
175
+
176
+ # env setup
177
+ envs = gym.vector.SyncVectorEnv(
178
+ [make_env(args.env_id, i, args.capture_video, run_name, args.gamma) for i in range(args.num_envs)]
179
+ )
180
+ assert isinstance(envs.single_action_space, gym.spaces.Box), "only continuous action space is supported"
181
+
182
+ agent = Agent(envs).to(device)
183
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
184
+
185
+ # ALGO Logic: Storage setup
186
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
187
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
188
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
189
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
190
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
191
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
192
+
193
+ # TRY NOT TO MODIFY: start the game
194
+ global_step = 0
195
+ start_time = time.time()
196
+ next_obs, _ = envs.reset(seed=args.seed)
197
+ next_obs = torch.Tensor(next_obs).to(device)
198
+ next_done = torch.zeros(args.num_envs).to(device)
199
+
200
+ for iteration in range(1, args.num_iterations + 1):
201
+ # Annealing the rate if instructed to do so.
202
+ if args.anneal_lr:
203
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
204
+ lrnow = frac * args.learning_rate
205
+ optimizer.param_groups[0]["lr"] = lrnow
206
+
207
+ for step in range(0, args.num_steps):
208
+ global_step += args.num_envs
209
+ obs[step] = next_obs
210
+ dones[step] = next_done
211
+
212
+ # ALGO LOGIC: action logic
213
+ with torch.no_grad():
214
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
215
+ values[step] = value.flatten()
216
+ actions[step] = action
217
+ logprobs[step] = logprob
218
+
219
+ # TRY NOT TO MODIFY: execute the game and log data.
220
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
221
+ next_done = np.logical_or(terminations, truncations)
222
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
223
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
224
+
225
+ if "final_info" in infos:
226
+ for info in infos["final_info"]:
227
+ if info and "episode" in info:
228
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
229
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
230
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
231
+
232
+ # bootstrap value if not done
233
+ with torch.no_grad():
234
+ next_value = agent.get_value(next_obs).reshape(1, -1)
235
+ advantages = torch.zeros_like(rewards).to(device)
236
+ lastgaelam = 0
237
+ for t in reversed(range(args.num_steps)):
238
+ if t == args.num_steps - 1:
239
+ nextnonterminal = 1.0 - next_done
240
+ nextvalues = next_value
241
+ else:
242
+ nextnonterminal = 1.0 - dones[t + 1]
243
+ nextvalues = values[t + 1]
244
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
245
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
246
+ returns = advantages + values
247
+
248
+ # flatten the batch
249
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
250
+ b_logprobs = logprobs.reshape(-1)
251
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
252
+ b_advantages = advantages.reshape(-1)
253
+ b_returns = returns.reshape(-1)
254
+ b_values = values.reshape(-1)
255
+
256
+ # Optimizing the policy and value network
257
+ b_inds = np.arange(args.batch_size)
258
+ clipfracs = []
259
+ for epoch in range(args.update_epochs):
260
+ np.random.shuffle(b_inds)
261
+ for start in range(0, args.batch_size, args.minibatch_size):
262
+ end = start + args.minibatch_size
263
+ mb_inds = b_inds[start:end]
264
+
265
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions[mb_inds])
266
+ logratio = newlogprob - b_logprobs[mb_inds]
267
+ ratio = logratio.exp()
268
+
269
+ with torch.no_grad():
270
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
271
+ old_approx_kl = (-logratio).mean()
272
+ approx_kl = ((ratio - 1) - logratio).mean()
273
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
274
+
275
+ mb_advantages = b_advantages[mb_inds]
276
+ if args.norm_adv:
277
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
278
+
279
+ # Policy loss
280
+ pg_loss1 = -mb_advantages * ratio
281
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
282
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
283
+
284
+ # Value loss
285
+ newvalue = newvalue.view(-1)
286
+ if args.clip_vloss:
287
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
288
+ v_clipped = b_values[mb_inds] + torch.clamp(
289
+ newvalue - b_values[mb_inds],
290
+ -args.clip_coef,
291
+ args.clip_coef,
292
+ )
293
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
294
+ v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped)
295
+ v_loss = 0.5 * v_loss_max.mean()
296
+ else:
297
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
298
+
299
+ entropy_loss = entropy.mean()
300
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
301
+
302
+ optimizer.zero_grad()
303
+ loss.backward()
304
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
305
+ optimizer.step()
306
+
307
+ if args.target_kl is not None and approx_kl > args.target_kl:
308
+ break
309
+
310
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
311
+ var_y = np.var(y_true)
312
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
313
+
314
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
315
+ writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step)
316
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
317
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
318
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
319
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
320
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
321
+ writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step)
322
+ writer.add_scalar("losses/explained_variance", explained_var, global_step)
323
+ print("SPS:", int(global_step / (time.time() - start_time)))
324
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
325
+
326
+ if args.save_model:
327
+ model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
328
+ torch.save(agent.state_dict(), model_path)
329
+ print(f"model saved to {model_path}")
330
+ from cleanrl_utils.evals.ppo_eval import evaluate
331
+
332
+ episodic_returns = evaluate(
333
+ model_path,
334
+ make_env,
335
+ args.env_id,
336
+ eval_episodes=10,
337
+ run_name=f"{run_name}-eval",
338
+ Model=Agent,
339
+ device=device,
340
+ gamma=args.gamma,
341
+ )
342
+ for idx, episodic_return in enumerate(episodic_returns):
343
+ writer.add_scalar("eval/episodic_return", episodic_return, idx)
344
+
345
+ if args.upload_model:
346
+ from cleanrl_utils.huggingface import push_to_hub
347
+
348
+ repo_name = f"{args.env_id}-{args.exp_name}-seed{args.seed}"
349
+ repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
350
+ push_to_hub(args, episodic_returns, repo_id, "PPO", f"runs/{run_name}", f"videos/{run_name}-eval")
351
+
352
+ envs.close()
353
+ writer.close()
cleanrl/cleanrl/ppo_rubikscube.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PPO with small MLP for RAGEN Rubik's Cube 2x2 using the existing env (no env edits)
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Tuple, Dict, Any, List
8
+ import json
9
+ import re
10
+
11
+ import gymnasium as gym
12
+ import numpy as np
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.optim as optim
16
+ import tyro
17
+ from torch.distributions.categorical import Categorical
18
+
19
+ import sys
20
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../'))
21
+
22
+ from ragen.env.rubikscube.env import RubiksCube2x2Env
23
+ from ragen.env.rubikscube.config import RubiksCube2x2Config
24
+
25
+
26
+ class RubiksCubeWrapper(gym.Env):
27
+ """
28
+ Adapter to use ragen RubiksCube2x2Env with Gymnasium vector API.
29
+ - Converts text observation to one-hot vector of 24 stickers x 6 colors.
30
+ - Maps agent actions [0..11] to env actions [1..12].
31
+ - Exposes proper observation_space and action_space.
32
+ """
33
+ metadata = {"render_modes": ["rgb_array", "human", "ansi"]}
34
+
35
+ def __init__(self, env: RubiksCube2x2Env):
36
+ super().__init__()
37
+ self._env = env
38
+ # 24 stickers, 6 colors -> one-hot size 144
39
+ self._colors = ['W', 'O', 'G', 'R', 'B', 'Y']
40
+ self._color_to_idx = {c: i for i, c in enumerate(self._colors)}
41
+ self.observation_space = gym.spaces.Box(low=0.0, high=1.0, shape=(24 * len(self._colors),), dtype=np.float32)
42
+ self.action_space = gym.spaces.Discrete(12)
43
+ # precompile regex to extract 4 letters within [X, X]\n [X, X]
44
+ # Lines look like: "Up (U): [W, W]\n [W, W]"
45
+ self._face_pat = re.compile(r"\[(?:\s*([A-Z])\s*,\s*([A-Z])\s*\])\n\s*\[(?:\s*([A-Z])\s*,\s*([A-Z])\s*\])")
46
+
47
+ def _encode_obs(self, text_obs: str) -> np.ndarray:
48
+ # Extract the six face blocks in the order U, L, F, R, B, D as rendered
49
+ faces_order = ["Up (U):", "Left (L):", "Front (F):", "Right (R):", "Back (B):", "Down (D):"]
50
+ onehots: List[int] = []
51
+ # Build a map from header to its block text
52
+ lines = text_obs.splitlines()
53
+ # Collect blocks starting after header line and including the next line for second row
54
+ i = 0
55
+ blocks: List[str] = []
56
+ while i < len(lines):
57
+ line = lines[i]
58
+ for header in faces_order:
59
+ if line.startswith(header):
60
+ # Join current line's bracketed pair and the next line (which contains the second pair)
61
+ # Remove the "Header:" prefix to keep only the bracket portions
62
+ content = line[len(header):].strip()
63
+ next_line = lines[i + 1] if i + 1 < len(lines) else ""
64
+ block = f"{content}\n{next_line}"
65
+ blocks.append(block)
66
+ break
67
+ i += 1
68
+ # Fallback: if regex fails, return zeros
69
+ if len(blocks) != 6:
70
+ return np.zeros(24 * len(self._colors), dtype=np.float32)
71
+ stickers: List[int] = []
72
+ for blk in blocks:
73
+ m = self._face_pat.search(blk)
74
+ if not m:
75
+ return np.zeros(24 * len(self._colors), dtype=np.float32)
76
+ # order: 0,1,2,3 per render() doc
77
+ c0, c1, c2, c3 = m.group(1), m.group(2), m.group(3), m.group(4)
78
+ stickers.extend([c0, c1, c2, c3])
79
+ # stickers now length 24; convert to one-hot
80
+ grid = np.zeros((24, len(self._colors)), dtype=np.float32)
81
+ for idx, ch in enumerate(stickers):
82
+ cidx = self._color_to_idx.get(ch, None)
83
+ if cidx is not None:
84
+ grid[idx, cidx] = 1.0
85
+ return grid.reshape(-1)
86
+
87
+ def reset(self, *, seed: int | None = None, options: Dict[str, Any] | None = None):
88
+ text_obs = self._env.reset(seed=seed)
89
+ obs = self._encode_obs(text_obs)
90
+ return obs, {}
91
+
92
+ def step(self, action: int):
93
+ mapped = int(action) + 1 # 0..11 -> 1..12
94
+ text_obs, reward, done, info = self._env.step(mapped)
95
+ obs = self._encode_obs(text_obs)
96
+ terminated = bool(done)
97
+ truncated = False
98
+ return obs, float(reward), terminated, truncated, info or {}
99
+
100
+ def render(self):
101
+ return self._env.render()
102
+
103
+ def close(self):
104
+ self._env.close()
105
+
106
+
107
+ @dataclass
108
+ class Args:
109
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
110
+ seed: int = 1
111
+ torch_deterministic: bool = True
112
+ cuda: bool = True
113
+ track: bool = True
114
+ wandb_project_name: str = "cleanRL"
115
+ wandb_entity: str | None = None
116
+ capture_video: bool = False
117
+
118
+ # Algorithm
119
+ env_id: str = "RubiksCube2x2"
120
+ total_timesteps: int = 1000_000
121
+ learning_rate: float = 2.5e-4
122
+ num_envs: int = 8
123
+ num_steps: int = 128
124
+ anneal_lr: bool = True
125
+ gamma: float = 0.99
126
+ gae_lambda: float = 0.95
127
+ num_minibatches: int = 4
128
+ update_epochs: int = 4
129
+ norm_adv: bool = True
130
+ clip_coef: float = 0.2
131
+ clip_vloss: bool = True
132
+ ent_coef: float = 0.01
133
+ vf_coef: float = 0.5
134
+ max_grad_norm: float = 0.5
135
+ target_kl: float | None = None
136
+
137
+ # Rubik specific
138
+ scramble_depth: int = 3
139
+ max_steps_env: int = 6
140
+
141
+ # runtime filled
142
+ batch_size: int = 0
143
+ minibatch_size: int = 0
144
+ num_iterations: int = 0
145
+ eval_splits: int = 20
146
+ eval_episodes: int = 10000
147
+
148
+
149
+ def make_env(idx, run_name, seed, scramble_depth, max_steps_env, capture_video=False):
150
+ def thunk():
151
+ config = RubiksCube2x2Config(scramble_depth=scramble_depth, max_steps=max_steps_env, render_mode='text')
152
+ env = RubiksCube2x2Env(config)
153
+ env = RubiksCubeWrapper(env)
154
+ env = gym.wrappers.TimeLimit(env, max_episode_steps=max_steps_env)
155
+ env = gym.wrappers.RecordEpisodeStatistics(env)
156
+ if capture_video and idx == 0:
157
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
158
+ return env
159
+ return thunk
160
+
161
+
162
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
163
+ torch.nn.init.orthogonal_(layer.weight, std)
164
+ torch.nn.init.constant_(layer.bias, bias_const)
165
+ return layer
166
+
167
+
168
+ class Agent(nn.Module):
169
+ def __init__(self, envs):
170
+ super().__init__()
171
+ obs_shape = int(np.array(envs.single_observation_space.shape).prod())
172
+ hidden = 128
173
+ self.critic = nn.Sequential(
174
+ layer_init(nn.Linear(obs_shape, hidden)),
175
+ nn.Tanh(),
176
+ layer_init(nn.Linear(hidden, hidden)),
177
+ nn.Tanh(),
178
+ layer_init(nn.Linear(hidden, 1), std=1.0),
179
+ )
180
+ self.actor = nn.Sequential(
181
+ layer_init(nn.Linear(obs_shape, hidden)),
182
+ nn.Tanh(),
183
+ layer_init(nn.Linear(hidden, hidden)),
184
+ nn.Tanh(),
185
+ layer_init(nn.Linear(hidden, envs.single_action_space.n), std=0.01),
186
+ )
187
+
188
+ def get_value(self, x):
189
+ return self.critic(x)
190
+
191
+ def get_action_and_value(self, x, action=None):
192
+ logits = self.actor(x)
193
+ probs = Categorical(logits=logits)
194
+ if action is None:
195
+ action = probs.sample()
196
+ return action, probs.log_prob(action), probs.entropy(), self.critic(x)
197
+
198
+
199
+ if __name__ == "__main__":
200
+ args = tyro.cli(Args)
201
+ args.batch_size = int(args.num_envs * args.num_steps)
202
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
203
+ args.num_iterations = args.total_timesteps // args.batch_size
204
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
205
+
206
+ if args.track:
207
+ import wandb
208
+ wandb.init(
209
+ project=args.wandb_project_name,
210
+ entity=args.wandb_entity,
211
+ config=vars(args),
212
+ name=run_name,
213
+ monitor_gym=True,
214
+ save_code=True,
215
+ )
216
+ try:
217
+ wandb.define_metric("global_step")
218
+ for prefix in ["train/*", "rollout/*", "eval/*", "losses/*", "charts/*", "perf/*"]:
219
+ wandb.define_metric(prefix, step_metric="global_step")
220
+ except Exception:
221
+ pass
222
+
223
+ # seeding
224
+ random.seed(args.seed)
225
+ np.random.seed(args.seed)
226
+ torch.manual_seed(args.seed)
227
+ torch.backends.cudnn.deterministic = args.torch_deterministic
228
+
229
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
230
+
231
+ # envs
232
+ envs = gym.vector.SyncVectorEnv([
233
+ make_env(i, run_name, args.seed, args.scramble_depth, args.max_steps_env, args.capture_video)
234
+ for i in range(args.num_envs)
235
+ ])
236
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete)
237
+
238
+ agent = Agent(envs).to(device)
239
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
240
+
241
+ # storage
242
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
243
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
244
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
245
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
246
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
247
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
248
+
249
+ # start
250
+ global_step = 0
251
+ start_time = time.time()
252
+ next_obs, _ = envs.reset(seed=args.seed)
253
+ next_obs = torch.Tensor(next_obs).to(device)
254
+ next_done = torch.zeros(args.num_envs).to(device)
255
+
256
+ # eval helper similar to FrozenLake: collect greedy eval trajectories and write metrics.json
257
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes, step_tag):
258
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
259
+ out_dir.mkdir(parents=True, exist_ok=True)
260
+ out_path = out_dir / "trajectories.jsonl"
261
+ env = make_env_fn()
262
+ collected = 0
263
+ summary_returns = []
264
+ summary_success = []
265
+ with out_path.open("w") as f:
266
+ while collected < n_episodes:
267
+ state, _ = env.reset(seed=args.seed + 100000 + collected)
268
+ traj_states = [state.tolist()]
269
+ traj_actions = []
270
+ traj_rewards = []
271
+ traj_dones = []
272
+ traj_success = []
273
+ done = False
274
+ step_count = 0
275
+ max_eval_steps = getattr(env, '_max_episode_steps', None) or int(args.max_steps_env)
276
+ while not done:
277
+ with torch.no_grad():
278
+ logits = agent_model.actor(torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0))
279
+ action = int(torch.argmax(logits, dim=1).item())
280
+ next_state, reward, terminated, truncated, info = env.step(action)
281
+ traj_actions.append(int(action))
282
+ traj_rewards.append(float(reward))
283
+ step_count += 1
284
+ d = bool(terminated) or bool(truncated) or (step_count >= max_eval_steps)
285
+ traj_dones.append(d)
286
+ traj_success.append(bool((info or {}).get('success', False)))
287
+ state = next_state
288
+ traj_states.append(state.tolist())
289
+ done = d
290
+ ep_ret = float(sum(traj_rewards))
291
+ ep_succ = bool(any(traj_success))
292
+ record = {
293
+ "states": traj_states,
294
+ "actions": traj_actions,
295
+ "rewards": traj_rewards,
296
+ "dones": traj_dones,
297
+ "success": traj_success,
298
+ "episode_return": ep_ret,
299
+ "episode_success": ep_succ,
300
+ }
301
+ f.write(json.dumps(record) + "\n")
302
+ collected += 1
303
+ summary_returns.append(ep_ret)
304
+ summary_success.append(1.0 if ep_succ else 0.0)
305
+ env.close()
306
+ try:
307
+ metrics = {
308
+ "global_step": int(step_tag),
309
+ "episodes": int(n_episodes),
310
+ "success_rate": float(np.mean(summary_success)) if len(summary_success) else 0.0,
311
+ "avg_return": float(np.mean(summary_returns)) if len(summary_returns) else 0.0,
312
+ "std_return": float(np.std(summary_returns)) if len(summary_returns) else 0.0,
313
+ }
314
+ with (out_dir / "metrics.json").open("w") as mf:
315
+ json.dump(metrics, mf)
316
+ except Exception as e:
317
+ print(f"Warning: failed to write eval metrics: {e}")
318
+
319
+ # training loop
320
+ eval_every_iters = max(1, args.num_iterations // args.eval_splits)
321
+ for iteration in range(1, args.num_iterations + 1):
322
+ # Anneal LR
323
+ if args.anneal_lr:
324
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
325
+ lrnow = frac * args.learning_rate
326
+ optimizer.param_groups[0]["lr"] = lrnow
327
+
328
+ # accumulate per-iteration episode successes
329
+ iter_successes = []
330
+ for step in range(0, args.num_steps):
331
+ global_step += args.num_envs
332
+ obs[step] = next_obs
333
+ dones[step] = next_done
334
+
335
+ with torch.no_grad():
336
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
337
+ values[step] = value.flatten()
338
+ actions[step] = action
339
+ logprobs[step] = logprob
340
+
341
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
342
+ next_done = np.logical_or(terminations, truncations)
343
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
344
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
345
+
346
+ # Episode stats logging similar to FrozenLake
347
+ try:
348
+ mask = None
349
+ if isinstance(infos, dict):
350
+ if "_episode" in infos:
351
+ mask = np.asarray(infos["_episode"]).astype(bool)
352
+ elif "episode" in infos and isinstance(infos["episode"], dict) and "_l" in infos["episode"]:
353
+ mask = np.asarray(infos["episode"]["_l"]).astype(bool)
354
+ if mask is not None and np.any(mask):
355
+ r_arr = np.asarray(infos.get("episode", {}).get("r", np.zeros_like(mask, dtype=float)))
356
+ l_arr = np.asarray(infos.get("episode", {}).get("l", np.zeros_like(mask, dtype=int)))
357
+ # prefer success from info; fallback to ep return > 0
358
+ if "success" in infos:
359
+ succ_arr = np.asarray(infos.get("success", np.zeros_like(mask, dtype=bool))).astype(float)
360
+ else:
361
+ try:
362
+ succ_arr = (np.asarray(r_arr) > 0).astype(float)
363
+ except Exception:
364
+ succ_arr = np.zeros_like(mask, dtype=float)
365
+ # collect iteration successes for training success rate
366
+ try:
367
+ for s in np.asarray(succ_arr)[mask]:
368
+ iter_successes.append(float(s))
369
+ except Exception:
370
+ pass
371
+ if args.track:
372
+ try:
373
+ import wandb
374
+ log_dict = {
375
+ "global_step": int(global_step),
376
+ "rollout/ep_rew_mean": float(np.mean(r_arr[mask])) if np.any(mask) else None,
377
+ "rollout/ep_len_mean": float(np.mean(l_arr[mask])) if np.any(mask) else None,
378
+ "rollout/success_rate": float(np.mean(succ_arr[mask])) if np.any(mask) else None,
379
+ }
380
+ wandb.log(log_dict, step=global_step)
381
+ except Exception:
382
+ pass
383
+ except Exception:
384
+ pass
385
+
386
+ # GAE
387
+ with torch.no_grad():
388
+ next_value = agent.get_value(next_obs).reshape(1, -1)
389
+ advantages = torch.zeros_like(rewards).to(device)
390
+ lastgaelam = 0
391
+ for t in reversed(range(args.num_steps)):
392
+ if t == args.num_steps - 1:
393
+ nextnonterminal = 1.0 - next_done
394
+ nextvalues = next_value
395
+ else:
396
+ nextnonterminal = 1.0 - dones[t + 1]
397
+ nextvalues = values[t + 1]
398
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
399
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
400
+ returns = advantages + values
401
+
402
+ # flatten batch
403
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
404
+ b_logprobs = logprobs.reshape(-1)
405
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
406
+ b_advantages = advantages.reshape(-1)
407
+ b_returns = returns.reshape(-1)
408
+ b_values = values.reshape(-1)
409
+
410
+ # update
411
+ b_inds = np.arange(args.batch_size)
412
+ clipfracs = []
413
+ for epoch in range(args.update_epochs):
414
+ np.random.shuffle(b_inds)
415
+ for start in range(0, args.batch_size, args.minibatch_size):
416
+ end = start + args.minibatch_size
417
+ mb_inds = b_inds[start:end]
418
+
419
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
420
+ logratio = newlogprob - b_logprobs[mb_inds]
421
+ ratio = logratio.exp()
422
+
423
+ with torch.no_grad():
424
+ old_approx_kl = (-logratio).mean()
425
+ approx_kl = ((ratio - 1) - logratio).mean()
426
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
427
+
428
+ mb_advantages = b_advantages[mb_inds]
429
+ if args.norm_adv:
430
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
431
+
432
+ pg_loss1 = -mb_advantages * ratio
433
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
434
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
435
+
436
+ newvalue = newvalue.view(-1)
437
+ if args.clip_vloss:
438
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
439
+ v_clipped = b_values[mb_inds] + torch.clamp(
440
+ newvalue - b_values[mb_inds], -args.clip_coef, args.clip_coef,
441
+ )
442
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
443
+ v_loss = 0.5 * torch.max(v_loss_unclipped, v_loss_clipped).mean()
444
+ else:
445
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
446
+
447
+ entropy_loss = entropy.mean()
448
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
449
+
450
+ optimizer.zero_grad()
451
+ loss.backward()
452
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
453
+ optimizer.step()
454
+
455
+ if args.target_kl is not None and approx_kl > args.target_kl:
456
+ break
457
+
458
+ # metrics
459
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
460
+ var_y = np.var(y_true)
461
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
462
+
463
+ sps = int(global_step / (time.time() - start_time))
464
+ train_success_rate = float(np.mean(iter_successes)) if len(iter_successes) else 0.0
465
+ print(f"Iter {iteration:4d}/{args.num_iterations} | SPS: {sps:5d} | R: {rewards.mean().item():6.3f}")
466
+ if args.track:
467
+ try:
468
+ import wandb
469
+ wandb.log({
470
+ "global_step": int(global_step),
471
+ "charts/progress": float(100.0 * iteration / max(1, args.num_iterations)),
472
+ "train/value_loss": float(v_loss.item()),
473
+ "train/policy_loss": float(pg_loss.item()),
474
+ "losses/value_loss": float(v_loss.item()),
475
+ "losses/policy_loss": float(pg_loss.item()),
476
+ "train/entropy": float(entropy_loss.item()),
477
+ "train/old_approx_kl": float(old_approx_kl.item()),
478
+ "train/approx_kl": float(approx_kl.item()),
479
+ "train/clipfrac": float(np.mean(clipfracs)) if len(clipfracs) else 0.0,
480
+ "losses/explained_variance": float(explained_var),
481
+ "charts/avg_reward": float(rewards.mean().item()),
482
+ "charts/avg_value": float(values.mean().item()),
483
+ "perf/SPS": int(sps),
484
+ "charts/SPS": int(sps),
485
+ "train/success_rate": train_success_rate,
486
+ "charts/train_success_rate": train_success_rate,
487
+ "train/learning_rate": float(optimizer.param_groups[0]["lr"]),
488
+ }, step=global_step)
489
+ except Exception:
490
+ pass
491
+
492
+ # periodic evaluation collection
493
+ if iteration % eval_every_iters == 0:
494
+ try:
495
+ eval_thunk = make_env(0, run_name, args.seed + 9999, args.scramble_depth, args.max_steps_env, False)
496
+ collect_eval_trajectories(agent, eval_thunk, n_episodes=args.eval_episodes, step_tag=global_step)
497
+ if args.track:
498
+ try:
499
+ import json as _json
500
+ from pathlib import Path as _Path
501
+ mpath = _Path(f"runs/{run_name}/trajectories/step_{global_step}/metrics.json")
502
+ if mpath.exists():
503
+ with mpath.open("r") as mf:
504
+ metrics = _json.load(mf)
505
+ wandb.log({
506
+ "eval/success_rate": metrics.get("success_rate"),
507
+ "eval/avg_return": metrics.get("avg_return"),
508
+ "eval/std_return": metrics.get("std_return"),
509
+ "eval/episodes": metrics.get("episodes"),
510
+ }, step=global_step)
511
+ except Exception:
512
+ pass
513
+ print(f"Collected {args.eval_episodes} eval trajectories at global_step {global_step}")
514
+ except Exception as e:
515
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
516
+
517
+ envs.close()
cleanrl/cleanrl/wandb/latest-run/files/code/cleanrl/dqn_bandit.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DQN implementation for RAGEN Bandit Environment
2
+ # Adapted from dqn_atari.py for single-step bandit problem
3
+ import os
4
+ import random
5
+ import sys
6
+ import time
7
+ from dataclasses import dataclass
8
+
9
+ # Add parent directory to path to import the wrapper
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+
12
+ import gymnasium as gym
13
+ import numpy as np
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+ import torch.optim as optim
18
+ import tyro
19
+ from torch.utils.tensorboard import SummaryWriter
20
+
21
+ from ragen.env.bandit.env import BanditEnv
22
+ from ragen.env.bandit.config import BanditEnvConfig
23
+
24
+
25
+ # Define BanditWrapper locally to avoid dependency issues
26
+ class BanditWrapper(gym.Wrapper):
27
+ """
28
+ Wrapper for RAGEN Bandit environment to make it compatible with DQN.
29
+ Converts single-step Bandit to multi-step environment.
30
+
31
+ State representation: [arm0_count, arm0_avg_reward, arm1_count, arm1_avg_reward]
32
+ This allows the agent to learn which arm is better based on historical performance.
33
+ """
34
+ def __init__(self, env, steps_per_episode=10):
35
+ super().__init__(env)
36
+ # State: [arm0_pulls, arm0_avg_reward, arm1_pulls, arm1_avg_reward]
37
+ self.observation_space = gym.spaces.Box(low=0, high=1000, shape=(4,), dtype=np.float32)
38
+ self.action_space = gym.spaces.Discrete(2)
39
+ self.steps_per_episode = steps_per_episode
40
+ self.current_step = 0
41
+ self._arm_counts = [0, 0]
42
+ self._arm_rewards = [0.0, 0.0]
43
+
44
+ def reset(self, **kwargs):
45
+ # Filter out 'options' parameter that gymnasium passes but RAGEN doesn't support
46
+ seed = kwargs.get('seed', None)
47
+ mode = kwargs.get('mode', None)
48
+ self.env.reset(seed=seed, mode=mode)
49
+
50
+ # Reset step counter but keep arm statistics for learning
51
+ self.current_step = 0
52
+
53
+ # Return current state based on accumulated history
54
+ state = self._get_state()
55
+ return state, {}
56
+
57
+ def _get_state(self):
58
+ """Get current state representation."""
59
+ return np.array([
60
+ self._arm_counts[0],
61
+ self._arm_rewards[0] / max(1, self._arm_counts[0]),
62
+ self._arm_counts[1],
63
+ self._arm_rewards[1] / max(1, self._arm_counts[1]),
64
+ ], dtype=np.float32)
65
+
66
+ def step(self, action):
67
+ # Map action from 0,1 to 1,2 (RAGEN uses 1-indexed actions)
68
+ ragen_action = action + 1
69
+ obs, reward, done, info = self.env.step(ragen_action)
70
+
71
+ # Update statistics for the chosen arm
72
+ self._arm_counts[action] += 1
73
+ self._arm_rewards[action] += reward
74
+ self.current_step += 1
75
+
76
+ # Episode ends after N steps (not after single step)
77
+ terminated = (self.current_step >= self.steps_per_episode)
78
+ truncated = False
79
+
80
+ # Debug: print when episode ends
81
+ if terminated and self._arm_counts[0] + self._arm_counts[1] < 100:
82
+ print(f"DEBUG: Episode ended at step {self.current_step}, arm_counts: {self._arm_counts}")
83
+
84
+ # Reset the underlying Bandit env but keep our statistics
85
+ if not terminated:
86
+ self.env.reset()
87
+
88
+ state = self._get_state()
89
+ return state, reward, terminated, truncated, info
90
+
91
+
92
+ @dataclass
93
+ class Args:
94
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
95
+ """the name of this experiment"""
96
+ seed: int = 1
97
+ """seed of the experiment"""
98
+ torch_deterministic: bool = True
99
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
100
+ cuda: bool = True
101
+ """if toggled, cuda will be enabled by default"""
102
+ track: bool = False
103
+ """if toggled, this experiment will be tracked with Weights and Biases"""
104
+ wandb_project_name: str = "cleanRL"
105
+ """the wandb's project name"""
106
+ wandb_entity: str = None
107
+ """the entity (team) of wandb's project"""
108
+ capture_video: bool = False
109
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
110
+ save_model: bool = False
111
+ """whether to save model into the `runs/{run_name}` folder"""
112
+
113
+ # Algorithm specific arguments
114
+ env_id: str = "Bandit"
115
+ """the id of the environment"""
116
+ total_timesteps: int = 100000
117
+ """total timesteps of the experiments"""
118
+ learning_rate: float = 1e-3
119
+ """the learning rate of the optimizer"""
120
+ num_envs: int = 1
121
+ """the number of parallel game environments (DQN typically uses 1)"""
122
+ buffer_size: int = 10000
123
+ """the replay memory buffer size"""
124
+ gamma: float = 0.99
125
+ """the discount factor gamma (0.99 for multi-step bandit)"""
126
+ tau: float = 1.0
127
+ """the target network update rate"""
128
+ target_network_frequency: int = 500
129
+ """the timesteps it takes to update the target network"""
130
+ batch_size: int = 32
131
+ """the batch size of sample from the reply memory"""
132
+ start_e: float = 1.0
133
+ """the starting epsilon for exploration"""
134
+ end_e: float = 0.05
135
+ """the ending epsilon for exploration"""
136
+ exploration_fraction: float = 0.5
137
+ """the fraction of `total-timesteps` it takes from start-e to go end-e"""
138
+ learning_starts: int = 1000
139
+ """timestep to start learning"""
140
+ train_frequency: int = 1
141
+ """the frequency of training"""
142
+ steps_per_episode: int = 10
143
+ """number of steps per episode for multi-step bandit"""
144
+
145
+
146
+ def make_env(env_id, idx, capture_video, run_name, seed, steps_per_episode):
147
+ def thunk():
148
+ config = BanditEnvConfig()
149
+ env = BanditEnv(config)
150
+ env = BanditWrapper(env, steps_per_episode=steps_per_episode)
151
+ env = gym.wrappers.RecordEpisodeStatistics(env)
152
+ if capture_video and idx == 0:
153
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
154
+ return env
155
+ return thunk
156
+
157
+
158
+ # ALGO LOGIC: initialize agent here:
159
+ class QNetwork(nn.Module):
160
+ """
161
+ Q-Network for Bandit environment.
162
+ Input: [arm0_pulls, arm0_avg_reward, arm1_pulls, arm1_avg_reward]
163
+ Output: Q-values for each arm
164
+ """
165
+ def __init__(self, env):
166
+ super().__init__()
167
+ obs_shape = np.array(env.single_observation_space.shape).prod()
168
+ self.network = nn.Sequential(
169
+ nn.Linear(obs_shape, 128),
170
+ nn.ReLU(),
171
+ nn.Linear(128, 128),
172
+ nn.ReLU(),
173
+ nn.Linear(128, env.single_action_space.n),
174
+ )
175
+
176
+ def forward(self, x):
177
+ return self.network(x)
178
+
179
+
180
+ def linear_schedule(start_e: float, end_e: float, duration: int, t: int):
181
+ slope = (end_e - start_e) / duration
182
+ return max(slope * t + start_e, end_e)
183
+
184
+
185
+ if __name__ == "__main__":
186
+ args = tyro.cli(Args)
187
+ assert args.num_envs == 1, "vectorized envs are not supported at the moment"
188
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
189
+
190
+ if args.track:
191
+ import wandb
192
+
193
+ wandb.init(
194
+ project=args.wandb_project_name,
195
+ entity=args.wandb_entity,
196
+ sync_tensorboard=True,
197
+ config=vars(args),
198
+ name=run_name,
199
+ monitor_gym=True,
200
+ save_code=True,
201
+ )
202
+ writer = SummaryWriter(f"runs/{run_name}")
203
+ writer.add_text(
204
+ "hyperparameters",
205
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
206
+ )
207
+
208
+ # TRY NOT TO MODIFY: seeding
209
+ random.seed(args.seed)
210
+ np.random.seed(args.seed)
211
+ torch.manual_seed(args.seed)
212
+ torch.backends.cudnn.deterministic = args.torch_deterministic
213
+
214
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
215
+
216
+ # env setup
217
+ envs = gym.vector.SyncVectorEnv(
218
+ [make_env(args.env_id, i, args.capture_video, run_name, args.seed + i, args.steps_per_episode)
219
+ for i in range(args.num_envs)]
220
+ )
221
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
222
+
223
+ q_network = QNetwork(envs).to(device)
224
+ optimizer = optim.Adam(q_network.parameters(), lr=args.learning_rate)
225
+ target_network = QNetwork(envs).to(device)
226
+ target_network.load_state_dict(q_network.state_dict())
227
+
228
+ # Use simple replay buffer (no special memory optimization needed for bandit)
229
+ from cleanrl_utils.buffers import ReplayBuffer
230
+ rb = ReplayBuffer(
231
+ args.buffer_size,
232
+ envs.single_observation_space,
233
+ envs.single_action_space,
234
+ device,
235
+ optimize_memory_usage=False,
236
+ handle_timeout_termination=False,
237
+ )
238
+
239
+ start_time = time.time()
240
+
241
+ # Track episode returns
242
+ episode_returns = []
243
+ recent_episode_returns = []
244
+
245
+ # TRY NOT TO MODIFY: start the game
246
+ obs, _ = envs.reset(seed=args.seed)
247
+ for global_step in range(args.total_timesteps):
248
+ # ALGO LOGIC: put action logic here
249
+ epsilon = linear_schedule(args.start_e, args.end_e, args.exploration_fraction * args.total_timesteps, global_step)
250
+ if random.random() < epsilon:
251
+ actions = np.array([envs.single_action_space.sample() for _ in range(envs.num_envs)])
252
+ else:
253
+ q_values = q_network(torch.Tensor(obs).to(device))
254
+ actions = torch.argmax(q_values, dim=1).cpu().numpy()
255
+
256
+ # TRY NOT TO MODIFY: execute the game and log data.
257
+ next_obs, rewards, terminations, truncations, infos = envs.step(actions)
258
+
259
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
260
+ if "final_info" in infos:
261
+ for info in infos["final_info"]:
262
+ if info and "episode" in info:
263
+ episode_return = info['episode']['r']
264
+ episode_length = info['episode']['l']
265
+ episode_returns.append(episode_return)
266
+ recent_episode_returns.append(episode_return)
267
+ if len(recent_episode_returns) > 10:
268
+ recent_episode_returns.pop(0)
269
+ writer.add_scalar("charts/episodic_return", episode_return, global_step)
270
+ writer.add_scalar("charts/episodic_length", episode_length, global_step)
271
+
272
+ # Debug: print episode completion
273
+ if global_step % 1000 == 0:
274
+ print(f" → Episode completed! Return: {episode_return:.3f}, Length: {episode_length}")
275
+
276
+ # TRY NOT TO MODIFY: save data to reply buffer; handle `final_observation`
277
+ real_next_obs = next_obs.copy()
278
+ for idx, trunc in enumerate(truncations):
279
+ if trunc:
280
+ real_next_obs[idx] = infos["final_observation"][idx]
281
+ rb.add(obs, real_next_obs, actions, rewards, terminations, infos)
282
+
283
+ # TRY NOT TO MODIFY: CRUCIAL step easy to overlook
284
+ obs = next_obs
285
+
286
+ # ALGO LOGIC: training.
287
+ if global_step > args.learning_starts:
288
+ if global_step % args.train_frequency == 0:
289
+ data = rb.sample(args.batch_size)
290
+ with torch.no_grad():
291
+ target_max, _ = target_network(data.next_observations).max(dim=1)
292
+ td_target = data.rewards.flatten() + args.gamma * target_max * (1 - data.dones.flatten())
293
+ old_val = q_network(data.observations).gather(1, data.actions).squeeze()
294
+ loss = F.mse_loss(td_target, old_val)
295
+
296
+ if global_step % 100 == 0:
297
+ writer.add_scalar("losses/td_loss", loss, global_step)
298
+ writer.add_scalar("losses/q_values", old_val.mean().item(), global_step)
299
+ writer.add_scalar("charts/epsilon", epsilon, global_step)
300
+
301
+ # Console output with key metrics
302
+ sps = int(global_step / (time.time() - start_time))
303
+ progress = 100 * global_step / args.total_timesteps
304
+ avg_episode_return = np.mean(recent_episode_returns) if recent_episode_returns else 0.0
305
+
306
+ print(f"[{progress:5.1f}%] Step {global_step:6d}/{args.total_timesteps} | "
307
+ f"SPS: {sps:5d} | "
308
+ f"EpRet: {avg_episode_return:7.3f} | "
309
+ f"Loss: {loss.item():.4f} | "
310
+ f"Q-val: {old_val.mean().item():.4f} | "
311
+ f"Eps: {epsilon:.3f}")
312
+
313
+ writer.add_scalar("charts/SPS", sps, global_step)
314
+ if recent_episode_returns:
315
+ writer.add_scalar("charts/avg_episodic_return", avg_episode_return, global_step)
316
+
317
+ # optimize the model
318
+ optimizer.zero_grad()
319
+ loss.backward()
320
+ optimizer.step()
321
+
322
+ # update target network
323
+ if global_step % args.target_network_frequency == 0:
324
+ for target_network_param, q_network_param in zip(target_network.parameters(), q_network.parameters()):
325
+ target_network_param.data.copy_(
326
+ args.tau * q_network_param.data + (1.0 - args.tau) * target_network_param.data
327
+ )
328
+
329
+ if args.save_model:
330
+ model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
331
+ torch.save(q_network.state_dict(), model_path)
332
+ print(f"model saved to {model_path}")
333
+
334
+ envs.close()
335
+ writer.close()
336
+
337
+ print("\n" + "="*60)
338
+ print("Training Complete!")
339
+ print("="*60)
340
+ if episode_returns:
341
+ print(f"Final Average Episode Return (last 10): {np.mean(recent_episode_returns):.3f}")
342
+ print(f"Overall Average Episode Return: {np.mean(episode_returns):.3f}")
343
+ print(f"Best Episode Return: {max(episode_returns):.3f}")
344
+ print("="*60)
cleanrl/cleanrl/wandb/latest-run/files/config.yaml ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _wandb:
2
+ value:
3
+ cli_version: 0.22.3
4
+ code_path: code/cleanrl/dqn_bandit.py
5
+ e:
6
+ jbqdicudyaaspbdzq2z1959r4qyohhsf:
7
+ args:
8
+ - --track
9
+ - --wandb-project-name
10
+ - ragen-bandit
11
+ codePath: cleanrl/dqn_bandit.py
12
+ codePathLocal: dqn_bandit.py
13
+ cpu_count: 64
14
+ cpu_count_logical: 128
15
+ cudaVersion: "12.4"
16
+ disk:
17
+ /:
18
+ total: "5153960755200"
19
+ used: "31724965888"
20
+ email: haoyu-wa22@mails.tsinghua.edu.cn
21
+ executable: /root/local/miniconda3/envs/ragen/bin/python
22
+ git:
23
+ commit: 004f8a086a892a2a180f4dd332b90d83a968aa7a
24
+ remote: https://github.com/vwxyzjn/cleanrl.git
25
+ gpu: NVIDIA H100 80GB HBM3
26
+ gpu_count: 8
27
+ gpu_nvidia:
28
+ - architecture: Hopper
29
+ cudaCores: 16896
30
+ memoryTotal: "85520809984"
31
+ name: NVIDIA H100 80GB HBM3
32
+ uuid: GPU-35e2d43d-4067-82ce-90d4-def9e389bf28
33
+ - architecture: Hopper
34
+ cudaCores: 16896
35
+ memoryTotal: "85520809984"
36
+ name: NVIDIA H100 80GB HBM3
37
+ uuid: GPU-af4135e3-88f2-e9ac-518d-502c75a85429
38
+ - architecture: Hopper
39
+ cudaCores: 16896
40
+ memoryTotal: "85520809984"
41
+ name: NVIDIA H100 80GB HBM3
42
+ uuid: GPU-d7fdeeba-fe9b-ec03-d9f7-6724fe4266b5
43
+ - architecture: Hopper
44
+ cudaCores: 16896
45
+ memoryTotal: "85520809984"
46
+ name: NVIDIA H100 80GB HBM3
47
+ uuid: GPU-ccc4f668-3882-5a8e-2c07-c5cd08f6f666
48
+ - architecture: Hopper
49
+ cudaCores: 16896
50
+ memoryTotal: "85520809984"
51
+ name: NVIDIA H100 80GB HBM3
52
+ uuid: GPU-7b73c0cf-d3d5-e10c-7176-a43be1e41001
53
+ - architecture: Hopper
54
+ cudaCores: 16896
55
+ memoryTotal: "85520809984"
56
+ name: NVIDIA H100 80GB HBM3
57
+ uuid: GPU-81b58d94-5d1f-8ec2-f9d2-fd56172ed177
58
+ - architecture: Hopper
59
+ cudaCores: 16896
60
+ memoryTotal: "85520809984"
61
+ name: NVIDIA H100 80GB HBM3
62
+ uuid: GPU-03e8bc66-3b44-6794-49fd-5392fbdda6d1
63
+ - architecture: Hopper
64
+ cudaCores: 16896
65
+ memoryTotal: "85520809984"
66
+ name: NVIDIA H100 80GB HBM3
67
+ uuid: GPU-b7cf0ec6-7c29-1179-dceb-09565da51890
68
+ host: pt-4d654cf4576f4d23ad3d3919f12932fe-worker-0
69
+ memory:
70
+ total: "2163642122240"
71
+ os: Linux-5.14.0-284.25.1.el9_2.x86_64-x86_64-with-glibc2.35
72
+ program: /mnt/general/wanghy/RAGEN/cleanrl/cleanrl/dqn_bandit.py
73
+ python: CPython 3.12.12
74
+ root: /mnt/general/wanghy/RAGEN/cleanrl/cleanrl
75
+ startedAt: "2025-11-07T04:56:47.687990Z"
76
+ writerId: jbqdicudyaaspbdzq2z1959r4qyohhsf
77
+ m: []
78
+ python_version: 3.12.12
79
+ t:
80
+ "1":
81
+ - 1
82
+ - 49
83
+ - 51
84
+ - 105
85
+ "2":
86
+ - 1
87
+ - 49
88
+ - 51
89
+ - 105
90
+ "3":
91
+ - 13
92
+ - 16
93
+ - 35
94
+ "4": 3.12.12
95
+ "5": 0.22.3
96
+ "12": 0.22.3
97
+ "13": linux-x86_64
98
+ batch_size:
99
+ value: 32
100
+ buffer_size:
101
+ value: 10000
102
+ capture_video:
103
+ value: false
104
+ cuda:
105
+ value: true
106
+ end_e:
107
+ value: 0.05
108
+ env_id:
109
+ value: Bandit
110
+ exp_name:
111
+ value: dqn_bandit
112
+ exploration_fraction:
113
+ value: 0.5
114
+ gamma:
115
+ value: 0.99
116
+ learning_rate:
117
+ value: 0.001
118
+ learning_starts:
119
+ value: 1000
120
+ num_envs:
121
+ value: 1
122
+ save_model:
123
+ value: false
124
+ seed:
125
+ value: 1
126
+ start_e:
127
+ value: 1
128
+ steps_per_episode:
129
+ value: 10
130
+ target_network_frequency:
131
+ value: 500
132
+ tau:
133
+ value: 1
134
+ torch_deterministic:
135
+ value: true
136
+ total_timesteps:
137
+ value: 100000
138
+ track:
139
+ value: true
140
+ train_frequency:
141
+ value: 1
142
+ wandb_entity:
143
+ value: null
144
+ wandb_project_name:
145
+ value: ragen-bandit
cleanrl/cleanrl/wandb/latest-run/files/output.log ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DEBUG: Episode ended at step 10, arm_counts: [6, 4]
2
+ DEBUG: Episode ended at step 10, arm_counts: [9, 11]
3
+ DEBUG: Episode ended at step 10, arm_counts: [12, 18]
4
+ DEBUG: Episode ended at step 10, arm_counts: [20, 20]
5
+ DEBUG: Episode ended at step 10, arm_counts: [25, 25]
6
+ DEBUG: Episode ended at step 10, arm_counts: [33, 27]
7
+ DEBUG: Episode ended at step 10, arm_counts: [37, 33]
8
+ DEBUG: Episode ended at step 10, arm_counts: [41, 39]
9
+ DEBUG: Episode ended at step 10, arm_counts: [45, 45]
10
+ [ 1.1%] Step 1100/100000 | SPS: 2447 | EpRet: 0.000 | Loss: 0.5871 | Q-val: -1.5165 | Eps: 0.979
11
+ [ 1.2%] Step 1200/100000 | SPS: 2143 | EpRet: 0.000 | Loss: 2.2378 | Q-val: -1.1003 | Eps: 0.977
12
+ [ 1.3%] Step 1300/100000 | SPS: 1942 | EpRet: 0.000 | Loss: 2.8699 | Q-val: -0.4089 | Eps: 0.975
13
+ [ 1.4%] Step 1400/100000 | SPS: 1794 | EpRet: 0.000 | Loss: 0.4940 | Q-val: -1.8337 | Eps: 0.973
14
+ [ 1.5%] Step 1500/100000 | SPS: 1652 | EpRet: 0.000 | Loss: 7.6582 | Q-val: -3.1953 | Eps: 0.972
15
+ [ 1.6%] Step 1600/100000 | SPS: 1266 | EpRet: 0.000 | Loss: 2.2227 | Q-val: -2.6707 | Eps: 0.970
16
+ [ 1.7%] Step 1700/100000 | SPS: 1113 | EpRet: 0.000 | Loss: 27.5951 | Q-val: -5.2100 | Eps: 0.968
17
+ [ 1.8%] Step 1800/100000 | SPS: 774 | EpRet: 0.000 | Loss: 2.7080 | Q-val: -2.7679 | Eps: 0.966
18
+ [ 1.9%] Step 1900/100000 | SPS: 685 | EpRet: 0.000 | Loss: 11.6545 | Q-val: -5.6619 | Eps: 0.964
19
+ [ 2.0%] Step 2000/100000 | SPS: 688 | EpRet: 0.000 | Loss: 2.5694 | Q-val: -4.9087 | Eps: 0.962
20
+ [ 2.1%] Step 2100/100000 | SPS: 696 | EpRet: 0.000 | Loss: 1.4418 | Q-val: -3.4358 | Eps: 0.960
21
+ [ 2.2%] Step 2200/100000 | SPS: 704 | EpRet: 0.000 | Loss: 3.4676 | Q-val: -3.2345 | Eps: 0.958
22
+ [ 2.3%] Step 2300/100000 | SPS: 711 | EpRet: 0.000 | Loss: 4.6980 | Q-val: -4.6280 | Eps: 0.956
23
+ [ 2.4%] Step 2400/100000 | SPS: 718 | EpRet: 0.000 | Loss: 4.4856 | Q-val: -3.7042 | Eps: 0.954
24
+ [ 2.5%] Step 2500/100000 | SPS: 724 | EpRet: 0.000 | Loss: 16.9031 | Q-val: -1.1285 | Eps: 0.953
25
+ [ 2.6%] Step 2600/100000 | SPS: 730 | EpRet: 0.000 | Loss: 0.8887 | Q-val: 0.1586 | Eps: 0.951
26
+ [ 2.7%] Step 2700/100000 | SPS: 736 | EpRet: 0.000 | Loss: 0.4255 | Q-val: -0.1371 | Eps: 0.949
27
+ [ 2.8%] Step 2800/100000 | SPS: 741 | EpRet: 0.000 | Loss: 0.1293 | Q-val: -0.6650 | Eps: 0.947
28
+ [ 2.9%] Step 2900/100000 | SPS: 745 | EpRet: 0.000 | Loss: 1.3904 | Q-val: -1.6370 | Eps: 0.945
29
+ [ 3.0%] Step 3000/100000 | SPS: 749 | EpRet: 0.000 | Loss: 0.3428 | Q-val: -0.7361 | Eps: 0.943
30
+ [ 3.1%] Step 3100/100000 | SPS: 753 | EpRet: 0.000 | Loss: 0.2346 | Q-val: 0.5201 | Eps: 0.941
31
+ [ 3.2%] Step 3200/100000 | SPS: 756 | EpRet: 0.000 | Loss: 0.7521 | Q-val: -0.1650 | Eps: 0.939
32
+ [ 3.3%] Step 3300/100000 | SPS: 729 | EpRet: 0.000 | Loss: 0.4594 | Q-val: 0.0121 | Eps: 0.937
33
+ [ 3.4%] Step 3400/100000 | SPS: 698 | EpRet: 0.000 | Loss: 0.5089 | Q-val: 0.7252 | Eps: 0.935
34
+ [ 3.5%] Step 3500/100000 | SPS: 667 | EpRet: 0.000 | Loss: 2.0388 | Q-val: 0.8035 | Eps: 0.933
35
+ [ 3.6%] Step 3600/100000 | SPS: 619 | EpRet: 0.000 | Loss: 1.6456 | Q-val: 2.8996 | Eps: 0.932
36
+ [ 3.7%] Step 3700/100000 | SPS: 564 | EpRet: 0.000 | Loss: 0.3920 | Q-val: 2.0191 | Eps: 0.930
37
+ [ 3.8%] Step 3800/100000 | SPS: 517 | EpRet: 0.000 | Loss: 1.0114 | Q-val: 1.1074 | Eps: 0.928
38
+ [ 3.9%] Step 3900/100000 | SPS: 477 | EpRet: 0.000 | Loss: 1.5410 | Q-val: 1.7671 | Eps: 0.926
39
+ [ 4.0%] Step 4000/100000 | SPS: 448 | EpRet: 0.000 | Loss: 0.4592 | Q-val: 1.6611 | Eps: 0.924
40
+ [ 4.1%] Step 4100/100000 | SPS: 419 | EpRet: 0.000 | Loss: 0.5028 | Q-val: 1.8597 | Eps: 0.922
41
+ [ 4.2%] Step 4200/100000 | SPS: 399 | EpRet: 0.000 | Loss: 1.5164 | Q-val: 1.6604 | Eps: 0.920
42
+ [ 4.3%] Step 4300/100000 | SPS: 376 | EpRet: 0.000 | Loss: 2.9306 | Q-val: 1.3875 | Eps: 0.918
43
+ [ 4.4%] Step 4400/100000 | SPS: 363 | EpRet: 0.000 | Loss: 0.6109 | Q-val: 2.2573 | Eps: 0.916
44
+ [ 4.5%] Step 4500/100000 | SPS: 345 | EpRet: 0.000 | Loss: 1.7421 | Q-val: 1.6360 | Eps: 0.914
45
+ Traceback (most recent call last):
46
+ File "/mnt/general/wanghy/RAGEN/cleanrl/cleanrl/dqn_bandit.py", line 253, in <module>
47
+ q_values = q_network(torch.Tensor(obs).to(device))
48
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
49
+ KeyboardInterrupt
cleanrl/cleanrl/wandb/latest-run/files/requirements.txt ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ setuptools==80.9.0
2
+ wheel==0.45.1
3
+ pip==25.2
4
+ zipp==3.23.0
5
+ verl==0.2.0.dev0
6
+ ragen==0.1
7
+ triton==3.2.0
8
+ nvidia-cusparselt-cu12==0.6.2
9
+ mpmath==1.3.0
10
+ typing_extensions==4.15.0
11
+ sympy==1.13.1
12
+ nvidia-nvtx-cu12==12.4.127
13
+ nvidia-nvjitlink-cu12==12.4.127
14
+ nvidia-nccl-cu12==2.21.5
15
+ nvidia-curand-cu12==10.3.5.147
16
+ nvidia-cufft-cu12==11.2.1.3
17
+ nvidia-cuda-runtime-cu12==12.4.127
18
+ nvidia-cuda-nvrtc-cu12==12.4.127
19
+ nvidia-cuda-cupti-cu12==12.4.127
20
+ nvidia-cublas-cu12==12.4.5.8
21
+ networkx==3.5
22
+ MarkupSafe==2.1.5
23
+ fsspec==2025.9.0
24
+ filelock==3.19.1
25
+ nvidia-cusparse-cu12==12.3.1.170
26
+ nvidia-cudnn-cu12==9.1.0.70
27
+ Jinja2==3.1.6
28
+ nvidia-cusolver-cu12==11.6.1.9
29
+ torch==2.6.0+cu124
30
+ einops==0.8.1
31
+ flash_attn==2.7.4.post1
32
+ pytz==2025.2
33
+ pyperclip==1.11.0
34
+ pylatexenc==2.10
35
+ pyjnius==1.7.0
36
+ py-cpuinfo==9.0.0
37
+ pure_eval==0.2.3
38
+ ptyprocess==0.7.0
39
+ gym-notices==0.1.0
40
+ flatbuffers==25.9.23
41
+ fastrlock==0.8.3
42
+ Farama-Notifications==0.0.4
43
+ cymem==2.0.11
44
+ antlr4-python3-runtime==4.9.3
45
+ xxhash==3.6.0
46
+ wrapt==2.0.0
47
+ Werkzeug==3.1.3
48
+ websockets==15.0.1
49
+ wcwidth==0.2.14
50
+ wasabi==1.1.3
51
+ uvloop==0.22.1
52
+ urllib3==2.5.0
53
+ tzdata==2025.2
54
+ typing-inspection==0.4.2
55
+ traitlets==5.14.3
56
+ tqdm==4.67.1
57
+ threadpoolctl==3.6.0
58
+ tabulate==0.9.0
59
+ spacy-loggers==1.0.5
60
+ spacy-legacy==3.0.12
61
+ soupsieve==2.8
62
+ sniffio==1.3.1
63
+ smmap==5.0.2
64
+ six==1.17.0
65
+ shellingham==1.5.4
66
+ sentencepiece==0.2.1
67
+ safetensors==0.6.2
68
+ rpds-py==0.28.0
69
+ rignore==0.7.6
70
+ regex==2025.11.3
71
+ RapidFuzz==3.14.3
72
+ pyzmq==27.1.0
73
+ PyYAML==6.0.3
74
+ pytokens==0.3.0
75
+ python-multipart==0.0.20
76
+ python-json-logger==4.0.0
77
+ python-dotenv==1.2.1
78
+ PySocks==1.7.1
79
+ pyparsing==3.2.5
80
+ PyJWT==2.10.1
81
+ Pygments==2.19.2
82
+ pygame==2.6.1
83
+ pydantic_core==2.41.5
84
+ pycparser==2.23
85
+ pycountry==24.6.1
86
+ pybind11==3.0.1
87
+ pyarrow==22.0.0
88
+ psutil==7.1.3
89
+ protobuf==6.33.0
90
+ propcache==0.4.1
91
+ prometheus_client==0.23.1
92
+ platformdirs==4.5.0
93
+ pillow==11.3.0
94
+ pexpect==4.9.0
95
+ pathvalidate==3.3.1
96
+ pathspec==0.12.1
97
+ pathable==0.4.4
98
+ partial-json-parser==0.2.1.1.post6
99
+ parso==0.8.5
100
+ packaging==25.0
101
+ orjson==3.11.4
102
+ numpy==1.26.4
103
+ ninja==1.13.0
104
+ nest-asyncio==1.6.0
105
+ mypy_extensions==1.1.0
106
+ murmurhash==1.0.13
107
+ multidict==6.7.0
108
+ msgspec==0.19.0
109
+ msgpack==1.1.2
110
+ more-itertools==10.8.0
111
+ mdurl==0.1.2
112
+ marisa-trie==1.3.1
113
+ llvmlite==0.43.0
114
+ llguidance==0.7.30
115
+ lark==1.2.2
116
+ kiwisolver==1.4.9
117
+ joblib==1.5.2
118
+ jiter==0.11.1
119
+ jeepney==0.9.0
120
+ jaraco.context==6.0.1
121
+ itsdangerous==2.2.0
122
+ interegular==0.3.3
123
+ idna==3.11
124
+ humanfriendly==10.0
125
+ httpx-sse==0.4.3
126
+ httptools==0.7.1
127
+ html2text==2025.4.15
128
+ hf-xet==1.2.0
129
+ h11==0.16.0
130
+ frozenlist==1.8.0
131
+ fonttools==4.60.1
132
+ executing==2.2.1
133
+ exceptiongroup==1.3.0
134
+ eval_type_backport==0.2.2
135
+ docutils==0.22.3
136
+ docstring_parser==0.17.0
137
+ dnspython==2.8.0
138
+ distro==1.9.0
139
+ diskcache==5.6.3
140
+ dill==0.4.0
141
+ decorator==5.2.1
142
+ debugpy==1.8.17
143
+ Cython==3.2.0
144
+ cycler==0.12.1
145
+ codetiming==1.4.0
146
+ cloudpickle==3.1.2
147
+ cloudpathlib==0.23.0
148
+ click==8.2.1
149
+ charset-normalizer==3.4.4
150
+ certifi==2025.10.5
151
+ catalogue==2.0.10
152
+ cachetools==6.2.1
153
+ blinker==1.9.0
154
+ blake3==1.0.8
155
+ beartype==0.22.5
156
+ attrs==25.4.0
157
+ asttokens==3.0.0
158
+ astor==0.8.1
159
+ annotated-types==0.7.0
160
+ annotated-doc==0.0.3
161
+ airportsdata==20250909
162
+ aiohappyeyeballs==2.6.1
163
+ yarl==1.22.0
164
+ uvicorn==0.38.0
165
+ typer-slim==0.20.0
166
+ thefuzz==0.22.1
167
+ stack-data==0.6.3
168
+ srsly==2.5.1
169
+ smart_open==7.4.4
170
+ sentry-sdk==2.43.0
171
+ scipy==1.16.3
172
+ requests==2.32.5
173
+ referencing==0.36.2
174
+ rank-bm25==0.2.2
175
+ python-dateutil==2.9.0.post0
176
+ pydantic==2.12.4
177
+ py-key-value-shared==0.2.8
178
+ prompt_toolkit==3.0.52
179
+ preshed==3.0.10
180
+ opencv-python-headless==4.11.0.86
181
+ omegaconf==2.3.0
182
+ numba==0.60.0
183
+ nltk==3.9.2
184
+ multiprocess==0.70.18
185
+ matplotlib-inline==0.2.1
186
+ markdown-it-py==4.0.0
187
+ language_data==1.3.0
188
+ jedi==0.19.2
189
+ jaraco.functools==4.3.0
190
+ jaraco.classes==3.4.0
191
+ ipython_pygments_lexers==1.1.1
192
+ importlib_metadata==8.7.0
193
+ ImageIO==2.37.2
194
+ httpcore==1.0.9
195
+ gymnasium==1.2.2
196
+ gym==0.26.2
197
+ gitdb==4.0.12
198
+ gguf==0.10.0
199
+ Flask==3.1.2
200
+ faiss-cpu==1.12.0
201
+ email-validator==2.3.0
202
+ depyf==0.18.0
203
+ cupy-cuda12x==13.6.0
204
+ contourpy==1.3.3
205
+ coloredlogs==15.0.1
206
+ cffi==2.0.0
207
+ blis==1.3.0
208
+ black==25.9.0
209
+ beautifulsoup4==4.14.2
210
+ anyio==4.11.0
211
+ aiosignal==1.4.0
212
+ watchfiles==1.1.1
213
+ tiktoken==0.12.0
214
+ starlette==0.49.3
215
+ sse-starlette==3.0.3
216
+ scikit-learn==1.7.2
217
+ rich==14.2.0
218
+ pydantic-settings==2.11.0
219
+ pydantic-extra-types==2.10.6
220
+ py-key-value-aio==0.2.8
221
+ pandas==2.3.3
222
+ openapi-pydantic==0.5.1
223
+ onnxruntime==1.23.2
224
+ matplotlib==3.10.7
225
+ lm-format-enforcer==0.10.12
226
+ langcodes==3.5.0
227
+ jsonschema-specifications==2025.9.1
228
+ jsonschema-path==0.3.4
229
+ ipython==9.7.0
230
+ hydra-core==1.3.2
231
+ huggingface-hub==0.36.0
232
+ httpx==0.28.1
233
+ gym-sokoban==0.0.6
234
+ GitPython==3.1.45
235
+ cryptography==46.0.3
236
+ confection==0.1.5
237
+ cleantext==1.1.4
238
+ aiohttp==3.13.2
239
+ xformers==0.0.29.post2
240
+ weasel==0.4.2
241
+ wandb==0.22.3
242
+ typer==0.19.2
243
+ torchvision==0.21.0
244
+ torchdata==0.11.0
245
+ torchaudio==2.6.0
246
+ tokenizers==0.22.1
247
+ thinc==8.3.7
248
+ tensordict==0.8.3
249
+ SecretStorage==3.4.0
250
+ rich-toolkit==0.15.1
251
+ rich-rst==1.3.2
252
+ prometheus-fastapi-instrumentator==7.1.0
253
+ openai==2.7.1
254
+ jsonschema==4.25.1
255
+ gdown==5.2.0
256
+ fastapi==0.121.0
257
+ Authlib==1.6.5
258
+ anthropic==0.72.0
259
+ accelerate==1.11.0
260
+ transformers==4.57.1
261
+ together==1.5.30
262
+ spacy==3.8.7
263
+ ray==2.51.1
264
+ outlines_core==0.1.26
265
+ mistral_common==1.8.5
266
+ mcp==1.20.0
267
+ keyring==25.6.0
268
+ fastapi-cloud-cli==0.3.1
269
+ fastapi-cli==0.0.14
270
+ datasets==4.4.1
271
+ cyclopts==4.2.1
272
+ xgrammar==0.1.16
273
+ peft==0.17.1
274
+ outlines==0.1.11
275
+ compressed-tensors==0.9.2
276
+ fastmcp==2.13.0.2
277
+ vllm==0.8.2
278
+ pyserini==1.3.0
279
+ typeguard==4.4.4
280
+ shtab==1.7.2
281
+ tyro==0.9.35
282
+ tensorboard-data-server==0.7.2
283
+ Markdown==3.10
284
+ grpcio==1.76.0
285
+ absl-py==2.3.1
286
+ tensorboard==2.20.0
287
+ ragen==0.1
288
+ verl==0.2.0.dev0
289
+ autocommand==2.2.2
290
+ backports.tarfile==1.2.0
291
+ importlib_metadata==8.0.0
292
+ inflect==7.3.1
293
+ jaraco.collections==5.1.0
294
+ jaraco.context==5.3.0
295
+ jaraco.functools==4.0.1
296
+ jaraco.text==3.12.1
297
+ more-itertools==10.3.0
298
+ packaging==24.2
299
+ platformdirs==4.2.2
300
+ tomli==2.0.1
301
+ typeguard==4.3.0
302
+ typing_extensions==4.12.2
303
+ wheel==0.45.1
304
+ zipp==3.19.2
cleanrl/cleanrl/wandb/latest-run/files/wandb-metadata.json ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "os": "Linux-5.14.0-284.25.1.el9_2.x86_64-x86_64-with-glibc2.35",
3
+ "python": "CPython 3.12.12",
4
+ "startedAt": "2025-11-07T04:56:47.687990Z",
5
+ "args": [
6
+ "--track",
7
+ "--wandb-project-name",
8
+ "ragen-bandit"
9
+ ],
10
+ "program": "/mnt/general/wanghy/RAGEN/cleanrl/cleanrl/dqn_bandit.py",
11
+ "codePath": "cleanrl/dqn_bandit.py",
12
+ "codePathLocal": "dqn_bandit.py",
13
+ "git": {
14
+ "remote": "https://github.com/vwxyzjn/cleanrl.git",
15
+ "commit": "004f8a086a892a2a180f4dd332b90d83a968aa7a"
16
+ },
17
+ "email": "haoyu-wa22@mails.tsinghua.edu.cn",
18
+ "root": "/mnt/general/wanghy/RAGEN/cleanrl/cleanrl",
19
+ "host": "pt-4d654cf4576f4d23ad3d3919f12932fe-worker-0",
20
+ "executable": "/root/local/miniconda3/envs/ragen/bin/python",
21
+ "cpu_count": 64,
22
+ "cpu_count_logical": 128,
23
+ "gpu": "NVIDIA H100 80GB HBM3",
24
+ "gpu_count": 8,
25
+ "disk": {
26
+ "/": {
27
+ "total": "5153960755200",
28
+ "used": "31724965888"
29
+ }
30
+ },
31
+ "memory": {
32
+ "total": "2163642122240"
33
+ },
34
+ "gpu_nvidia": [
35
+ {
36
+ "name": "NVIDIA H100 80GB HBM3",
37
+ "memoryTotal": "85520809984",
38
+ "cudaCores": 16896,
39
+ "architecture": "Hopper",
40
+ "uuid": "GPU-35e2d43d-4067-82ce-90d4-def9e389bf28"
41
+ },
42
+ {
43
+ "name": "NVIDIA H100 80GB HBM3",
44
+ "memoryTotal": "85520809984",
45
+ "cudaCores": 16896,
46
+ "architecture": "Hopper",
47
+ "uuid": "GPU-af4135e3-88f2-e9ac-518d-502c75a85429"
48
+ },
49
+ {
50
+ "name": "NVIDIA H100 80GB HBM3",
51
+ "memoryTotal": "85520809984",
52
+ "cudaCores": 16896,
53
+ "architecture": "Hopper",
54
+ "uuid": "GPU-d7fdeeba-fe9b-ec03-d9f7-6724fe4266b5"
55
+ },
56
+ {
57
+ "name": "NVIDIA H100 80GB HBM3",
58
+ "memoryTotal": "85520809984",
59
+ "cudaCores": 16896,
60
+ "architecture": "Hopper",
61
+ "uuid": "GPU-ccc4f668-3882-5a8e-2c07-c5cd08f6f666"
62
+ },
63
+ {
64
+ "name": "NVIDIA H100 80GB HBM3",
65
+ "memoryTotal": "85520809984",
66
+ "cudaCores": 16896,
67
+ "architecture": "Hopper",
68
+ "uuid": "GPU-7b73c0cf-d3d5-e10c-7176-a43be1e41001"
69
+ },
70
+ {
71
+ "name": "NVIDIA H100 80GB HBM3",
72
+ "memoryTotal": "85520809984",
73
+ "cudaCores": 16896,
74
+ "architecture": "Hopper",
75
+ "uuid": "GPU-81b58d94-5d1f-8ec2-f9d2-fd56172ed177"
76
+ },
77
+ {
78
+ "name": "NVIDIA H100 80GB HBM3",
79
+ "memoryTotal": "85520809984",
80
+ "cudaCores": 16896,
81
+ "architecture": "Hopper",
82
+ "uuid": "GPU-03e8bc66-3b44-6794-49fd-5392fbdda6d1"
83
+ },
84
+ {
85
+ "name": "NVIDIA H100 80GB HBM3",
86
+ "memoryTotal": "85520809984",
87
+ "cudaCores": 16896,
88
+ "architecture": "Hopper",
89
+ "uuid": "GPU-b7cf0ec6-7c29-1179-dceb-09565da51890"
90
+ }
91
+ ],
92
+ "cudaVersion": "12.4",
93
+ "writerId": "jbqdicudyaaspbdzq2z1959r4qyohhsf"
94
+ }
cleanrl/cleanrl/wandb/latest-run/files/wandb-summary.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"losses/q_values":1.63602,"_runtime":14,"global_step":4500,"_step":139,"losses/td_loss":1.7421228,"_wandb":{"runtime":14},"charts/epsilon":0.9145,"_timestamp":1.7624914231757627e+09,"charts/SPS":345}
cleanrl/cleanrl/wandb/latest-run/logs/debug-internal.log ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"time":"2025-11-07T12:56:47.957309906+08:00","level":"INFO","msg":"stream: starting","core version":"0.22.3"}
2
+ {"time":"2025-11-07T12:56:48.33142385+08:00","level":"INFO","msg":"stream: created new stream","id":"g1edw7ov"}
3
+ {"time":"2025-11-07T12:56:48.331674194+08:00","level":"INFO","msg":"handler: started","stream_id":"g1edw7ov"}
4
+ {"time":"2025-11-07T12:56:48.335368381+08:00","level":"INFO","msg":"stream: started","id":"g1edw7ov"}
5
+ {"time":"2025-11-07T12:56:48.335386015+08:00","level":"INFO","msg":"writer: started","stream_id":"g1edw7ov"}
6
+ {"time":"2025-11-07T12:56:48.335389832+08:00","level":"INFO","msg":"sender: started","stream_id":"g1edw7ov"}
7
+ {"time":"2025-11-07T12:56:48.726770104+08:00","level":"ERROR","msg":"git repo not found","error":"repository does not exist"}
8
+ {"time":"2025-11-07T12:56:58.861202459+08:00","level":"WARN","msg":"tensorboard: no root directory","error":"timed out after 10s"}
9
+ {"time":"2025-11-07T12:56:58.862839009+08:00","level":"INFO","msg":"tensorboard: tracking new log directory","rootDir":{},"logDir":"LocalOrCloudPath(LocalPath=\"/mnt/general/wanghy/RAGEN/cleanrl/cleanrl/runs/Bandit__dqn_bandit__1__1762491400\")","namespace":""}
10
+ {"time":"2025-11-07T12:56:58.864923146+08:00","level":"INFO","msg":"tensorboard: saving file","fileLocation":"/mnt/general/wanghy/RAGEN/cleanrl/cleanrl/runs/Bandit__dqn_bandit__1__1762491400/events.out.tfevents.1762491408.pt-4d654cf4576f4d23ad3d3919f12932fe-worker-0.234009.0","runPath":"runs/Bandit__dqn_bandit__1__1762491400/events.out.tfevents.1762491408.pt-4d654cf4576f4d23ad3d3919f12932fe-worker-0.234009.0"}
11
+ {"time":"2025-11-07T12:56:58.868040818+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":122}
12
+ {"time":"2025-11-07T12:56:58.871369044+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":311}
13
+ {"time":"2025-11-07T12:57:03.576733669+08:00","level":"INFO","msg":"stream: closing","id":"g1edw7ov"}
14
+ {"time":"2025-11-07T12:57:03.579454439+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":506}
15
+ {"time":"2025-11-07T12:57:03.581505913+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":20}
cleanrl/cleanrl/wandb/latest-run/logs/debug.log ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2025-11-07 12:56:47,735 INFO MainThread:234009 [wandb_setup.py:_flush():81] Current SDK version is 0.22.3
2
+ 2025-11-07 12:56:47,736 INFO MainThread:234009 [wandb_setup.py:_flush():81] Configure stats pid to 234009
3
+ 2025-11-07 12:56:47,736 INFO MainThread:234009 [wandb_setup.py:_flush():81] Loading settings from /root/.config/wandb/settings
4
+ 2025-11-07 12:56:47,736 INFO MainThread:234009 [wandb_setup.py:_flush():81] Loading settings from /mnt/general/wanghy/RAGEN/cleanrl/cleanrl/wandb/settings
5
+ 2025-11-07 12:56:47,736 INFO MainThread:234009 [wandb_setup.py:_flush():81] Loading settings from environment variables
6
+ 2025-11-07 12:56:47,736 INFO MainThread:234009 [wandb_init.py:setup_run_log_directory():706] Logging user logs to /mnt/general/wanghy/RAGEN/cleanrl/cleanrl/wandb/run-20251107_125647-g1edw7ov/logs/debug.log
7
+ 2025-11-07 12:56:47,737 INFO MainThread:234009 [wandb_init.py:setup_run_log_directory():707] Logging internal logs to /mnt/general/wanghy/RAGEN/cleanrl/cleanrl/wandb/run-20251107_125647-g1edw7ov/logs/debug-internal.log
8
+ 2025-11-07 12:56:47,738 INFO MainThread:234009 [wandb_init.py:init():833] calling init triggers
9
+ 2025-11-07 12:56:47,738 INFO MainThread:234009 [wandb_init.py:init():838] wandb.init called with sweep_config: {}
10
+ config: {'exp_name': 'dqn_bandit', 'seed': 1, 'torch_deterministic': True, 'cuda': True, 'track': True, 'wandb_project_name': 'ragen-bandit', 'wandb_entity': None, 'capture_video': False, 'save_model': False, 'env_id': 'Bandit', 'total_timesteps': 100000, 'learning_rate': 0.001, 'num_envs': 1, 'buffer_size': 10000, 'gamma': 0.99, 'tau': 1.0, 'target_network_frequency': 500, 'batch_size': 32, 'start_e': 1.0, 'end_e': 0.05, 'exploration_fraction': 0.5, 'learning_starts': 1000, 'train_frequency': 1, 'steps_per_episode': 10, '_wandb': {'code_path': 'code/cleanrl/dqn_bandit.py'}}
11
+ 2025-11-07 12:56:47,738 INFO MainThread:234009 [wandb_init.py:init():881] starting backend
12
+ 2025-11-07 12:56:47,944 INFO MainThread:234009 [wandb_init.py:init():884] sending inform_init request
13
+ 2025-11-07 12:56:47,954 INFO MainThread:234009 [wandb_init.py:init():892] backend started and connected
14
+ 2025-11-07 12:56:47,956 INFO MainThread:234009 [wandb_init.py:init():962] updated telemetry
15
+ 2025-11-07 12:56:47,990 INFO MainThread:234009 [wandb_init.py:init():986] communicating run to backend with 90.0 second timeout
16
+ 2025-11-07 12:56:48,714 INFO MainThread:234009 [wandb_init.py:init():1033] starting run threads in backend
17
+ 2025-11-07 12:56:48,856 INFO MainThread:234009 [wandb_run.py:_console_start():2506] atexit reg
18
+ 2025-11-07 12:56:48,857 INFO MainThread:234009 [wandb_run.py:_redirect():2354] redirect: wrap_raw
19
+ 2025-11-07 12:56:48,857 INFO MainThread:234009 [wandb_run.py:_redirect():2423] Wrapping output streams.
20
+ 2025-11-07 12:56:48,857 INFO MainThread:234009 [wandb_run.py:_redirect():2446] Redirects installed.
21
+ 2025-11-07 12:56:48,859 INFO MainThread:234009 [wandb_init.py:init():1073] run started, returning control to user process
22
+ 2025-11-07 12:56:48,860 INFO MainThread:234009 [wandb_run.py:_tensorboard_callback():1598] tensorboard callback: runs/Bandit__dqn_bandit__1__1762491400, True
23
+ 2025-11-07 12:57:03,576 INFO wandb-AsyncioManager-main:234009 [service_client.py:_forward_responses():80] Reached EOF.
24
+ 2025-11-07 12:57:03,577 INFO wandb-AsyncioManager-main:234009 [mailbox.py:close():137] Closing mailbox, abandoning 1 handles.
25
+ 2025-11-07 12:57:03,925 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
26
+ Traceback (most recent call last):
27
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
28
+ await fn()
29
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
30
+ await self._send_server_request(request)
31
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
32
+ await self._writer.drain()
33
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
34
+ await self._protocol._drain_helper()
35
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
36
+ raise ConnectionResetError('Connection lost')
37
+ ConnectionResetError: Connection lost
38
+ 2025-11-07 12:57:03,933 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
39
+ Traceback (most recent call last):
40
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
41
+ await fn()
42
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
43
+ await self._send_server_request(request)
44
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
45
+ await self._writer.drain()
46
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
47
+ await self._protocol._drain_helper()
48
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
49
+ raise ConnectionResetError('Connection lost')
50
+ ConnectionResetError: Connection lost
51
+ 2025-11-07 12:57:03,933 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
52
+ Traceback (most recent call last):
53
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
54
+ await fn()
55
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
56
+ await self._send_server_request(request)
57
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
58
+ await self._writer.drain()
59
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
60
+ await self._protocol._drain_helper()
61
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
62
+ raise ConnectionResetError('Connection lost')
63
+ ConnectionResetError: Connection lost
64
+ 2025-11-07 12:57:03,934 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
65
+ Traceback (most recent call last):
66
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
67
+ await fn()
68
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
69
+ await self._send_server_request(request)
70
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
71
+ await self._writer.drain()
72
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
73
+ await self._protocol._drain_helper()
74
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
75
+ raise ConnectionResetError('Connection lost')
76
+ ConnectionResetError: Connection lost
77
+ 2025-11-07 12:57:03,934 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
78
+ Traceback (most recent call last):
79
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
80
+ await fn()
81
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
82
+ await self._send_server_request(request)
83
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
84
+ await self._writer.drain()
85
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
86
+ await self._protocol._drain_helper()
87
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
88
+ raise ConnectionResetError('Connection lost')
89
+ ConnectionResetError: Connection lost
90
+ 2025-11-07 12:57:03,935 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
91
+ Traceback (most recent call last):
92
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
93
+ await fn()
94
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
95
+ await self._send_server_request(request)
96
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
97
+ await self._writer.drain()
98
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
99
+ await self._protocol._drain_helper()
100
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
101
+ raise ConnectionResetError('Connection lost')
102
+ ConnectionResetError: Connection lost
103
+ 2025-11-07 12:57:03,935 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
104
+ Traceback (most recent call last):
105
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
106
+ await fn()
107
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
108
+ await self._send_server_request(request)
109
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
110
+ await self._writer.drain()
111
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
112
+ await self._protocol._drain_helper()
113
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
114
+ raise ConnectionResetError('Connection lost')
115
+ ConnectionResetError: Connection lost
116
+ 2025-11-07 12:57:03,935 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
117
+ Traceback (most recent call last):
118
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
119
+ await fn()
120
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
121
+ await self._send_server_request(request)
122
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
123
+ await self._writer.drain()
124
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
125
+ await self._protocol._drain_helper()
126
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
127
+ raise ConnectionResetError('Connection lost')
128
+ ConnectionResetError: Connection lost
129
+ 2025-11-07 12:57:03,936 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
130
+ Traceback (most recent call last):
131
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
132
+ await fn()
133
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
134
+ await self._send_server_request(request)
135
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
136
+ await self._writer.drain()
137
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
138
+ await self._protocol._drain_helper()
139
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
140
+ raise ConnectionResetError('Connection lost')
141
+ ConnectionResetError: Connection lost
142
+ 2025-11-07 12:57:03,936 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
143
+ Traceback (most recent call last):
144
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
145
+ await fn()
146
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
147
+ await self._send_server_request(request)
148
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
149
+ await self._writer.drain()
150
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
151
+ await self._protocol._drain_helper()
152
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
153
+ raise ConnectionResetError('Connection lost')
154
+ ConnectionResetError: Connection lost
155
+ 2025-11-07 12:57:03,937 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
156
+ Traceback (most recent call last):
157
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
158
+ await fn()
159
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
160
+ await self._send_server_request(request)
161
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
162
+ await self._writer.drain()
163
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
164
+ await self._protocol._drain_helper()
165
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
166
+ raise ConnectionResetError('Connection lost')
167
+ ConnectionResetError: Connection lost
168
+ 2025-11-07 12:57:03,937 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
169
+ Traceback (most recent call last):
170
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
171
+ await fn()
172
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
173
+ await self._send_server_request(request)
174
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
175
+ await self._writer.drain()
176
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
177
+ await self._protocol._drain_helper()
178
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
179
+ raise ConnectionResetError('Connection lost')
180
+ ConnectionResetError: Connection lost
181
+ 2025-11-07 12:57:03,937 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
182
+ Traceback (most recent call last):
183
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
184
+ await fn()
185
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
186
+ await self._send_server_request(request)
187
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
188
+ await self._writer.drain()
189
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
190
+ await self._protocol._drain_helper()
191
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
192
+ raise ConnectionResetError('Connection lost')
193
+ ConnectionResetError: Connection lost
194
+ 2025-11-07 12:57:03,938 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
195
+ Traceback (most recent call last):
196
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
197
+ await fn()
198
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
199
+ await self._send_server_request(request)
200
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
201
+ await self._writer.drain()
202
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
203
+ await self._protocol._drain_helper()
204
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
205
+ raise ConnectionResetError('Connection lost')
206
+ ConnectionResetError: Connection lost
207
+ 2025-11-07 12:57:03,938 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
208
+ Traceback (most recent call last):
209
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
210
+ await fn()
211
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
212
+ await self._send_server_request(request)
213
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
214
+ await self._writer.drain()
215
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
216
+ await self._protocol._drain_helper()
217
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
218
+ raise ConnectionResetError('Connection lost')
219
+ ConnectionResetError: Connection lost
220
+ 2025-11-07 12:57:03,938 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
221
+ Traceback (most recent call last):
222
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
223
+ await fn()
224
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
225
+ await self._send_server_request(request)
226
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
227
+ await self._writer.drain()
228
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
229
+ await self._protocol._drain_helper()
230
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
231
+ raise ConnectionResetError('Connection lost')
232
+ ConnectionResetError: Connection lost
233
+ 2025-11-07 12:57:03,939 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
234
+ Traceback (most recent call last):
235
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
236
+ await fn()
237
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
238
+ await self._send_server_request(request)
239
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
240
+ await self._writer.drain()
241
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
242
+ await self._protocol._drain_helper()
243
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
244
+ raise ConnectionResetError('Connection lost')
245
+ ConnectionResetError: Connection lost
246
+ 2025-11-07 12:57:03,939 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
247
+ Traceback (most recent call last):
248
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
249
+ await fn()
250
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
251
+ await self._send_server_request(request)
252
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
253
+ await self._writer.drain()
254
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
255
+ await self._protocol._drain_helper()
256
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
257
+ raise ConnectionResetError('Connection lost')
258
+ ConnectionResetError: Connection lost
259
+ 2025-11-07 12:57:03,948 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
260
+ Traceback (most recent call last):
261
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
262
+ await fn()
263
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
264
+ await self._send_server_request(request)
265
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
266
+ await self._writer.drain()
267
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
268
+ await self._protocol._drain_helper()
269
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
270
+ raise ConnectionResetError('Connection lost')
271
+ ConnectionResetError: Connection lost
272
+ 2025-11-07 12:57:03,948 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
273
+ Traceback (most recent call last):
274
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
275
+ await fn()
276
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
277
+ await self._send_server_request(request)
278
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
279
+ await self._writer.drain()
280
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
281
+ await self._protocol._drain_helper()
282
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
283
+ raise ConnectionResetError('Connection lost')
284
+ ConnectionResetError: Connection lost
285
+ 2025-11-07 12:57:03,950 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
286
+ Traceback (most recent call last):
287
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
288
+ await fn()
289
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
290
+ await self._send_server_request(request)
291
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
292
+ await self._writer.drain()
293
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
294
+ await self._protocol._drain_helper()
295
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
296
+ raise ConnectionResetError('Connection lost')
297
+ ConnectionResetError: Connection lost
298
+ 2025-11-07 12:57:03,951 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
299
+ Traceback (most recent call last):
300
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
301
+ await fn()
302
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
303
+ await self._send_server_request(request)
304
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
305
+ await self._writer.drain()
306
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
307
+ await self._protocol._drain_helper()
308
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
309
+ raise ConnectionResetError('Connection lost')
310
+ ConnectionResetError: Connection lost
311
+ 2025-11-07 12:57:03,952 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
312
+ Traceback (most recent call last):
313
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
314
+ await fn()
315
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
316
+ await self._send_server_request(request)
317
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
318
+ await self._writer.drain()
319
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
320
+ await self._protocol._drain_helper()
321
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
322
+ raise ConnectionResetError('Connection lost')
323
+ ConnectionResetError: Connection lost
324
+ 2025-11-07 12:57:03,953 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
325
+ Traceback (most recent call last):
326
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
327
+ await fn()
328
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
329
+ await self._send_server_request(request)
330
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
331
+ await self._writer.drain()
332
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
333
+ await self._protocol._drain_helper()
334
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
335
+ raise ConnectionResetError('Connection lost')
336
+ ConnectionResetError: Connection lost
337
+ 2025-11-07 12:57:03,954 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
338
+ Traceback (most recent call last):
339
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
340
+ await fn()
341
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
342
+ await self._send_server_request(request)
343
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
344
+ await self._writer.drain()
345
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
346
+ await self._protocol._drain_helper()
347
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
348
+ raise ConnectionResetError('Connection lost')
349
+ ConnectionResetError: Connection lost
350
+ 2025-11-07 12:57:03,955 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
351
+ Traceback (most recent call last):
352
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
353
+ await fn()
354
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
355
+ await self._send_server_request(request)
356
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
357
+ await self._writer.drain()
358
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
359
+ await self._protocol._drain_helper()
360
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
361
+ raise ConnectionResetError('Connection lost')
362
+ ConnectionResetError: Connection lost
363
+ 2025-11-07 12:57:03,955 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
364
+ Traceback (most recent call last):
365
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
366
+ await fn()
367
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
368
+ await self._send_server_request(request)
369
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
370
+ await self._writer.drain()
371
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
372
+ await self._protocol._drain_helper()
373
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
374
+ raise ConnectionResetError('Connection lost')
375
+ ConnectionResetError: Connection lost
376
+ 2025-11-07 12:57:03,957 ERROR wandb-AsyncioManager-main:234009 [asyncio_manager.py:fn_wrap_exceptions():183] Uncaught exception in run_soon callback.
377
+ Traceback (most recent call last):
378
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_manager.py", line 181, in fn_wrap_exceptions
379
+ await fn()
380
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 38, in publish
381
+ await self._send_server_request(request)
382
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/wandb/sdk/lib/service/service_client.py", line 64, in _send_server_request
383
+ await self._writer.drain()
384
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 392, in drain
385
+ await self._protocol._drain_helper()
386
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/asyncio/streams.py", line 166, in _drain_helper
387
+ raise ConnectionResetError('Connection lost')
388
+ ConnectionResetError: Connection lost
cleanrl/cleanrl/wandb/latest-run/run-g1edw7ov.wandb ADDED
Binary file (59.6 kB). View file
 
cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/files/code/cleanrl/ppo_bandit.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PPO implementation for RAGEN Bandit environment
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+
7
+ import gymnasium as gym
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.optim as optim
12
+ import tyro
13
+ from torch.distributions.categorical import Categorical
14
+ from torch.utils.tensorboard import SummaryWriter
15
+
16
+ import sys
17
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../'))
18
+
19
+ from ragen.env.bandit.env import BanditEnv
20
+ from ragen.env.bandit.config import BanditEnvConfig
21
+ from ragen_wrappers import BanditWrapper
22
+
23
+
24
+ @dataclass
25
+ class Args:
26
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
27
+ """the name of this experiment"""
28
+ seed: int = 1
29
+ """seed of the experiment"""
30
+ torch_deterministic: bool = True
31
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
32
+ cuda: bool = True
33
+ """if toggled, cuda will be enabled by default"""
34
+ track: bool = False
35
+ """if toggled, this experiment will be tracked with Weights and Biases"""
36
+ wandb_project_name: str = "cleanRL"
37
+ """the wandb's project name"""
38
+ wandb_entity: str = None
39
+ """the entity (team) of wandb's project"""
40
+ capture_video: bool = False
41
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
42
+
43
+ # Algorithm specific arguments
44
+ env_id: str = "Bandit"
45
+ """the id of the environment"""
46
+ total_timesteps: int = 1000000
47
+ """total timesteps of the experiments"""
48
+ learning_rate: float = 2.5e-4
49
+ """the learning rate of the optimizer"""
50
+ num_envs: int = 32
51
+ """the number of parallel game environments"""
52
+ num_steps: int = 512
53
+ """the number of steps to run in each environment per policy rollout"""
54
+ anneal_lr: bool = True
55
+ """Toggle learning rate annealing for policy and value networks"""
56
+ gamma: float = 0.99
57
+ """the discount factor gamma"""
58
+ gae_lambda: float = 0.95
59
+ """the lambda for the general advantage estimation"""
60
+ num_minibatches: int = 4
61
+ """the number of mini-batches"""
62
+ update_epochs: int = 4
63
+ """the K epochs to update the policy"""
64
+ norm_adv: bool = True
65
+ """Toggles advantages normalization"""
66
+ clip_coef: float = 0.2
67
+ """the surrogate clipping coefficient"""
68
+ clip_vloss: bool = True
69
+ """Toggles whether or not to use a clipped loss for the value function, as per the paper."""
70
+ ent_coef: float = 0.01
71
+ """coefficient of the entropy"""
72
+ vf_coef: float = 0.5
73
+ """coefficient of the value function"""
74
+ max_grad_norm: float = 0.5
75
+ """the maximum norm for the gradient clipping"""
76
+ target_kl: float = None
77
+ """the target KL divergence threshold"""
78
+
79
+ # to be filled in runtime
80
+ batch_size: int = 0
81
+ """the batch size (computed in runtime)"""
82
+ minibatch_size: int = 0
83
+ """the mini-batch size (computed in runtime)"""
84
+ num_iterations: int = 0
85
+ """the number of iterations (computed in runtime)"""
86
+
87
+
88
+ def make_env(env_id, idx, capture_video, run_name, seed):
89
+ def thunk():
90
+ config = BanditEnvConfig()
91
+ env = BanditEnv(config)
92
+ env = BanditWrapper(env)
93
+ env = gym.wrappers.RecordEpisodeStatistics(env)
94
+ if capture_video and idx == 0:
95
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
96
+ return env
97
+ return thunk
98
+
99
+
100
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
101
+ torch.nn.init.orthogonal_(layer.weight, std)
102
+ torch.nn.init.constant_(layer.bias, bias_const)
103
+ return layer
104
+
105
+
106
+ class Agent(nn.Module):
107
+ def __init__(self, envs):
108
+ super().__init__()
109
+ obs_shape = np.array(envs.single_observation_space.shape).prod()
110
+ self.critic = nn.Sequential(
111
+ layer_init(nn.Linear(obs_shape, 64)),
112
+ nn.Tanh(),
113
+ layer_init(nn.Linear(64, 64)),
114
+ nn.Tanh(),
115
+ layer_init(nn.Linear(64, 1), std=1.0),
116
+ )
117
+ self.actor = nn.Sequential(
118
+ layer_init(nn.Linear(obs_shape, 64)),
119
+ nn.Tanh(),
120
+ layer_init(nn.Linear(64, 64)),
121
+ nn.Tanh(),
122
+ layer_init(nn.Linear(64, envs.single_action_space.n), std=0.01),
123
+ )
124
+
125
+ def get_value(self, x):
126
+ return self.critic(x)
127
+
128
+ def get_action_and_value(self, x, action=None):
129
+ logits = self.actor(x)
130
+ probs = Categorical(logits=logits)
131
+ if action is None:
132
+ action = probs.sample()
133
+ return action, probs.log_prob(action), probs.entropy(), self.critic(x)
134
+
135
+
136
+ if __name__ == "__main__":
137
+ args = tyro.cli(Args)
138
+ args.batch_size = int(args.num_envs * args.num_steps)
139
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
140
+ args.num_iterations = args.total_timesteps // args.batch_size
141
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
142
+ if args.track:
143
+ import wandb
144
+
145
+ wandb.init(
146
+ project=args.wandb_project_name,
147
+ entity=args.wandb_entity,
148
+ sync_tensorboard=True,
149
+ config=vars(args),
150
+ name=run_name,
151
+ monitor_gym=True,
152
+ save_code=True,
153
+ )
154
+ writer = SummaryWriter(f"runs/{run_name}")
155
+ writer.add_text(
156
+ "hyperparameters",
157
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
158
+ )
159
+
160
+ # TRY NOT TO MODIFY: seeding
161
+ random.seed(args.seed)
162
+ np.random.seed(args.seed)
163
+ torch.manual_seed(args.seed)
164
+ torch.backends.cudnn.deterministic = args.torch_deterministic
165
+
166
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
167
+
168
+ # env setup
169
+ envs = gym.vector.SyncVectorEnv(
170
+ [make_env(args.env_id, i, args.capture_video, run_name, args.seed + i) for i in range(args.num_envs)],
171
+ )
172
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
173
+
174
+ agent = Agent(envs).to(device)
175
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
176
+
177
+ # ALGO Logic: Storage setup
178
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
179
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
180
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
181
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
182
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
183
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
184
+
185
+ # TRY NOT TO MODIFY: start the game
186
+ global_step = 0
187
+ start_time = time.time()
188
+ next_obs, _ = envs.reset(seed=args.seed)
189
+ next_obs = torch.Tensor(next_obs).to(device)
190
+ next_done = torch.zeros(args.num_envs).to(device)
191
+
192
+ for iteration in range(1, args.num_iterations + 1):
193
+ # Annealing the rate if instructed to do so.
194
+ if args.anneal_lr:
195
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
196
+ lrnow = frac * args.learning_rate
197
+ optimizer.param_groups[0]["lr"] = lrnow
198
+
199
+ for step in range(0, args.num_steps):
200
+ global_step += args.num_envs
201
+ obs[step] = next_obs
202
+ dones[step] = next_done
203
+
204
+ # ALGO LOGIC: action logic
205
+ with torch.no_grad():
206
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
207
+ values[step] = value.flatten()
208
+ actions[step] = action
209
+ logprobs[step] = logprob
210
+
211
+ # TRY NOT TO MODIFY: execute the game and log data.
212
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
213
+ next_done = np.logical_or(terminations, truncations)
214
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
215
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
216
+
217
+ if "final_info" in infos:
218
+ for info in infos["final_info"]:
219
+ if info and "episode" in info:
220
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
221
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
222
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
223
+
224
+ # bootstrap value if not done
225
+ with torch.no_grad():
226
+ next_value = agent.get_value(next_obs).reshape(1, -1)
227
+ advantages = torch.zeros_like(rewards).to(device)
228
+ lastgaelam = 0
229
+ for t in reversed(range(args.num_steps)):
230
+ if t == args.num_steps - 1:
231
+ nextnonterminal = 1.0 - next_done
232
+ nextvalues = next_value
233
+ else:
234
+ nextnonterminal = 1.0 - dones[t + 1]
235
+ nextvalues = values[t + 1]
236
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
237
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
238
+ returns = advantages + values
239
+
240
+ # flatten the batch
241
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
242
+ b_logprobs = logprobs.reshape(-1)
243
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
244
+ b_advantages = advantages.reshape(-1)
245
+ b_returns = returns.reshape(-1)
246
+ b_values = values.reshape(-1)
247
+
248
+ # Optimizing the policy and value network
249
+ b_inds = np.arange(args.batch_size)
250
+ clipfracs = []
251
+ for epoch in range(args.update_epochs):
252
+ np.random.shuffle(b_inds)
253
+ for start in range(0, args.batch_size, args.minibatch_size):
254
+ end = start + args.minibatch_size
255
+ mb_inds = b_inds[start:end]
256
+
257
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
258
+ logratio = newlogprob - b_logprobs[mb_inds]
259
+ ratio = logratio.exp()
260
+
261
+ with torch.no_grad():
262
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
263
+ old_approx_kl = (-logratio).mean()
264
+ approx_kl = ((ratio - 1) - logratio).mean()
265
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
266
+
267
+ mb_advantages = b_advantages[mb_inds]
268
+ if args.norm_adv:
269
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
270
+
271
+ # Policy loss
272
+ pg_loss1 = -mb_advantages * ratio
273
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
274
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
275
+
276
+ # Value loss
277
+ newvalue = newvalue.view(-1)
278
+ if args.clip_vloss:
279
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
280
+ v_clipped = b_values[mb_inds] + torch.clamp(
281
+ newvalue - b_values[mb_inds],
282
+ -args.clip_coef,
283
+ args.clip_coef,
284
+ )
285
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
286
+ v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped)
287
+ v_loss = 0.5 * v_loss_max.mean()
288
+ else:
289
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
290
+
291
+ entropy_loss = entropy.mean()
292
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
293
+
294
+ optimizer.zero_grad()
295
+ loss.backward()
296
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
297
+ optimizer.step()
298
+
299
+ if args.target_kl is not None and approx_kl > args.target_kl:
300
+ break
301
+
302
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
303
+ var_y = np.var(y_true)
304
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
305
+
306
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
307
+ writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step)
308
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
309
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
310
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
311
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
312
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
313
+ writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step)
314
+ writer.add_scalar("losses/explained_variance", explained_var, global_step)
315
+
316
+ # Additional useful metrics
317
+ writer.add_scalar("charts/avg_reward", rewards.mean().item(), global_step)
318
+ writer.add_scalar("charts/avg_value", values.mean().item(), global_step)
319
+ writer.add_scalar("charts/max_reward", rewards.max().item(), global_step)
320
+ writer.add_scalar("charts/min_reward", rewards.min().item(), global_step)
321
+
322
+ # Console output with key metrics
323
+ sps = int(global_step / (time.time() - start_time))
324
+ progress = 100 * iteration / args.num_iterations
325
+ print(f"[{progress:5.1f}%] Iter {iteration:4d}/{args.num_iterations} | "
326
+ f"SPS: {sps:5d} | "
327
+ f"Reward: {rewards.mean().item():6.3f} | "
328
+ f"Value: {values.mean().item():6.3f} | "
329
+ f"VLoss: {v_loss.item():.4f} | "
330
+ f"PLoss: {pg_loss.item():.4f} | "
331
+ f"Ent: {entropy_loss.item():.4f}")
332
+ writer.add_scalar("charts/SPS", sps, global_step)
333
+
334
+ envs.close()
335
+ writer.close()
cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/files/config.yaml ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _wandb:
2
+ value:
3
+ cli_version: 0.22.3
4
+ code_path: code/cleanrl/ppo_bandit.py
5
+ e:
6
+ xa4im9wkbwlcw1r2rhsulzxqq9xni8uv:
7
+ args:
8
+ - --track
9
+ - --wandb-project-name
10
+ - ragen-bandit
11
+ codePath: cleanrl/ppo_bandit.py
12
+ codePathLocal: ppo_bandit.py
13
+ cpu_count: 64
14
+ cpu_count_logical: 128
15
+ cudaVersion: "12.4"
16
+ disk:
17
+ /:
18
+ total: "5153960755200"
19
+ used: "30509879296"
20
+ email: haoyu-wa22@mails.tsinghua.edu.cn
21
+ executable: /root/local/miniconda3/envs/ragen/bin/python
22
+ git:
23
+ commit: 004f8a086a892a2a180f4dd332b90d83a968aa7a
24
+ remote: https://github.com/vwxyzjn/cleanrl.git
25
+ gpu: NVIDIA H100 80GB HBM3
26
+ gpu_count: 8
27
+ gpu_nvidia:
28
+ - architecture: Hopper
29
+ cudaCores: 16896
30
+ memoryTotal: "85520809984"
31
+ name: NVIDIA H100 80GB HBM3
32
+ uuid: GPU-35e2d43d-4067-82ce-90d4-def9e389bf28
33
+ - architecture: Hopper
34
+ cudaCores: 16896
35
+ memoryTotal: "85520809984"
36
+ name: NVIDIA H100 80GB HBM3
37
+ uuid: GPU-af4135e3-88f2-e9ac-518d-502c75a85429
38
+ - architecture: Hopper
39
+ cudaCores: 16896
40
+ memoryTotal: "85520809984"
41
+ name: NVIDIA H100 80GB HBM3
42
+ uuid: GPU-d7fdeeba-fe9b-ec03-d9f7-6724fe4266b5
43
+ - architecture: Hopper
44
+ cudaCores: 16896
45
+ memoryTotal: "85520809984"
46
+ name: NVIDIA H100 80GB HBM3
47
+ uuid: GPU-ccc4f668-3882-5a8e-2c07-c5cd08f6f666
48
+ - architecture: Hopper
49
+ cudaCores: 16896
50
+ memoryTotal: "85520809984"
51
+ name: NVIDIA H100 80GB HBM3
52
+ uuid: GPU-7b73c0cf-d3d5-e10c-7176-a43be1e41001
53
+ - architecture: Hopper
54
+ cudaCores: 16896
55
+ memoryTotal: "85520809984"
56
+ name: NVIDIA H100 80GB HBM3
57
+ uuid: GPU-81b58d94-5d1f-8ec2-f9d2-fd56172ed177
58
+ - architecture: Hopper
59
+ cudaCores: 16896
60
+ memoryTotal: "85520809984"
61
+ name: NVIDIA H100 80GB HBM3
62
+ uuid: GPU-03e8bc66-3b44-6794-49fd-5392fbdda6d1
63
+ - architecture: Hopper
64
+ cudaCores: 16896
65
+ memoryTotal: "85520809984"
66
+ name: NVIDIA H100 80GB HBM3
67
+ uuid: GPU-b7cf0ec6-7c29-1179-dceb-09565da51890
68
+ host: pt-4d654cf4576f4d23ad3d3919f12932fe-worker-0
69
+ memory:
70
+ total: "2163642122240"
71
+ os: Linux-5.14.0-284.25.1.el9_2.x86_64-x86_64-with-glibc2.35
72
+ program: /mnt/general/wanghy/RAGEN/cleanrl/cleanrl/ppo_bandit.py
73
+ python: CPython 3.12.12
74
+ root: /mnt/general/wanghy/RAGEN/cleanrl/cleanrl
75
+ startedAt: "2025-11-07T02:06:19.722084Z"
76
+ writerId: xa4im9wkbwlcw1r2rhsulzxqq9xni8uv
77
+ m: []
78
+ python_version: 3.12.12
79
+ t:
80
+ "1":
81
+ - 1
82
+ - 49
83
+ - 51
84
+ - 105
85
+ "2":
86
+ - 1
87
+ - 49
88
+ - 51
89
+ - 105
90
+ "3":
91
+ - 13
92
+ - 16
93
+ - 35
94
+ "4": 3.12.12
95
+ "5": 0.22.3
96
+ "12": 0.22.3
97
+ "13": linux-x86_64
98
+ anneal_lr:
99
+ value: true
100
+ batch_size:
101
+ value: 16384
102
+ capture_video:
103
+ value: false
104
+ clip_coef:
105
+ value: 0.2
106
+ clip_vloss:
107
+ value: true
108
+ cuda:
109
+ value: true
110
+ ent_coef:
111
+ value: 0.01
112
+ env_id:
113
+ value: Bandit
114
+ exp_name:
115
+ value: ppo_bandit
116
+ gae_lambda:
117
+ value: 0.95
118
+ gamma:
119
+ value: 0.99
120
+ learning_rate:
121
+ value: 0.00025
122
+ max_grad_norm:
123
+ value: 0.5
124
+ minibatch_size:
125
+ value: 4096
126
+ norm_adv:
127
+ value: true
128
+ num_envs:
129
+ value: 32
130
+ num_iterations:
131
+ value: 61
132
+ num_minibatches:
133
+ value: 4
134
+ num_steps:
135
+ value: 512
136
+ seed:
137
+ value: 1
138
+ target_kl:
139
+ value: null
140
+ torch_deterministic:
141
+ value: true
142
+ total_timesteps:
143
+ value: 1000000
144
+ track:
145
+ value: true
146
+ update_epochs:
147
+ value: 4
148
+ vf_coef:
149
+ value: 0.5
150
+ wandb_entity:
151
+ value: null
152
+ wandb_project_name:
153
+ value: ragen-bandit
cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/files/output.log ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [ 1.6%] Iter 1/61 | SPS: 17749 | Reward: 0.087 | Value: -0.018 | VLoss: 0.0488 | PLoss: -0.0002 | Ent: 0.6931
2
+ [ 3.3%] Iter 2/61 | SPS: 21695 | Reward: 0.084 | Value: 0.098 | VLoss: 0.0444 | PLoss: 0.0000 | Ent: 0.6929
3
+ [ 4.9%] Iter 3/61 | SPS: 23367 | Reward: 0.087 | Value: 0.131 | VLoss: 0.0472 | PLoss: -0.0000 | Ent: 0.6929
4
+ [ 6.6%] Iter 4/61 | SPS: 24347 | Reward: 0.087 | Value: 0.155 | VLoss: 0.0452 | PLoss: -0.0001 | Ent: 0.6928
5
+ [ 8.2%] Iter 5/61 | SPS: 24887 | Reward: 0.088 | Value: 0.169 | VLoss: 0.0457 | PLoss: -0.0001 | Ent: 0.6923
6
+ [ 9.8%] Iter 6/61 | SPS: 25340 | Reward: 0.086 | Value: 0.176 | VLoss: 0.0476 | PLoss: -0.0001 | Ent: 0.6916
7
+ [ 11.5%] Iter 7/61 | SPS: 25670 | Reward: 0.089 | Value: 0.173 | VLoss: 0.0484 | PLoss: -0.0001 | Ent: 0.6905
8
+ [ 13.1%] Iter 8/61 | SPS: 25929 | Reward: 0.089 | Value: 0.175 | VLoss: 0.0470 | PLoss: -0.0000 | Ent: 0.6899
9
+ [ 14.8%] Iter 9/61 | SPS: 26121 | Reward: 0.089 | Value: 0.175 | VLoss: 0.0480 | PLoss: 0.0001 | Ent: 0.6898
10
+ [ 16.4%] Iter 10/61 | SPS: 26281 | Reward: 0.083 | Value: 0.177 | VLoss: 0.0438 | PLoss: -0.0000 | Ent: 0.6903
11
+ [ 18.0%] Iter 11/61 | SPS: 26419 | Reward: 0.091 | Value: 0.165 | VLoss: 0.0487 | PLoss: 0.0000 | Ent: 0.6903
12
+ [ 19.7%] Iter 12/61 | SPS: 26528 | Reward: 0.085 | Value: 0.179 | VLoss: 0.0462 | PLoss: -0.0001 | Ent: 0.6907
13
+ [ 21.3%] Iter 13/61 | SPS: 26604 | Reward: 0.085 | Value: 0.169 | VLoss: 0.0466 | PLoss: -0.0003 | Ent: 0.6913
14
+ [ 23.0%] Iter 14/61 | SPS: 26663 | Reward: 0.086 | Value: 0.169 | VLoss: 0.0449 | PLoss: -0.0002 | Ent: 0.6920
15
+ [ 24.6%] Iter 15/61 | SPS: 26710 | Reward: 0.087 | Value: 0.169 | VLoss: 0.0469 | PLoss: 0.0001 | Ent: 0.6924
16
+ [ 26.2%] Iter 16/61 | SPS: 26749 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0486 | PLoss: -0.0002 | Ent: 0.6927
17
+ [ 27.9%] Iter 17/61 | SPS: 26778 | Reward: 0.087 | Value: 0.172 | VLoss: 0.0473 | PLoss: 0.0000 | Ent: 0.6929
18
+ [ 29.5%] Iter 18/61 | SPS: 26807 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0456 | PLoss: -0.0001 | Ent: 0.6930
19
+ [ 31.1%] Iter 19/61 | SPS: 26829 | Reward: 0.089 | Value: 0.169 | VLoss: 0.0488 | PLoss: -0.0000 | Ent: 0.6931
20
+ [ 32.8%] Iter 20/61 | SPS: 26867 | Reward: 0.088 | Value: 0.179 | VLoss: 0.0461 | PLoss: -0.0001 | Ent: 0.6931
21
+ [ 34.4%] Iter 21/61 | SPS: 26887 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0458 | PLoss: 0.0002 | Ent: 0.6931
22
+ [ 36.1%] Iter 22/61 | SPS: 26906 | Reward: 0.091 | Value: 0.172 | VLoss: 0.0505 | PLoss: -0.0000 | Ent: 0.6931
23
+ [ 37.7%] Iter 23/61 | SPS: 26936 | Reward: 0.083 | Value: 0.181 | VLoss: 0.0434 | PLoss: -0.0001 | Ent: 0.6930
24
+ [ 39.3%] Iter 24/61 | SPS: 26966 | Reward: 0.084 | Value: 0.167 | VLoss: 0.0435 | PLoss: 0.0000 | Ent: 0.6929
25
+ [ 41.0%] Iter 25/61 | SPS: 26984 | Reward: 0.086 | Value: 0.169 | VLoss: 0.0457 | PLoss: -0.0001 | Ent: 0.6929
26
+ [ 42.6%] Iter 26/61 | SPS: 27009 | Reward: 0.087 | Value: 0.167 | VLoss: 0.0446 | PLoss: -0.0000 | Ent: 0.6928
27
+ [ 44.3%] Iter 27/61 | SPS: 27032 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0472 | PLoss: -0.0000 | Ent: 0.6928
28
+ [ 45.9%] Iter 28/61 | SPS: 27053 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0488 | PLoss: -0.0001 | Ent: 0.6925
29
+ [ 47.5%] Iter 29/61 | SPS: 27075 | Reward: 0.088 | Value: 0.177 | VLoss: 0.0448 | PLoss: 0.0000 | Ent: 0.6923
30
+ [ 49.2%] Iter 30/61 | SPS: 27094 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0487 | PLoss: -0.0000 | Ent: 0.6924
31
+ [ 50.8%] Iter 31/61 | SPS: 27113 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0472 | PLoss: -0.0000 | Ent: 0.6925
32
+ [ 52.5%] Iter 32/61 | SPS: 27131 | Reward: 0.089 | Value: 0.173 | VLoss: 0.0494 | PLoss: -0.0000 | Ent: 0.6925
33
+ [ 54.1%] Iter 33/61 | SPS: 27147 | Reward: 0.084 | Value: 0.178 | VLoss: 0.0438 | PLoss: -0.0001 | Ent: 0.6923
34
+ [ 55.7%] Iter 34/61 | SPS: 27159 | Reward: 0.087 | Value: 0.167 | VLoss: 0.0452 | PLoss: -0.0001 | Ent: 0.6920
35
+ [ 57.4%] Iter 35/61 | SPS: 27159 | Reward: 0.086 | Value: 0.175 | VLoss: 0.0466 | PLoss: 0.0000 | Ent: 0.6919
36
+ [ 59.0%] Iter 36/61 | SPS: 27172 | Reward: 0.086 | Value: 0.169 | VLoss: 0.0448 | PLoss: 0.0000 | Ent: 0.6918
37
+ [ 60.7%] Iter 37/61 | SPS: 27184 | Reward: 0.087 | Value: 0.172 | VLoss: 0.0443 | PLoss: -0.0000 | Ent: 0.6916
38
+ [ 62.3%] Iter 38/61 | SPS: 27184 | Reward: 0.089 | Value: 0.173 | VLoss: 0.0484 | PLoss: -0.0001 | Ent: 0.6911
39
+ [ 63.9%] Iter 39/61 | SPS: 27189 | Reward: 0.090 | Value: 0.175 | VLoss: 0.0499 | PLoss: 0.0001 | Ent: 0.6906
40
+ [ 65.6%] Iter 40/61 | SPS: 27200 | Reward: 0.086 | Value: 0.180 | VLoss: 0.0454 | PLoss: 0.0000 | Ent: 0.6909
41
+ [ 67.2%] Iter 41/61 | SPS: 27200 | Reward: 0.086 | Value: 0.175 | VLoss: 0.0453 | PLoss: 0.0000 | Ent: 0.6913
42
+ [ 68.9%] Iter 42/61 | SPS: 27197 | Reward: 0.088 | Value: 0.171 | VLoss: 0.0457 | PLoss: 0.0000 | Ent: 0.6913
43
+ [ 70.5%] Iter 43/61 | SPS: 27199 | Reward: 0.086 | Value: 0.172 | VLoss: 0.0454 | PLoss: -0.0001 | Ent: 0.6912
44
+ [ 72.1%] Iter 44/61 | SPS: 27200 | Reward: 0.088 | Value: 0.172 | VLoss: 0.0479 | PLoss: -0.0001 | Ent: 0.6912
45
+ [ 73.8%] Iter 45/61 | SPS: 27202 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0456 | PLoss: -0.0001 | Ent: 0.6915
46
+ [ 75.4%] Iter 46/61 | SPS: 27205 | Reward: 0.090 | Value: 0.173 | VLoss: 0.0484 | PLoss: 0.0000 | Ent: 0.6916
47
+ [ 77.0%] Iter 47/61 | SPS: 27202 | Reward: 0.085 | Value: 0.178 | VLoss: 0.0437 | PLoss: -0.0001 | Ent: 0.6918
48
+ [ 78.7%] Iter 48/61 | SPS: 27203 | Reward: 0.089 | Value: 0.171 | VLoss: 0.0512 | PLoss: 0.0000 | Ent: 0.6920
49
+ [ 80.3%] Iter 49/61 | SPS: 27205 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0459 | PLoss: -0.0000 | Ent: 0.6919
50
+ [ 82.0%] Iter 50/61 | SPS: 27208 | Reward: 0.085 | Value: 0.175 | VLoss: 0.0438 | PLoss: -0.0000 | Ent: 0.6919
51
+ [ 83.6%] Iter 51/61 | SPS: 27209 | Reward: 0.087 | Value: 0.171 | VLoss: 0.0476 | PLoss: 0.0000 | Ent: 0.6920
52
+ [ 85.2%] Iter 52/61 | SPS: 27211 | Reward: 0.090 | Value: 0.174 | VLoss: 0.0479 | PLoss: 0.0000 | Ent: 0.6920
53
+ [ 86.9%] Iter 53/61 | SPS: 27213 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0468 | PLoss: -0.0000 | Ent: 0.6919
54
+ [ 88.5%] Iter 54/61 | SPS: 27215 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0472 | PLoss: -0.0001 | Ent: 0.6921
55
+ [ 90.2%] Iter 55/61 | SPS: 27206 | Reward: 0.086 | Value: 0.177 | VLoss: 0.0453 | PLoss: -0.0000 | Ent: 0.6922
56
+ [ 91.8%] Iter 56/61 | SPS: 27204 | Reward: 0.086 | Value: 0.175 | VLoss: 0.0469 | PLoss: -0.0000 | Ent: 0.6922
57
+ [ 93.4%] Iter 57/61 | SPS: 27205 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0468 | PLoss: 0.0000 | Ent: 0.6923
58
+ [ 95.1%] Iter 58/61 | SPS: 27209 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0465 | PLoss: -0.0000 | Ent: 0.6922
59
+ [ 96.7%] Iter 59/61 | SPS: 27210 | Reward: 0.090 | Value: 0.174 | VLoss: 0.0481 | PLoss: 0.0000 | Ent: 0.6922
60
+ [ 98.4%] Iter 60/61 | SPS: 27219 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0475 | PLoss: 0.0000 | Ent: 0.6922
61
+ [100.0%] Iter 61/61 | SPS: 27228 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0484 | PLoss: -0.0000 | Ent: 0.6922
cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/files/requirements.txt ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ragen==0.1
2
+ setuptools==80.9.0
3
+ wheel==0.45.1
4
+ pip==25.2
5
+ zipp==3.23.0
6
+ verl==0.2.0.dev0
7
+ ragen==0.1
8
+ triton==3.2.0
9
+ nvidia-cusparselt-cu12==0.6.2
10
+ mpmath==1.3.0
11
+ typing_extensions==4.15.0
12
+ sympy==1.13.1
13
+ nvidia-nvtx-cu12==12.4.127
14
+ nvidia-nvjitlink-cu12==12.4.127
15
+ nvidia-nccl-cu12==2.21.5
16
+ nvidia-curand-cu12==10.3.5.147
17
+ nvidia-cufft-cu12==11.2.1.3
18
+ nvidia-cuda-runtime-cu12==12.4.127
19
+ nvidia-cuda-nvrtc-cu12==12.4.127
20
+ nvidia-cuda-cupti-cu12==12.4.127
21
+ nvidia-cublas-cu12==12.4.5.8
22
+ networkx==3.5
23
+ MarkupSafe==2.1.5
24
+ fsspec==2025.9.0
25
+ filelock==3.19.1
26
+ nvidia-cusparse-cu12==12.3.1.170
27
+ nvidia-cudnn-cu12==9.1.0.70
28
+ Jinja2==3.1.6
29
+ nvidia-cusolver-cu12==11.6.1.9
30
+ torch==2.6.0+cu124
31
+ einops==0.8.1
32
+ flash_attn==2.7.4.post1
33
+ pytz==2025.2
34
+ pyperclip==1.11.0
35
+ pylatexenc==2.10
36
+ pyjnius==1.7.0
37
+ py-cpuinfo==9.0.0
38
+ pure_eval==0.2.3
39
+ ptyprocess==0.7.0
40
+ gym-notices==0.1.0
41
+ flatbuffers==25.9.23
42
+ fastrlock==0.8.3
43
+ Farama-Notifications==0.0.4
44
+ cymem==2.0.11
45
+ antlr4-python3-runtime==4.9.3
46
+ xxhash==3.6.0
47
+ wrapt==2.0.0
48
+ Werkzeug==3.1.3
49
+ websockets==15.0.1
50
+ wcwidth==0.2.14
51
+ wasabi==1.1.3
52
+ uvloop==0.22.1
53
+ urllib3==2.5.0
54
+ tzdata==2025.2
55
+ typing-inspection==0.4.2
56
+ traitlets==5.14.3
57
+ tqdm==4.67.1
58
+ threadpoolctl==3.6.0
59
+ tabulate==0.9.0
60
+ spacy-loggers==1.0.5
61
+ spacy-legacy==3.0.12
62
+ soupsieve==2.8
63
+ sniffio==1.3.1
64
+ smmap==5.0.2
65
+ six==1.17.0
66
+ shellingham==1.5.4
67
+ sentencepiece==0.2.1
68
+ safetensors==0.6.2
69
+ rpds-py==0.28.0
70
+ rignore==0.7.6
71
+ regex==2025.11.3
72
+ RapidFuzz==3.14.3
73
+ pyzmq==27.1.0
74
+ PyYAML==6.0.3
75
+ pytokens==0.3.0
76
+ python-multipart==0.0.20
77
+ python-json-logger==4.0.0
78
+ python-dotenv==1.2.1
79
+ PySocks==1.7.1
80
+ pyparsing==3.2.5
81
+ PyJWT==2.10.1
82
+ Pygments==2.19.2
83
+ pygame==2.6.1
84
+ pydantic_core==2.41.5
85
+ pycparser==2.23
86
+ pycountry==24.6.1
87
+ pybind11==3.0.1
88
+ pyarrow==22.0.0
89
+ psutil==7.1.3
90
+ protobuf==6.33.0
91
+ propcache==0.4.1
92
+ prometheus_client==0.23.1
93
+ platformdirs==4.5.0
94
+ pillow==11.3.0
95
+ pexpect==4.9.0
96
+ pathvalidate==3.3.1
97
+ pathspec==0.12.1
98
+ pathable==0.4.4
99
+ partial-json-parser==0.2.1.1.post6
100
+ parso==0.8.5
101
+ packaging==25.0
102
+ orjson==3.11.4
103
+ numpy==1.26.4
104
+ ninja==1.13.0
105
+ nest-asyncio==1.6.0
106
+ mypy_extensions==1.1.0
107
+ murmurhash==1.0.13
108
+ multidict==6.7.0
109
+ msgspec==0.19.0
110
+ msgpack==1.1.2
111
+ more-itertools==10.8.0
112
+ mdurl==0.1.2
113
+ marisa-trie==1.3.1
114
+ llvmlite==0.43.0
115
+ llguidance==0.7.30
116
+ lark==1.2.2
117
+ kiwisolver==1.4.9
118
+ joblib==1.5.2
119
+ jiter==0.11.1
120
+ jeepney==0.9.0
121
+ jaraco.context==6.0.1
122
+ itsdangerous==2.2.0
123
+ interegular==0.3.3
124
+ idna==3.11
125
+ humanfriendly==10.0
126
+ httpx-sse==0.4.3
127
+ httptools==0.7.1
128
+ html2text==2025.4.15
129
+ hf-xet==1.2.0
130
+ h11==0.16.0
131
+ frozenlist==1.8.0
132
+ fonttools==4.60.1
133
+ executing==2.2.1
134
+ exceptiongroup==1.3.0
135
+ eval_type_backport==0.2.2
136
+ docutils==0.22.3
137
+ docstring_parser==0.17.0
138
+ dnspython==2.8.0
139
+ distro==1.9.0
140
+ diskcache==5.6.3
141
+ dill==0.4.0
142
+ decorator==5.2.1
143
+ debugpy==1.8.17
144
+ Cython==3.2.0
145
+ cycler==0.12.1
146
+ codetiming==1.4.0
147
+ cloudpickle==3.1.2
148
+ cloudpathlib==0.23.0
149
+ click==8.2.1
150
+ charset-normalizer==3.4.4
151
+ certifi==2025.10.5
152
+ catalogue==2.0.10
153
+ cachetools==6.2.1
154
+ blinker==1.9.0
155
+ blake3==1.0.8
156
+ beartype==0.22.5
157
+ attrs==25.4.0
158
+ asttokens==3.0.0
159
+ astor==0.8.1
160
+ annotated-types==0.7.0
161
+ annotated-doc==0.0.3
162
+ airportsdata==20250909
163
+ aiohappyeyeballs==2.6.1
164
+ yarl==1.22.0
165
+ uvicorn==0.38.0
166
+ typer-slim==0.20.0
167
+ thefuzz==0.22.1
168
+ stack-data==0.6.3
169
+ srsly==2.5.1
170
+ smart_open==7.4.4
171
+ sentry-sdk==2.43.0
172
+ scipy==1.16.3
173
+ requests==2.32.5
174
+ referencing==0.36.2
175
+ rank-bm25==0.2.2
176
+ python-dateutil==2.9.0.post0
177
+ pydantic==2.12.4
178
+ py-key-value-shared==0.2.8
179
+ prompt_toolkit==3.0.52
180
+ preshed==3.0.10
181
+ opencv-python-headless==4.11.0.86
182
+ omegaconf==2.3.0
183
+ numba==0.60.0
184
+ nltk==3.9.2
185
+ multiprocess==0.70.18
186
+ matplotlib-inline==0.2.1
187
+ markdown-it-py==4.0.0
188
+ language_data==1.3.0
189
+ jedi==0.19.2
190
+ jaraco.functools==4.3.0
191
+ jaraco.classes==3.4.0
192
+ ipython_pygments_lexers==1.1.1
193
+ importlib_metadata==8.7.0
194
+ ImageIO==2.37.2
195
+ httpcore==1.0.9
196
+ gymnasium==1.2.2
197
+ gym==0.26.2
198
+ gitdb==4.0.12
199
+ gguf==0.10.0
200
+ Flask==3.1.2
201
+ faiss-cpu==1.12.0
202
+ email-validator==2.3.0
203
+ depyf==0.18.0
204
+ cupy-cuda12x==13.6.0
205
+ contourpy==1.3.3
206
+ coloredlogs==15.0.1
207
+ cffi==2.0.0
208
+ blis==1.3.0
209
+ black==25.9.0
210
+ beautifulsoup4==4.14.2
211
+ anyio==4.11.0
212
+ aiosignal==1.4.0
213
+ watchfiles==1.1.1
214
+ tiktoken==0.12.0
215
+ starlette==0.49.3
216
+ sse-starlette==3.0.3
217
+ scikit-learn==1.7.2
218
+ rich==14.2.0
219
+ pydantic-settings==2.11.0
220
+ pydantic-extra-types==2.10.6
221
+ py-key-value-aio==0.2.8
222
+ pandas==2.3.3
223
+ openapi-pydantic==0.5.1
224
+ onnxruntime==1.23.2
225
+ matplotlib==3.10.7
226
+ lm-format-enforcer==0.10.12
227
+ langcodes==3.5.0
228
+ jsonschema-specifications==2025.9.1
229
+ jsonschema-path==0.3.4
230
+ ipython==9.7.0
231
+ hydra-core==1.3.2
232
+ huggingface-hub==0.36.0
233
+ httpx==0.28.1
234
+ gym-sokoban==0.0.6
235
+ GitPython==3.1.45
236
+ cryptography==46.0.3
237
+ confection==0.1.5
238
+ cleantext==1.1.4
239
+ aiohttp==3.13.2
240
+ xformers==0.0.29.post2
241
+ weasel==0.4.2
242
+ wandb==0.22.3
243
+ typer==0.19.2
244
+ torchvision==0.21.0
245
+ torchdata==0.11.0
246
+ torchaudio==2.6.0
247
+ tokenizers==0.22.1
248
+ thinc==8.3.7
249
+ tensordict==0.8.3
250
+ SecretStorage==3.4.0
251
+ rich-toolkit==0.15.1
252
+ rich-rst==1.3.2
253
+ prometheus-fastapi-instrumentator==7.1.0
254
+ openai==2.7.1
255
+ jsonschema==4.25.1
256
+ gdown==5.2.0
257
+ fastapi==0.121.0
258
+ Authlib==1.6.5
259
+ anthropic==0.72.0
260
+ accelerate==1.11.0
261
+ transformers==4.57.1
262
+ together==1.5.30
263
+ spacy==3.8.7
264
+ ray==2.51.1
265
+ outlines_core==0.1.26
266
+ mistral_common==1.8.5
267
+ mcp==1.20.0
268
+ keyring==25.6.0
269
+ fastapi-cloud-cli==0.3.1
270
+ fastapi-cli==0.0.14
271
+ datasets==4.4.1
272
+ cyclopts==4.2.1
273
+ xgrammar==0.1.16
274
+ peft==0.17.1
275
+ outlines==0.1.11
276
+ compressed-tensors==0.9.2
277
+ fastmcp==2.13.0.2
278
+ vllm==0.8.2
279
+ pyserini==1.3.0
280
+ typeguard==4.4.4
281
+ shtab==1.7.2
282
+ tyro==0.9.35
283
+ tensorboard-data-server==0.7.2
284
+ Markdown==3.10
285
+ grpcio==1.76.0
286
+ absl-py==2.3.1
287
+ tensorboard==2.20.0
288
+ ragen==0.1
289
+ verl==0.2.0.dev0
290
+ autocommand==2.2.2
291
+ backports.tarfile==1.2.0
292
+ importlib_metadata==8.0.0
293
+ inflect==7.3.1
294
+ jaraco.collections==5.1.0
295
+ jaraco.context==5.3.0
296
+ jaraco.functools==4.0.1
297
+ jaraco.text==3.12.1
298
+ more-itertools==10.3.0
299
+ packaging==24.2
300
+ platformdirs==4.2.2
301
+ tomli==2.0.1
302
+ typeguard==4.3.0
303
+ typing_extensions==4.12.2
304
+ wheel==0.45.1
305
+ zipp==3.19.2
cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/files/wandb-metadata.json ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "os": "Linux-5.14.0-284.25.1.el9_2.x86_64-x86_64-with-glibc2.35",
3
+ "python": "CPython 3.12.12",
4
+ "startedAt": "2025-11-07T02:06:19.722084Z",
5
+ "args": [
6
+ "--track",
7
+ "--wandb-project-name",
8
+ "ragen-bandit"
9
+ ],
10
+ "program": "/mnt/general/wanghy/RAGEN/cleanrl/cleanrl/ppo_bandit.py",
11
+ "codePath": "cleanrl/ppo_bandit.py",
12
+ "codePathLocal": "ppo_bandit.py",
13
+ "git": {
14
+ "remote": "https://github.com/vwxyzjn/cleanrl.git",
15
+ "commit": "004f8a086a892a2a180f4dd332b90d83a968aa7a"
16
+ },
17
+ "email": "haoyu-wa22@mails.tsinghua.edu.cn",
18
+ "root": "/mnt/general/wanghy/RAGEN/cleanrl/cleanrl",
19
+ "host": "pt-4d654cf4576f4d23ad3d3919f12932fe-worker-0",
20
+ "executable": "/root/local/miniconda3/envs/ragen/bin/python",
21
+ "cpu_count": 64,
22
+ "cpu_count_logical": 128,
23
+ "gpu": "NVIDIA H100 80GB HBM3",
24
+ "gpu_count": 8,
25
+ "disk": {
26
+ "/": {
27
+ "total": "5153960755200",
28
+ "used": "30509879296"
29
+ }
30
+ },
31
+ "memory": {
32
+ "total": "2163642122240"
33
+ },
34
+ "gpu_nvidia": [
35
+ {
36
+ "name": "NVIDIA H100 80GB HBM3",
37
+ "memoryTotal": "85520809984",
38
+ "cudaCores": 16896,
39
+ "architecture": "Hopper",
40
+ "uuid": "GPU-35e2d43d-4067-82ce-90d4-def9e389bf28"
41
+ },
42
+ {
43
+ "name": "NVIDIA H100 80GB HBM3",
44
+ "memoryTotal": "85520809984",
45
+ "cudaCores": 16896,
46
+ "architecture": "Hopper",
47
+ "uuid": "GPU-af4135e3-88f2-e9ac-518d-502c75a85429"
48
+ },
49
+ {
50
+ "name": "NVIDIA H100 80GB HBM3",
51
+ "memoryTotal": "85520809984",
52
+ "cudaCores": 16896,
53
+ "architecture": "Hopper",
54
+ "uuid": "GPU-d7fdeeba-fe9b-ec03-d9f7-6724fe4266b5"
55
+ },
56
+ {
57
+ "name": "NVIDIA H100 80GB HBM3",
58
+ "memoryTotal": "85520809984",
59
+ "cudaCores": 16896,
60
+ "architecture": "Hopper",
61
+ "uuid": "GPU-ccc4f668-3882-5a8e-2c07-c5cd08f6f666"
62
+ },
63
+ {
64
+ "name": "NVIDIA H100 80GB HBM3",
65
+ "memoryTotal": "85520809984",
66
+ "cudaCores": 16896,
67
+ "architecture": "Hopper",
68
+ "uuid": "GPU-7b73c0cf-d3d5-e10c-7176-a43be1e41001"
69
+ },
70
+ {
71
+ "name": "NVIDIA H100 80GB HBM3",
72
+ "memoryTotal": "85520809984",
73
+ "cudaCores": 16896,
74
+ "architecture": "Hopper",
75
+ "uuid": "GPU-81b58d94-5d1f-8ec2-f9d2-fd56172ed177"
76
+ },
77
+ {
78
+ "name": "NVIDIA H100 80GB HBM3",
79
+ "memoryTotal": "85520809984",
80
+ "cudaCores": 16896,
81
+ "architecture": "Hopper",
82
+ "uuid": "GPU-03e8bc66-3b44-6794-49fd-5392fbdda6d1"
83
+ },
84
+ {
85
+ "name": "NVIDIA H100 80GB HBM3",
86
+ "memoryTotal": "85520809984",
87
+ "cudaCores": 16896,
88
+ "architecture": "Hopper",
89
+ "uuid": "GPU-b7cf0ec6-7c29-1179-dceb-09565da51890"
90
+ }
91
+ ],
92
+ "cudaVersion": "12.4",
93
+ "writerId": "xa4im9wkbwlcw1r2rhsulzxqq9xni8uv"
94
+ }
cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/files/wandb-summary.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"losses/entropy":0.6921915,"_step":792,"_timestamp":1.7624812191309254e+09,"losses/old_approx_kl":4.6293717e-06,"losses/explained_variance":-7.891655e-05,"_runtime":38,"charts/avg_reward":0.087274164,"charts/SPS":27228,"global_step":999424,"losses/policy_loss":-2.1699816e-06,"losses/approx_kl":7.246854e-09,"charts/min_reward":0,"_wandb":{"runtime":38},"losses/value_loss":0.04838482,"charts/max_reward":1,"losses/clipfrac":0,"charts/learning_rate":4.0983605e-06,"charts/avg_value":0.17467922}
cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/logs/debug.log ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2025-11-07 10:06:19,770 INFO MainThread:131343 [wandb_setup.py:_flush():81] Current SDK version is 0.22.3
2
+ 2025-11-07 10:06:19,770 INFO MainThread:131343 [wandb_setup.py:_flush():81] Configure stats pid to 131343
3
+ 2025-11-07 10:06:19,770 INFO MainThread:131343 [wandb_setup.py:_flush():81] Loading settings from /root/.config/wandb/settings
4
+ 2025-11-07 10:06:19,770 INFO MainThread:131343 [wandb_setup.py:_flush():81] Loading settings from /mnt/general/wanghy/RAGEN/cleanrl/cleanrl/wandb/settings
5
+ 2025-11-07 10:06:19,770 INFO MainThread:131343 [wandb_setup.py:_flush():81] Loading settings from environment variables
6
+ 2025-11-07 10:06:19,770 INFO MainThread:131343 [wandb_init.py:setup_run_log_directory():706] Logging user logs to /mnt/general/wanghy/RAGEN/cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/logs/debug.log
7
+ 2025-11-07 10:06:19,771 INFO MainThread:131343 [wandb_init.py:setup_run_log_directory():707] Logging internal logs to /mnt/general/wanghy/RAGEN/cleanrl/cleanrl/wandb/run-20251107_100619-gm3bobw8/logs/debug-internal.log
8
+ 2025-11-07 10:06:19,774 INFO MainThread:131343 [wandb_init.py:init():833] calling init triggers
9
+ 2025-11-07 10:06:19,774 INFO MainThread:131343 [wandb_init.py:init():838] wandb.init called with sweep_config: {}
10
+ config: {'exp_name': 'ppo_bandit', 'seed': 1, 'torch_deterministic': True, 'cuda': True, 'track': True, 'wandb_project_name': 'ragen-bandit', 'wandb_entity': None, 'capture_video': False, 'env_id': 'Bandit', 'total_timesteps': 1000000, 'learning_rate': 0.00025, 'num_envs': 32, 'num_steps': 512, 'anneal_lr': True, 'gamma': 0.99, 'gae_lambda': 0.95, 'num_minibatches': 4, 'update_epochs': 4, 'norm_adv': True, 'clip_coef': 0.2, 'clip_vloss': True, 'ent_coef': 0.01, 'vf_coef': 0.5, 'max_grad_norm': 0.5, 'target_kl': None, 'batch_size': 16384, 'minibatch_size': 4096, 'num_iterations': 61, '_wandb': {'code_path': 'code/cleanrl/ppo_bandit.py'}}
11
+ 2025-11-07 10:06:19,774 INFO MainThread:131343 [wandb_init.py:init():881] starting backend
12
+ 2025-11-07 10:06:19,980 INFO MainThread:131343 [wandb_init.py:init():884] sending inform_init request
13
+ 2025-11-07 10:06:19,991 INFO MainThread:131343 [wandb_init.py:init():892] backend started and connected
14
+ 2025-11-07 10:06:19,993 INFO MainThread:131343 [wandb_init.py:init():962] updated telemetry
15
+ 2025-11-07 10:06:20,030 INFO MainThread:131343 [wandb_init.py:init():986] communicating run to backend with 90.0 second timeout
16
+ 2025-11-07 10:06:20,800 INFO MainThread:131343 [wandb_init.py:init():1033] starting run threads in backend
17
+ 2025-11-07 10:06:20,946 INFO MainThread:131343 [wandb_run.py:_console_start():2506] atexit reg
18
+ 2025-11-07 10:06:20,946 INFO MainThread:131343 [wandb_run.py:_redirect():2354] redirect: wrap_raw
19
+ 2025-11-07 10:06:20,946 INFO MainThread:131343 [wandb_run.py:_redirect():2423] Wrapping output streams.
20
+ 2025-11-07 10:06:20,947 INFO MainThread:131343 [wandb_run.py:_redirect():2446] Redirects installed.
21
+ 2025-11-07 10:06:20,949 INFO MainThread:131343 [wandb_init.py:init():1073] run started, returning control to user process
22
+ 2025-11-07 10:06:20,949 INFO MainThread:131343 [wandb_run.py:_tensorboard_callback():1598] tensorboard callback: runs/Bandit__ppo_bandit__1__1762481172, True
23
+ 2025-11-07 10:06:59,151 INFO wandb-AsyncioManager-main:131343 [service_client.py:_forward_responses():80] Reached EOF.
24
+ 2025-11-07 10:06:59,152 INFO wandb-AsyncioManager-main:131343 [mailbox.py:close():137] Closing mailbox, abandoning 1 handles.
cleanrl/cleanrl/wandb/run-20251107_100911-8xuf7idy/files/output.log ADDED
@@ -0,0 +1,610 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [ 0.2%] Iter 1/610 | SPS: 17195 | Reward: 0.087 | Value: -0.018 | VLoss: 0.0488 | PLoss: -0.0002 | Ent: 0.6931
2
+ [ 0.3%] Iter 2/610 | SPS: 21007 | Reward: 0.084 | Value: 0.098 | VLoss: 0.0444 | PLoss: 0.0000 | Ent: 0.6929
3
+ [ 0.5%] Iter 3/610 | SPS: 22807 | Reward: 0.087 | Value: 0.131 | VLoss: 0.0472 | PLoss: -0.0000 | Ent: 0.6929
4
+ [ 0.7%] Iter 4/610 | SPS: 23807 | Reward: 0.087 | Value: 0.156 | VLoss: 0.0452 | PLoss: -0.0001 | Ent: 0.6927
5
+ [ 0.8%] Iter 5/610 | SPS: 24488 | Reward: 0.088 | Value: 0.170 | VLoss: 0.0457 | PLoss: -0.0001 | Ent: 0.6922
6
+ [ 1.0%] Iter 6/610 | SPS: 24959 | Reward: 0.086 | Value: 0.177 | VLoss: 0.0476 | PLoss: -0.0001 | Ent: 0.6914
7
+ [ 1.1%] Iter 7/610 | SPS: 25311 | Reward: 0.089 | Value: 0.173 | VLoss: 0.0484 | PLoss: -0.0001 | Ent: 0.6902
8
+ [ 1.3%] Iter 8/610 | SPS: 25594 | Reward: 0.089 | Value: 0.175 | VLoss: 0.0470 | PLoss: -0.0000 | Ent: 0.6896
9
+ [ 1.5%] Iter 9/610 | SPS: 25819 | Reward: 0.089 | Value: 0.175 | VLoss: 0.0479 | PLoss: 0.0001 | Ent: 0.6892
10
+ [ 1.6%] Iter 10/610 | SPS: 26001 | Reward: 0.083 | Value: 0.177 | VLoss: 0.0438 | PLoss: -0.0000 | Ent: 0.6896
11
+ [ 1.8%] Iter 11/610 | SPS: 26145 | Reward: 0.091 | Value: 0.165 | VLoss: 0.0487 | PLoss: 0.0000 | Ent: 0.6898
12
+ [ 2.0%] Iter 12/610 | SPS: 26270 | Reward: 0.085 | Value: 0.179 | VLoss: 0.0463 | PLoss: -0.0001 | Ent: 0.6905
13
+ [ 2.1%] Iter 13/610 | SPS: 26378 | Reward: 0.085 | Value: 0.169 | VLoss: 0.0469 | PLoss: -0.0005 | Ent: 0.6915
14
+ [ 2.3%] Iter 14/610 | SPS: 26469 | Reward: 0.086 | Value: 0.170 | VLoss: 0.0455 | PLoss: -0.0002 | Ent: 0.6925
15
+ [ 2.5%] Iter 15/610 | SPS: 26553 | Reward: 0.087 | Value: 0.170 | VLoss: 0.0464 | PLoss: 0.0001 | Ent: 0.6928
16
+ [ 2.6%] Iter 16/610 | SPS: 26625 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0481 | PLoss: 0.0000 | Ent: 0.6928
17
+ [ 2.8%] Iter 17/610 | SPS: 26556 | Reward: 0.087 | Value: 0.172 | VLoss: 0.0471 | PLoss: 0.0000 | Ent: 0.6929
18
+ [ 3.0%] Iter 18/610 | SPS: 26439 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0459 | PLoss: -0.0001 | Ent: 0.6930
19
+ [ 3.1%] Iter 19/610 | SPS: 26495 | Reward: 0.089 | Value: 0.170 | VLoss: 0.0486 | PLoss: -0.0000 | Ent: 0.6931
20
+ [ 3.3%] Iter 20/610 | SPS: 26543 | Reward: 0.088 | Value: 0.178 | VLoss: 0.0466 | PLoss: -0.0000 | Ent: 0.6931
21
+ [ 3.4%] Iter 21/610 | SPS: 26592 | Reward: 0.086 | Value: 0.175 | VLoss: 0.0453 | PLoss: 0.0002 | Ent: 0.6931
22
+ [ 3.6%] Iter 22/610 | SPS: 26631 | Reward: 0.091 | Value: 0.169 | VLoss: 0.0501 | PLoss: -0.0000 | Ent: 0.6931
23
+ [ 3.8%] Iter 23/610 | SPS: 26671 | Reward: 0.084 | Value: 0.183 | VLoss: 0.0430 | PLoss: -0.0001 | Ent: 0.6931
24
+ [ 3.9%] Iter 24/610 | SPS: 26715 | Reward: 0.084 | Value: 0.168 | VLoss: 0.0437 | PLoss: 0.0001 | Ent: 0.6930
25
+ [ 4.1%] Iter 25/610 | SPS: 26755 | Reward: 0.085 | Value: 0.164 | VLoss: 0.0453 | PLoss: -0.0001 | Ent: 0.6928
26
+ [ 4.3%] Iter 26/610 | SPS: 26791 | Reward: 0.087 | Value: 0.170 | VLoss: 0.0445 | PLoss: -0.0001 | Ent: 0.6927
27
+ [ 4.4%] Iter 27/610 | SPS: 26819 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0466 | PLoss: 0.0000 | Ent: 0.6926
28
+ [ 4.6%] Iter 28/610 | SPS: 26847 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0494 | PLoss: -0.0000 | Ent: 0.6922
29
+ [ 4.8%] Iter 29/610 | SPS: 26873 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0445 | PLoss: 0.0001 | Ent: 0.6920
30
+ [ 4.9%] Iter 30/610 | SPS: 26899 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0487 | PLoss: -0.0002 | Ent: 0.6924
31
+ [ 5.1%] Iter 31/610 | SPS: 26915 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0479 | PLoss: 0.0000 | Ent: 0.6927
32
+ [ 5.2%] Iter 32/610 | SPS: 26930 | Reward: 0.090 | Value: 0.175 | VLoss: 0.0491 | PLoss: -0.0000 | Ent: 0.6927
33
+ [ 5.4%] Iter 33/610 | SPS: 26947 | Reward: 0.084 | Value: 0.179 | VLoss: 0.0439 | PLoss: -0.0003 | Ent: 0.6924
34
+ [ 5.6%] Iter 34/610 | SPS: 26963 | Reward: 0.087 | Value: 0.168 | VLoss: 0.0451 | PLoss: -0.0000 | Ent: 0.6918
35
+ [ 5.7%] Iter 35/610 | SPS: 26886 | Reward: 0.087 | Value: 0.172 | VLoss: 0.0476 | PLoss: 0.0000 | Ent: 0.6915
36
+ [ 5.9%] Iter 36/610 | SPS: 26905 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0452 | PLoss: 0.0000 | Ent: 0.6913
37
+ [ 6.1%] Iter 37/610 | SPS: 26919 | Reward: 0.086 | Value: 0.173 | VLoss: 0.0449 | PLoss: -0.0001 | Ent: 0.6909
38
+ [ 6.2%] Iter 38/610 | SPS: 26934 | Reward: 0.088 | Value: 0.170 | VLoss: 0.0469 | PLoss: -0.0000 | Ent: 0.6902
39
+ [ 6.4%] Iter 39/610 | SPS: 26946 | Reward: 0.090 | Value: 0.174 | VLoss: 0.0499 | PLoss: 0.0001 | Ent: 0.6891
40
+ [ 6.6%] Iter 40/610 | SPS: 26961 | Reward: 0.086 | Value: 0.180 | VLoss: 0.0472 | PLoss: 0.0000 | Ent: 0.6897
41
+ [ 6.7%] Iter 41/610 | SPS: 26975 | Reward: 0.087 | Value: 0.172 | VLoss: 0.0449 | PLoss: 0.0003 | Ent: 0.6906
42
+ [ 6.9%] Iter 42/610 | SPS: 26993 | Reward: 0.088 | Value: 0.171 | VLoss: 0.0469 | PLoss: 0.0000 | Ent: 0.6905
43
+ [ 7.0%] Iter 43/610 | SPS: 27005 | Reward: 0.087 | Value: 0.176 | VLoss: 0.0461 | PLoss: -0.0001 | Ent: 0.6901
44
+ [ 7.2%] Iter 44/610 | SPS: 27020 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0480 | PLoss: -0.0002 | Ent: 0.6908
45
+ [ 7.4%] Iter 45/610 | SPS: 27033 | Reward: 0.087 | Value: 0.171 | VLoss: 0.0446 | PLoss: -0.0000 | Ent: 0.6916
46
+ [ 7.5%] Iter 46/610 | SPS: 27046 | Reward: 0.090 | Value: 0.174 | VLoss: 0.0492 | PLoss: -0.0000 | Ent: 0.6920
47
+ [ 7.7%] Iter 47/610 | SPS: 27056 | Reward: 0.085 | Value: 0.179 | VLoss: 0.0451 | PLoss: -0.0002 | Ent: 0.6928
48
+ [ 7.9%] Iter 48/610 | SPS: 27067 | Reward: 0.089 | Value: 0.171 | VLoss: 0.0509 | PLoss: 0.0001 | Ent: 0.6930
49
+ [ 8.0%] Iter 49/610 | SPS: 27076 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0453 | PLoss: -0.0000 | Ent: 0.6931
50
+ [ 8.2%] Iter 50/610 | SPS: 27085 | Reward: 0.085 | Value: 0.173 | VLoss: 0.0458 | PLoss: 0.0000 | Ent: 0.6931
51
+ [ 8.4%] Iter 51/610 | SPS: 27083 | Reward: 0.087 | Value: 0.168 | VLoss: 0.0477 | PLoss: 0.0000 | Ent: 0.6931
52
+ [ 8.5%] Iter 52/610 | SPS: 27078 | Reward: 0.090 | Value: 0.173 | VLoss: 0.0475 | PLoss: 0.0000 | Ent: 0.6931
53
+ [ 8.7%] Iter 53/610 | SPS: 27085 | Reward: 0.088 | Value: 0.179 | VLoss: 0.0454 | PLoss: -0.0001 | Ent: 0.6931
54
+ [ 8.9%] Iter 54/610 | SPS: 27092 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0480 | PLoss: -0.0000 | Ent: 0.6931
55
+ [ 9.0%] Iter 55/610 | SPS: 27098 | Reward: 0.087 | Value: 0.172 | VLoss: 0.0454 | PLoss: -0.0000 | Ent: 0.6931
56
+ [ 9.2%] Iter 56/610 | SPS: 27104 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0492 | PLoss: -0.0000 | Ent: 0.6931
57
+ [ 9.3%] Iter 57/610 | SPS: 27112 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0475 | PLoss: 0.0000 | Ent: 0.6931
58
+ [ 9.5%] Iter 58/610 | SPS: 27119 | Reward: 0.089 | Value: 0.173 | VLoss: 0.0471 | PLoss: -0.0000 | Ent: 0.6931
59
+ [ 9.7%] Iter 59/610 | SPS: 27123 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0466 | PLoss: -0.0000 | Ent: 0.6931
60
+ [ 9.8%] Iter 60/610 | SPS: 27129 | Reward: 0.090 | Value: 0.177 | VLoss: 0.0493 | PLoss: -0.0001 | Ent: 0.6931
61
+ [ 10.0%] Iter 61/610 | SPS: 27133 | Reward: 0.087 | Value: 0.177 | VLoss: 0.0478 | PLoss: -0.0000 | Ent: 0.6931
62
+ [ 10.2%] Iter 62/610 | SPS: 27139 | Reward: 0.086 | Value: 0.173 | VLoss: 0.0449 | PLoss: -0.0000 | Ent: 0.6931
63
+ [ 10.3%] Iter 63/610 | SPS: 27137 | Reward: 0.087 | Value: 0.170 | VLoss: 0.0477 | PLoss: -0.0000 | Ent: 0.6931
64
+ [ 10.5%] Iter 64/610 | SPS: 27141 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0492 | PLoss: -0.0000 | Ent: 0.6931
65
+ [ 10.7%] Iter 65/610 | SPS: 27146 | Reward: 0.086 | Value: 0.176 | VLoss: 0.0451 | PLoss: 0.0000 | Ent: 0.6931
66
+ [ 10.8%] Iter 66/610 | SPS: 27152 | Reward: 0.088 | Value: 0.168 | VLoss: 0.0471 | PLoss: -0.0001 | Ent: 0.6931
67
+ [ 11.0%] Iter 67/610 | SPS: 27156 | Reward: 0.083 | Value: 0.176 | VLoss: 0.0431 | PLoss: -0.0000 | Ent: 0.6931
68
+ [ 11.1%] Iter 68/610 | SPS: 27155 | Reward: 0.086 | Value: 0.167 | VLoss: 0.0471 | PLoss: -0.0000 | Ent: 0.6931
69
+ [ 11.3%] Iter 69/610 | SPS: 27155 | Reward: 0.088 | Value: 0.171 | VLoss: 0.0445 | PLoss: -0.0002 | Ent: 0.6931
70
+ [ 11.5%] Iter 70/610 | SPS: 27161 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0476 | PLoss: -0.0002 | Ent: 0.6931
71
+ [ 11.6%] Iter 71/610 | SPS: 27165 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0453 | PLoss: -0.0002 | Ent: 0.6929
72
+ [ 11.8%] Iter 72/610 | SPS: 27170 | Reward: 0.085 | Value: 0.176 | VLoss: 0.0446 | PLoss: -0.0001 | Ent: 0.6929
73
+ [ 12.0%] Iter 73/610 | SPS: 27173 | Reward: 0.086 | Value: 0.170 | VLoss: 0.0469 | PLoss: -0.0001 | Ent: 0.6930
74
+ [ 12.1%] Iter 74/610 | SPS: 27178 | Reward: 0.085 | Value: 0.172 | VLoss: 0.0463 | PLoss: -0.0001 | Ent: 0.6931
75
+ [ 12.3%] Iter 75/610 | SPS: 27183 | Reward: 0.088 | Value: 0.170 | VLoss: 0.0483 | PLoss: -0.0000 | Ent: 0.6931
76
+ [ 12.5%] Iter 76/610 | SPS: 27191 | Reward: 0.086 | Value: 0.173 | VLoss: 0.0448 | PLoss: -0.0001 | Ent: 0.6931
77
+ [ 12.6%] Iter 77/610 | SPS: 27197 | Reward: 0.090 | Value: 0.172 | VLoss: 0.0486 | PLoss: -0.0000 | Ent: 0.6931
78
+ [ 12.8%] Iter 78/610 | SPS: 27204 | Reward: 0.088 | Value: 0.180 | VLoss: 0.0472 | PLoss: -0.0000 | Ent: 0.6931
79
+ [ 13.0%] Iter 79/610 | SPS: 27210 | Reward: 0.090 | Value: 0.175 | VLoss: 0.0467 | PLoss: -0.0001 | Ent: 0.6930
80
+ [ 13.1%] Iter 80/610 | SPS: 27217 | Reward: 0.086 | Value: 0.181 | VLoss: 0.0463 | PLoss: -0.0002 | Ent: 0.6928
81
+ [ 13.3%] Iter 81/610 | SPS: 27222 | Reward: 0.088 | Value: 0.172 | VLoss: 0.0468 | PLoss: 0.0001 | Ent: 0.6926
82
+ [ 13.4%] Iter 82/610 | SPS: 27228 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0484 | PLoss: -0.0000 | Ent: 0.6924
83
+ [ 13.6%] Iter 83/610 | SPS: 27236 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0463 | PLoss: -0.0000 | Ent: 0.6920
84
+ [ 13.8%] Iter 84/610 | SPS: 27242 | Reward: 0.085 | Value: 0.175 | VLoss: 0.0431 | PLoss: -0.0000 | Ent: 0.6920
85
+ [ 13.9%] Iter 85/610 | SPS: 27245 | Reward: 0.090 | Value: 0.170 | VLoss: 0.0486 | PLoss: -0.0000 | Ent: 0.6922
86
+ [ 14.1%] Iter 86/610 | SPS: 27247 | Reward: 0.087 | Value: 0.180 | VLoss: 0.0465 | PLoss: -0.0001 | Ent: 0.6926
87
+ [ 14.3%] Iter 87/610 | SPS: 27252 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0454 | PLoss: -0.0000 | Ent: 0.6927
88
+ [ 14.4%] Iter 88/610 | SPS: 27258 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0461 | PLoss: -0.0000 | Ent: 0.6928
89
+ [ 14.6%] Iter 89/610 | SPS: 27261 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0473 | PLoss: 0.0000 | Ent: 0.6927
90
+ [ 14.8%] Iter 90/610 | SPS: 27266 | Reward: 0.090 | Value: 0.176 | VLoss: 0.0468 | PLoss: 0.0000 | Ent: 0.6927
91
+ [ 14.9%] Iter 91/610 | SPS: 27270 | Reward: 0.090 | Value: 0.178 | VLoss: 0.0486 | PLoss: -0.0001 | Ent: 0.6923
92
+ [ 15.1%] Iter 92/610 | SPS: 27276 | Reward: 0.084 | Value: 0.179 | VLoss: 0.0441 | PLoss: -0.0000 | Ent: 0.6918
93
+ [ 15.2%] Iter 93/610 | SPS: 27281 | Reward: 0.086 | Value: 0.166 | VLoss: 0.0457 | PLoss: -0.0000 | Ent: 0.6918
94
+ [ 15.4%] Iter 94/610 | SPS: 27286 | Reward: 0.089 | Value: 0.173 | VLoss: 0.0445 | PLoss: -0.0001 | Ent: 0.6920
95
+ [ 15.6%] Iter 95/610 | SPS: 27292 | Reward: 0.089 | Value: 0.178 | VLoss: 0.0495 | PLoss: 0.0000 | Ent: 0.6923
96
+ [ 15.7%] Iter 96/610 | SPS: 27297 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0465 | PLoss: -0.0001 | Ent: 0.6925
97
+ [ 15.9%] Iter 97/610 | SPS: 27303 | Reward: 0.087 | Value: 0.177 | VLoss: 0.0471 | PLoss: -0.0000 | Ent: 0.6926
98
+ [ 16.1%] Iter 98/610 | SPS: 27306 | Reward: 0.089 | Value: 0.174 | VLoss: 0.0481 | PLoss: -0.0000 | Ent: 0.6926
99
+ [ 16.2%] Iter 99/610 | SPS: 27309 | Reward: 0.090 | Value: 0.175 | VLoss: 0.0487 | PLoss: -0.0000 | Ent: 0.6926
100
+ [ 16.4%] Iter 100/610 | SPS: 27314 | Reward: 0.088 | Value: 0.179 | VLoss: 0.0487 | PLoss: -0.0000 | Ent: 0.6927
101
+ [ 16.6%] Iter 101/610 | SPS: 27317 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0450 | PLoss: -0.0002 | Ent: 0.6929
102
+ [ 16.7%] Iter 102/610 | SPS: 27315 | Reward: 0.094 | Value: 0.175 | VLoss: 0.0516 | PLoss: 0.0000 | Ent: 0.6931
103
+ [ 16.9%] Iter 103/610 | SPS: 27317 | Reward: 0.087 | Value: 0.186 | VLoss: 0.0465 | PLoss: -0.0000 | Ent: 0.6931
104
+ [ 17.0%] Iter 104/610 | SPS: 27320 | Reward: 0.087 | Value: 0.171 | VLoss: 0.0471 | PLoss: 0.0000 | Ent: 0.6931
105
+ [ 17.2%] Iter 105/610 | SPS: 27324 | Reward: 0.086 | Value: 0.173 | VLoss: 0.0449 | PLoss: 0.0000 | Ent: 0.6931
106
+ [ 17.4%] Iter 106/610 | SPS: 27328 | Reward: 0.088 | Value: 0.172 | VLoss: 0.0485 | PLoss: -0.0001 | Ent: 0.6931
107
+ [ 17.5%] Iter 107/610 | SPS: 27331 | Reward: 0.091 | Value: 0.174 | VLoss: 0.0480 | PLoss: -0.0003 | Ent: 0.6931
108
+ [ 17.7%] Iter 108/610 | SPS: 27336 | Reward: 0.089 | Value: 0.180 | VLoss: 0.0468 | PLoss: 0.0000 | Ent: 0.6930
109
+ [ 17.9%] Iter 109/610 | SPS: 27340 | Reward: 0.086 | Value: 0.176 | VLoss: 0.0443 | PLoss: -0.0000 | Ent: 0.6930
110
+ [ 18.0%] Iter 110/610 | SPS: 27343 | Reward: 0.088 | Value: 0.172 | VLoss: 0.0475 | PLoss: -0.0000 | Ent: 0.6929
111
+ [ 18.2%] Iter 111/610 | SPS: 27346 | Reward: 0.090 | Value: 0.174 | VLoss: 0.0489 | PLoss: -0.0000 | Ent: 0.6929
112
+ [ 18.4%] Iter 112/610 | SPS: 27349 | Reward: 0.086 | Value: 0.181 | VLoss: 0.0465 | PLoss: -0.0000 | Ent: 0.6930
113
+ [ 18.5%] Iter 113/610 | SPS: 27353 | Reward: 0.085 | Value: 0.171 | VLoss: 0.0440 | PLoss: -0.0000 | Ent: 0.6930
114
+ [ 18.7%] Iter 114/610 | SPS: 27356 | Reward: 0.090 | Value: 0.169 | VLoss: 0.0482 | PLoss: -0.0000 | Ent: 0.6930
115
+ [ 18.9%] Iter 115/610 | SPS: 27359 | Reward: 0.087 | Value: 0.179 | VLoss: 0.0456 | PLoss: 0.0000 | Ent: 0.6931
116
+ [ 19.0%] Iter 116/610 | SPS: 27362 | Reward: 0.085 | Value: 0.172 | VLoss: 0.0442 | PLoss: -0.0001 | Ent: 0.6931
117
+ [ 19.2%] Iter 117/610 | SPS: 27364 | Reward: 0.088 | Value: 0.170 | VLoss: 0.0453 | PLoss: -0.0000 | Ent: 0.6931
118
+ [ 19.3%] Iter 118/610 | SPS: 27368 | Reward: 0.084 | Value: 0.177 | VLoss: 0.0441 | PLoss: -0.0000 | Ent: 0.6931
119
+ [ 19.5%] Iter 119/610 | SPS: 27364 | Reward: 0.088 | Value: 0.168 | VLoss: 0.0457 | PLoss: -0.0000 | Ent: 0.6931
120
+ [ 19.7%] Iter 120/610 | SPS: 27369 | Reward: 0.085 | Value: 0.175 | VLoss: 0.0444 | PLoss: -0.0001 | Ent: 0.6930
121
+ [ 19.8%] Iter 121/610 | SPS: 27371 | Reward: 0.087 | Value: 0.169 | VLoss: 0.0488 | PLoss: 0.0000 | Ent: 0.6930
122
+ [ 20.0%] Iter 122/610 | SPS: 27375 | Reward: 0.086 | Value: 0.172 | VLoss: 0.0443 | PLoss: -0.0000 | Ent: 0.6930
123
+ [ 20.2%] Iter 123/610 | SPS: 27377 | Reward: 0.089 | Value: 0.169 | VLoss: 0.0477 | PLoss: 0.0000 | Ent: 0.6931
124
+ [ 20.3%] Iter 124/610 | SPS: 27379 | Reward: 0.088 | Value: 0.177 | VLoss: 0.0501 | PLoss: 0.0000 | Ent: 0.6931
125
+ [ 20.5%] Iter 125/610 | SPS: 27382 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0472 | PLoss: -0.0000 | Ent: 0.6931
126
+ [ 20.7%] Iter 126/610 | SPS: 27386 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0463 | PLoss: -0.0000 | Ent: 0.6931
127
+ [ 20.8%] Iter 127/610 | SPS: 27389 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0462 | PLoss: 0.0000 | Ent: 0.6931
128
+ [ 21.0%] Iter 128/610 | SPS: 27391 | Reward: 0.089 | Value: 0.178 | VLoss: 0.0483 | PLoss: -0.0000 | Ent: 0.6930
129
+ [ 21.1%] Iter 129/610 | SPS: 27393 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0476 | PLoss: 0.0000 | Ent: 0.6930
130
+ [ 21.3%] Iter 130/610 | SPS: 27396 | Reward: 0.089 | Value: 0.179 | VLoss: 0.0463 | PLoss: -0.0001 | Ent: 0.6929
131
+ [ 21.5%] Iter 131/610 | SPS: 27398 | Reward: 0.088 | Value: 0.178 | VLoss: 0.0441 | PLoss: -0.0001 | Ent: 0.6930
132
+ [ 21.6%] Iter 132/610 | SPS: 27400 | Reward: 0.090 | Value: 0.178 | VLoss: 0.0485 | PLoss: 0.0000 | Ent: 0.6931
133
+ [ 21.8%] Iter 133/610 | SPS: 27404 | Reward: 0.085 | Value: 0.179 | VLoss: 0.0443 | PLoss: -0.0001 | Ent: 0.6930
134
+ [ 22.0%] Iter 134/610 | SPS: 27405 | Reward: 0.090 | Value: 0.168 | VLoss: 0.0504 | PLoss: 0.0001 | Ent: 0.6929
135
+ [ 22.1%] Iter 135/610 | SPS: 27406 | Reward: 0.088 | Value: 0.182 | VLoss: 0.0452 | PLoss: -0.0000 | Ent: 0.6929
136
+ [ 22.3%] Iter 136/610 | SPS: 27404 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0455 | PLoss: -0.0000 | Ent: 0.6929
137
+ [ 22.5%] Iter 137/610 | SPS: 27406 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0452 | PLoss: 0.0001 | Ent: 0.6930
138
+ [ 22.6%] Iter 138/610 | SPS: 27408 | Reward: 0.088 | Value: 0.172 | VLoss: 0.0459 | PLoss: -0.0000 | Ent: 0.6930
139
+ [ 22.8%] Iter 139/610 | SPS: 27410 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0455 | PLoss: -0.0000 | Ent: 0.6931
140
+ [ 23.0%] Iter 140/610 | SPS: 27412 | Reward: 0.086 | Value: 0.176 | VLoss: 0.0461 | PLoss: -0.0000 | Ent: 0.6931
141
+ [ 23.1%] Iter 141/610 | SPS: 27413 | Reward: 0.090 | Value: 0.171 | VLoss: 0.0488 | PLoss: -0.0000 | Ent: 0.6931
142
+ [ 23.3%] Iter 142/610 | SPS: 27414 | Reward: 0.092 | Value: 0.177 | VLoss: 0.0512 | PLoss: 0.0000 | Ent: 0.6931
143
+ [ 23.4%] Iter 143/610 | SPS: 27416 | Reward: 0.086 | Value: 0.186 | VLoss: 0.0441 | PLoss: -0.0000 | Ent: 0.6931
144
+ [ 23.6%] Iter 144/610 | SPS: 27418 | Reward: 0.086 | Value: 0.169 | VLoss: 0.0454 | PLoss: -0.0000 | Ent: 0.6931
145
+ [ 23.8%] Iter 145/610 | SPS: 27419 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0469 | PLoss: -0.0000 | Ent: 0.6931
146
+ [ 23.9%] Iter 146/610 | SPS: 27421 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0483 | PLoss: -0.0000 | Ent: 0.6931
147
+ [ 24.1%] Iter 147/610 | SPS: 27423 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0499 | PLoss: -0.0002 | Ent: 0.6931
148
+ [ 24.3%] Iter 148/610 | SPS: 27424 | Reward: 0.086 | Value: 0.178 | VLoss: 0.0446 | PLoss: -0.0001 | Ent: 0.6929
149
+ [ 24.4%] Iter 149/610 | SPS: 27423 | Reward: 0.086 | Value: 0.172 | VLoss: 0.0478 | PLoss: 0.0001 | Ent: 0.6928
150
+ [ 24.6%] Iter 150/610 | SPS: 27426 | Reward: 0.083 | Value: 0.170 | VLoss: 0.0430 | PLoss: -0.0001 | Ent: 0.6929
151
+ [ 24.8%] Iter 151/610 | SPS: 27428 | Reward: 0.087 | Value: 0.165 | VLoss: 0.0460 | PLoss: 0.0001 | Ent: 0.6930
152
+ [ 24.9%] Iter 152/610 | SPS: 27428 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0481 | PLoss: 0.0000 | Ent: 0.6930
153
+ [ 25.1%] Iter 153/610 | SPS: 27426 | Reward: 0.092 | Value: 0.177 | VLoss: 0.0474 | PLoss: -0.0000 | Ent: 0.6929
154
+ [ 25.2%] Iter 154/610 | SPS: 27427 | Reward: 0.089 | Value: 0.181 | VLoss: 0.0484 | PLoss: 0.0001 | Ent: 0.6929
155
+ [ 25.4%] Iter 155/610 | SPS: 27429 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0477 | PLoss: -0.0001 | Ent: 0.6929
156
+ [ 25.6%] Iter 156/610 | SPS: 27431 | Reward: 0.086 | Value: 0.176 | VLoss: 0.0452 | PLoss: -0.0000 | Ent: 0.6929
157
+ [ 25.7%] Iter 157/610 | SPS: 27431 | Reward: 0.090 | Value: 0.172 | VLoss: 0.0484 | PLoss: -0.0001 | Ent: 0.6930
158
+ [ 25.9%] Iter 158/610 | SPS: 27433 | Reward: 0.087 | Value: 0.181 | VLoss: 0.0469 | PLoss: 0.0001 | Ent: 0.6930
159
+ [ 26.1%] Iter 159/610 | SPS: 27435 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0459 | PLoss: -0.0000 | Ent: 0.6930
160
+ [ 26.2%] Iter 160/610 | SPS: 27437 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0485 | PLoss: -0.0000 | Ent: 0.6929
161
+ [ 26.4%] Iter 161/610 | SPS: 27439 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0478 | PLoss: 0.0000 | Ent: 0.6930
162
+ [ 26.6%] Iter 162/610 | SPS: 27440 | Reward: 0.089 | Value: 0.173 | VLoss: 0.0461 | PLoss: 0.0000 | Ent: 0.6930
163
+ [ 26.7%] Iter 163/610 | SPS: 27442 | Reward: 0.089 | Value: 0.178 | VLoss: 0.0462 | PLoss: -0.0001 | Ent: 0.6930
164
+ [ 26.9%] Iter 164/610 | SPS: 27445 | Reward: 0.085 | Value: 0.176 | VLoss: 0.0430 | PLoss: 0.0000 | Ent: 0.6930
165
+ [ 27.0%] Iter 165/610 | SPS: 27446 | Reward: 0.088 | Value: 0.171 | VLoss: 0.0490 | PLoss: -0.0000 | Ent: 0.6930
166
+ [ 27.2%] Iter 166/610 | SPS: 27448 | Reward: 0.087 | Value: 0.176 | VLoss: 0.0474 | PLoss: 0.0000 | Ent: 0.6930
167
+ [ 27.4%] Iter 167/610 | SPS: 27450 | Reward: 0.088 | Value: 0.172 | VLoss: 0.0473 | PLoss: -0.0001 | Ent: 0.6931
168
+ [ 27.5%] Iter 168/610 | SPS: 27451 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0451 | PLoss: -0.0000 | Ent: 0.6931
169
+ [ 27.7%] Iter 169/610 | SPS: 27450 | Reward: 0.089 | Value: 0.173 | VLoss: 0.0475 | PLoss: 0.0000 | Ent: 0.6930
170
+ [ 27.9%] Iter 170/610 | SPS: 27448 | Reward: 0.085 | Value: 0.177 | VLoss: 0.0462 | PLoss: 0.0000 | Ent: 0.6931
171
+ [ 28.0%] Iter 171/610 | SPS: 27450 | Reward: 0.086 | Value: 0.169 | VLoss: 0.0464 | PLoss: 0.0000 | Ent: 0.6931
172
+ [ 28.2%] Iter 172/610 | SPS: 27452 | Reward: 0.086 | Value: 0.171 | VLoss: 0.0445 | PLoss: 0.0000 | Ent: 0.6931
173
+ [ 28.4%] Iter 173/610 | SPS: 27453 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0467 | PLoss: -0.0001 | Ent: 0.6931
174
+ [ 28.5%] Iter 174/610 | SPS: 27453 | Reward: 0.086 | Value: 0.171 | VLoss: 0.0459 | PLoss: -0.0000 | Ent: 0.6930
175
+ [ 28.7%] Iter 175/610 | SPS: 27454 | Reward: 0.089 | Value: 0.174 | VLoss: 0.0474 | PLoss: 0.0001 | Ent: 0.6931
176
+ [ 28.9%] Iter 176/610 | SPS: 27456 | Reward: 0.088 | Value: 0.177 | VLoss: 0.0466 | PLoss: -0.0000 | Ent: 0.6931
177
+ [ 29.0%] Iter 177/610 | SPS: 27458 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0434 | PLoss: 0.0001 | Ent: 0.6931
178
+ [ 29.2%] Iter 178/610 | SPS: 27459 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0453 | PLoss: 0.0001 | Ent: 0.6930
179
+ [ 29.3%] Iter 179/610 | SPS: 27461 | Reward: 0.086 | Value: 0.175 | VLoss: 0.0478 | PLoss: -0.0000 | Ent: 0.6930
180
+ [ 29.5%] Iter 180/610 | SPS: 27462 | Reward: 0.088 | Value: 0.169 | VLoss: 0.0457 | PLoss: -0.0000 | Ent: 0.6930
181
+ [ 29.7%] Iter 181/610 | SPS: 27464 | Reward: 0.089 | Value: 0.174 | VLoss: 0.0468 | PLoss: -0.0000 | Ent: 0.6930
182
+ [ 29.8%] Iter 182/610 | SPS: 27466 | Reward: 0.085 | Value: 0.178 | VLoss: 0.0462 | PLoss: -0.0000 | Ent: 0.6930
183
+ [ 30.0%] Iter 183/610 | SPS: 27336 | Reward: 0.087 | Value: 0.169 | VLoss: 0.0477 | PLoss: -0.0001 | Ent: 0.6930
184
+ [ 30.2%] Iter 184/610 | SPS: 27338 | Reward: 0.087 | Value: 0.172 | VLoss: 0.0475 | PLoss: -0.0001 | Ent: 0.6929
185
+ [ 30.3%] Iter 185/610 | SPS: 27338 | Reward: 0.084 | Value: 0.172 | VLoss: 0.0448 | PLoss: -0.0000 | Ent: 0.6929
186
+ [ 30.5%] Iter 186/610 | SPS: 27234 | Reward: 0.086 | Value: 0.167 | VLoss: 0.0464 | PLoss: 0.0000 | Ent: 0.6929
187
+ [ 30.7%] Iter 187/610 | SPS: 27237 | Reward: 0.088 | Value: 0.171 | VLoss: 0.0465 | PLoss: -0.0000 | Ent: 0.6930
188
+ [ 30.8%] Iter 188/610 | SPS: 27240 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0458 | PLoss: 0.0000 | Ent: 0.6930
189
+ [ 31.0%] Iter 189/610 | SPS: 27241 | Reward: 0.090 | Value: 0.175 | VLoss: 0.0486 | PLoss: -0.0001 | Ent: 0.6931
190
+ [ 31.1%] Iter 190/610 | SPS: 27244 | Reward: 0.087 | Value: 0.177 | VLoss: 0.0460 | PLoss: 0.0000 | Ent: 0.6931
191
+ [ 31.3%] Iter 191/610 | SPS: 27247 | Reward: 0.089 | Value: 0.173 | VLoss: 0.0476 | PLoss: -0.0000 | Ent: 0.6930
192
+ [ 31.5%] Iter 192/610 | SPS: 27250 | Reward: 0.087 | Value: 0.178 | VLoss: 0.0455 | PLoss: 0.0000 | Ent: 0.6929
193
+ [ 31.6%] Iter 193/610 | SPS: 27253 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0464 | PLoss: -0.0000 | Ent: 0.6928
194
+ [ 31.8%] Iter 194/610 | SPS: 27256 | Reward: 0.090 | Value: 0.179 | VLoss: 0.0472 | PLoss: -0.0000 | Ent: 0.6929
195
+ [ 32.0%] Iter 195/610 | SPS: 27259 | Reward: 0.084 | Value: 0.177 | VLoss: 0.0425 | PLoss: -0.0001 | Ent: 0.6929
196
+ [ 32.1%] Iter 196/610 | SPS: 27263 | Reward: 0.088 | Value: 0.168 | VLoss: 0.0469 | PLoss: -0.0001 | Ent: 0.6929
197
+ [ 32.3%] Iter 197/610 | SPS: 27266 | Reward: 0.089 | Value: 0.175 | VLoss: 0.0484 | PLoss: -0.0000 | Ent: 0.6928
198
+ [ 32.5%] Iter 198/610 | SPS: 27268 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0472 | PLoss: -0.0000 | Ent: 0.6929
199
+ [ 32.6%] Iter 199/610 | SPS: 27270 | Reward: 0.088 | Value: 0.177 | VLoss: 0.0473 | PLoss: -0.0001 | Ent: 0.6929
200
+ [ 32.8%] Iter 200/610 | SPS: 27273 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0462 | PLoss: 0.0000 | Ent: 0.6929
201
+ [ 33.0%] Iter 201/610 | SPS: 27274 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0484 | PLoss: -0.0000 | Ent: 0.6929
202
+ [ 33.1%] Iter 202/610 | SPS: 27273 | Reward: 0.089 | Value: 0.174 | VLoss: 0.0476 | PLoss: 0.0000 | Ent: 0.6929
203
+ [ 33.3%] Iter 203/610 | SPS: 27275 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0463 | PLoss: 0.0000 | Ent: 0.6929
204
+ [ 33.4%] Iter 204/610 | SPS: 27277 | Reward: 0.086 | Value: 0.180 | VLoss: 0.0451 | PLoss: 0.0001 | Ent: 0.6929
205
+ [ 33.6%] Iter 205/610 | SPS: 27279 | Reward: 0.091 | Value: 0.170 | VLoss: 0.0488 | PLoss: -0.0000 | Ent: 0.6928
206
+ [ 33.8%] Iter 206/610 | SPS: 27282 | Reward: 0.087 | Value: 0.182 | VLoss: 0.0452 | PLoss: -0.0000 | Ent: 0.6930
207
+ [ 33.9%] Iter 207/610 | SPS: 27284 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0473 | PLoss: -0.0000 | Ent: 0.6931
208
+ [ 34.1%] Iter 208/610 | SPS: 27287 | Reward: 0.086 | Value: 0.175 | VLoss: 0.0469 | PLoss: -0.0000 | Ent: 0.6931
209
+ [ 34.3%] Iter 209/610 | SPS: 27290 | Reward: 0.088 | Value: 0.169 | VLoss: 0.0493 | PLoss: -0.0000 | Ent: 0.6931
210
+ [ 34.4%] Iter 210/610 | SPS: 27293 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0470 | PLoss: -0.0001 | Ent: 0.6931
211
+ [ 34.6%] Iter 211/610 | SPS: 27294 | Reward: 0.086 | Value: 0.171 | VLoss: 0.0468 | PLoss: -0.0000 | Ent: 0.6930
212
+ [ 34.8%] Iter 212/610 | SPS: 27296 | Reward: 0.090 | Value: 0.169 | VLoss: 0.0479 | PLoss: 0.0001 | Ent: 0.6929
213
+ [ 34.9%] Iter 213/610 | SPS: 27298 | Reward: 0.089 | Value: 0.179 | VLoss: 0.0500 | PLoss: -0.0000 | Ent: 0.6928
214
+ [ 35.1%] Iter 214/610 | SPS: 27300 | Reward: 0.086 | Value: 0.177 | VLoss: 0.0461 | PLoss: 0.0000 | Ent: 0.6928
215
+ [ 35.2%] Iter 215/610 | SPS: 27301 | Reward: 0.089 | Value: 0.174 | VLoss: 0.0461 | PLoss: 0.0000 | Ent: 0.6927
216
+ [ 35.4%] Iter 216/610 | SPS: 27303 | Reward: 0.085 | Value: 0.179 | VLoss: 0.0450 | PLoss: 0.0000 | Ent: 0.6926
217
+ [ 35.6%] Iter 217/610 | SPS: 27306 | Reward: 0.087 | Value: 0.170 | VLoss: 0.0484 | PLoss: -0.0001 | Ent: 0.6927
218
+ [ 35.7%] Iter 218/610 | SPS: 27307 | Reward: 0.089 | Value: 0.175 | VLoss: 0.0492 | PLoss: -0.0003 | Ent: 0.6930
219
+ [ 35.9%] Iter 219/610 | SPS: 27306 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0489 | PLoss: 0.0000 | Ent: 0.6931
220
+ [ 36.1%] Iter 220/610 | SPS: 27309 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0424 | PLoss: 0.0000 | Ent: 0.6931
221
+ [ 36.2%] Iter 221/610 | SPS: 27310 | Reward: 0.090 | Value: 0.178 | VLoss: 0.0476 | PLoss: -0.0001 | Ent: 0.6931
222
+ [ 36.4%] Iter 222/610 | SPS: 27313 | Reward: 0.090 | Value: 0.178 | VLoss: 0.0469 | PLoss: 0.0000 | Ent: 0.6931
223
+ [ 36.6%] Iter 223/610 | SPS: 27315 | Reward: 0.088 | Value: 0.180 | VLoss: 0.0451 | PLoss: 0.0000 | Ent: 0.6931
224
+ [ 36.7%] Iter 224/610 | SPS: 27315 | Reward: 0.089 | Value: 0.177 | VLoss: 0.0485 | PLoss: 0.0000 | Ent: 0.6931
225
+ [ 36.9%] Iter 225/610 | SPS: 27317 | Reward: 0.094 | Value: 0.176 | VLoss: 0.0512 | PLoss: 0.0000 | Ent: 0.6931
226
+ [ 37.0%] Iter 226/610 | SPS: 27318 | Reward: 0.087 | Value: 0.186 | VLoss: 0.0456 | PLoss: -0.0001 | Ent: 0.6931
227
+ [ 37.2%] Iter 227/610 | SPS: 27319 | Reward: 0.089 | Value: 0.170 | VLoss: 0.0493 | PLoss: -0.0001 | Ent: 0.6931
228
+ [ 37.4%] Iter 228/610 | SPS: 27316 | Reward: 0.087 | Value: 0.176 | VLoss: 0.0461 | PLoss: 0.0000 | Ent: 0.6931
229
+ [ 37.5%] Iter 229/610 | SPS: 27317 | Reward: 0.086 | Value: 0.173 | VLoss: 0.0446 | PLoss: -0.0001 | Ent: 0.6931
230
+ [ 37.7%] Iter 230/610 | SPS: 27318 | Reward: 0.087 | Value: 0.169 | VLoss: 0.0482 | PLoss: 0.0001 | Ent: 0.6931
231
+ [ 37.9%] Iter 231/610 | SPS: 27319 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0469 | PLoss: -0.0001 | Ent: 0.6931
232
+ [ 38.0%] Iter 232/610 | SPS: 27320 | Reward: 0.086 | Value: 0.170 | VLoss: 0.0463 | PLoss: -0.0000 | Ent: 0.6931
233
+ [ 38.2%] Iter 233/610 | SPS: 27321 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0449 | PLoss: -0.0000 | Ent: 0.6931
234
+ [ 38.4%] Iter 234/610 | SPS: 27323 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0442 | PLoss: 0.0000 | Ent: 0.6930
235
+ [ 38.5%] Iter 235/610 | SPS: 27322 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0471 | PLoss: 0.0000 | Ent: 0.6930
236
+ [ 38.7%] Iter 236/610 | SPS: 27321 | Reward: 0.089 | Value: 0.177 | VLoss: 0.0476 | PLoss: -0.0001 | Ent: 0.6930
237
+ [ 38.9%] Iter 237/610 | SPS: 27322 | Reward: 0.090 | Value: 0.175 | VLoss: 0.0485 | PLoss: 0.0000 | Ent: 0.6928
238
+ [ 39.0%] Iter 238/610 | SPS: 27324 | Reward: 0.084 | Value: 0.178 | VLoss: 0.0452 | PLoss: -0.0002 | Ent: 0.6926
239
+ [ 39.2%] Iter 239/610 | SPS: 27326 | Reward: 0.086 | Value: 0.167 | VLoss: 0.0442 | PLoss: -0.0001 | Ent: 0.6921
240
+ [ 39.3%] Iter 240/610 | SPS: 27327 | Reward: 0.089 | Value: 0.172 | VLoss: 0.0497 | PLoss: -0.0001 | Ent: 0.6918
241
+ [ 39.5%] Iter 241/610 | SPS: 27329 | Reward: 0.086 | Value: 0.178 | VLoss: 0.0472 | PLoss: -0.0002 | Ent: 0.6911
242
+ [ 39.7%] Iter 242/610 | SPS: 27330 | Reward: 0.091 | Value: 0.173 | VLoss: 0.0487 | PLoss: 0.0000 | Ent: 0.6909
243
+ [ 39.8%] Iter 243/610 | SPS: 27332 | Reward: 0.090 | Value: 0.179 | VLoss: 0.0489 | PLoss: -0.0001 | Ent: 0.6904
244
+ [ 40.0%] Iter 244/610 | SPS: 27333 | Reward: 0.089 | Value: 0.180 | VLoss: 0.0484 | PLoss: -0.0004 | Ent: 0.6888
245
+ [ 40.2%] Iter 245/610 | SPS: 27335 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0493 | PLoss: -0.0009 | Ent: 0.6862
246
+ [ 40.3%] Iter 246/610 | SPS: 27337 | Reward: 0.084 | Value: 0.177 | VLoss: 0.0463 | PLoss: -0.0001 | Ent: 0.6848
247
+ [ 40.5%] Iter 247/610 | SPS: 27339 | Reward: 0.086 | Value: 0.167 | VLoss: 0.0457 | PLoss: -0.0001 | Ent: 0.6842
248
+ [ 40.7%] Iter 248/610 | SPS: 27340 | Reward: 0.089 | Value: 0.170 | VLoss: 0.0502 | PLoss: -0.0001 | Ent: 0.6841
249
+ [ 40.8%] Iter 249/610 | SPS: 27341 | Reward: 0.088 | Value: 0.178 | VLoss: 0.0454 | PLoss: -0.0001 | Ent: 0.6848
250
+ [ 41.0%] Iter 250/610 | SPS: 27342 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0466 | PLoss: -0.0002 | Ent: 0.6832
251
+ [ 41.1%] Iter 251/610 | SPS: 27342 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0467 | PLoss: -0.0002 | Ent: 0.6818
252
+ [ 41.3%] Iter 252/610 | SPS: 27340 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0470 | PLoss: 0.0000 | Ent: 0.6823
253
+ [ 41.5%] Iter 253/610 | SPS: 27338 | Reward: 0.091 | Value: 0.176 | VLoss: 0.0499 | PLoss: -0.0001 | Ent: 0.6833
254
+ [ 41.6%] Iter 254/610 | SPS: 27339 | Reward: 0.087 | Value: 0.181 | VLoss: 0.0480 | PLoss: -0.0001 | Ent: 0.6834
255
+ [ 41.8%] Iter 255/610 | SPS: 27305 | Reward: 0.091 | Value: 0.171 | VLoss: 0.0483 | PLoss: -0.0005 | Ent: 0.6821
256
+ [ 42.0%] Iter 256/610 | SPS: 27306 | Reward: 0.086 | Value: 0.182 | VLoss: 0.0462 | PLoss: -0.0003 | Ent: 0.6818
257
+ [ 42.1%] Iter 257/610 | SPS: 27306 | Reward: 0.089 | Value: 0.171 | VLoss: 0.0478 | PLoss: 0.0003 | Ent: 0.6837
258
+ [ 42.3%] Iter 258/610 | SPS: 27307 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0489 | PLoss: -0.0001 | Ent: 0.6854
259
+ [ 42.5%] Iter 259/610 | SPS: 27307 | Reward: 0.086 | Value: 0.171 | VLoss: 0.0454 | PLoss: 0.0000 | Ent: 0.6850
260
+ [ 42.6%] Iter 260/610 | SPS: 27308 | Reward: 0.090 | Value: 0.170 | VLoss: 0.0463 | PLoss: 0.0000 | Ent: 0.6850
261
+ [ 42.8%] Iter 261/610 | SPS: 27309 | Reward: 0.087 | Value: 0.177 | VLoss: 0.0445 | PLoss: -0.0004 | Ent: 0.6841
262
+ [ 43.0%] Iter 262/610 | SPS: 27310 | Reward: 0.085 | Value: 0.175 | VLoss: 0.0461 | PLoss: 0.0000 | Ent: 0.6839
263
+ [ 43.1%] Iter 263/610 | SPS: 27310 | Reward: 0.090 | Value: 0.170 | VLoss: 0.0499 | PLoss: -0.0003 | Ent: 0.6819
264
+ [ 43.3%] Iter 264/610 | SPS: 27311 | Reward: 0.089 | Value: 0.180 | VLoss: 0.0482 | PLoss: -0.0000 | Ent: 0.6822
265
+ [ 43.4%] Iter 265/610 | SPS: 27311 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0462 | PLoss: 0.0002 | Ent: 0.6851
266
+ [ 43.6%] Iter 266/610 | SPS: 27311 | Reward: 0.087 | Value: 0.177 | VLoss: 0.0481 | PLoss: -0.0000 | Ent: 0.6860
267
+ [ 43.8%] Iter 267/610 | SPS: 27311 | Reward: 0.087 | Value: 0.171 | VLoss: 0.0453 | PLoss: 0.0000 | Ent: 0.6865
268
+ [ 43.9%] Iter 268/610 | SPS: 27311 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0482 | PLoss: 0.0001 | Ent: 0.6874
269
+ [ 44.1%] Iter 269/610 | SPS: 27309 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0457 | PLoss: -0.0002 | Ent: 0.6883
270
+ [ 44.3%] Iter 270/610 | SPS: 27310 | Reward: 0.090 | Value: 0.174 | VLoss: 0.0469 | PLoss: -0.0001 | Ent: 0.6886
271
+ [ 44.4%] Iter 271/610 | SPS: 27310 | Reward: 0.087 | Value: 0.181 | VLoss: 0.0472 | PLoss: -0.0000 | Ent: 0.6880
272
+ [ 44.6%] Iter 272/610 | SPS: 27311 | Reward: 0.085 | Value: 0.176 | VLoss: 0.0440 | PLoss: -0.0001 | Ent: 0.6871
273
+ [ 44.8%] Iter 273/610 | SPS: 27311 | Reward: 0.088 | Value: 0.169 | VLoss: 0.0442 | PLoss: -0.0000 | Ent: 0.6873
274
+ [ 44.9%] Iter 274/610 | SPS: 27312 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0459 | PLoss: -0.0000 | Ent: 0.6868
275
+ [ 45.1%] Iter 275/610 | SPS: 27313 | Reward: 0.088 | Value: 0.177 | VLoss: 0.0461 | PLoss: 0.0000 | Ent: 0.6859
276
+ [ 45.2%] Iter 276/610 | SPS: 27314 | Reward: 0.090 | Value: 0.175 | VLoss: 0.0496 | PLoss: -0.0002 | Ent: 0.6870
277
+ [ 45.4%] Iter 277/610 | SPS: 27315 | Reward: 0.086 | Value: 0.179 | VLoss: 0.0453 | PLoss: -0.0001 | Ent: 0.6873
278
+ [ 45.6%] Iter 278/610 | SPS: 27316 | Reward: 0.082 | Value: 0.172 | VLoss: 0.0427 | PLoss: -0.0000 | Ent: 0.6880
279
+ [ 45.7%] Iter 279/610 | SPS: 27316 | Reward: 0.087 | Value: 0.164 | VLoss: 0.0457 | PLoss: -0.0001 | Ent: 0.6886
280
+ [ 45.9%] Iter 280/610 | SPS: 27317 | Reward: 0.089 | Value: 0.172 | VLoss: 0.0482 | PLoss: 0.0001 | Ent: 0.6887
281
+ [ 46.1%] Iter 281/610 | SPS: 27317 | Reward: 0.086 | Value: 0.177 | VLoss: 0.0454 | PLoss: -0.0002 | Ent: 0.6879
282
+ [ 46.2%] Iter 282/610 | SPS: 27317 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0445 | PLoss: 0.0000 | Ent: 0.6865
283
+ [ 46.4%] Iter 283/610 | SPS: 27318 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0464 | PLoss: -0.0000 | Ent: 0.6869
284
+ [ 46.6%] Iter 284/610 | SPS: 27319 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0465 | PLoss: -0.0004 | Ent: 0.6882
285
+ [ 46.7%] Iter 285/610 | SPS: 27317 | Reward: 0.089 | Value: 0.170 | VLoss: 0.0469 | PLoss: 0.0000 | Ent: 0.6894
286
+ [ 46.9%] Iter 286/610 | SPS: 27316 | Reward: 0.085 | Value: 0.177 | VLoss: 0.0438 | PLoss: -0.0001 | Ent: 0.6896
287
+ [ 47.0%] Iter 287/610 | SPS: 27316 | Reward: 0.086 | Value: 0.169 | VLoss: 0.0432 | PLoss: -0.0000 | Ent: 0.6897
288
+ [ 47.2%] Iter 288/610 | SPS: 27316 | Reward: 0.087 | Value: 0.171 | VLoss: 0.0485 | PLoss: -0.0001 | Ent: 0.6906
289
+ [ 47.4%] Iter 289/610 | SPS: 27317 | Reward: 0.085 | Value: 0.173 | VLoss: 0.0459 | PLoss: 0.0001 | Ent: 0.6911
290
+ [ 47.5%] Iter 290/610 | SPS: 27318 | Reward: 0.086 | Value: 0.170 | VLoss: 0.0460 | PLoss: 0.0000 | Ent: 0.6915
291
+ [ 47.7%] Iter 291/610 | SPS: 27319 | Reward: 0.087 | Value: 0.170 | VLoss: 0.0458 | PLoss: -0.0001 | Ent: 0.6918
292
+ [ 47.9%] Iter 292/610 | SPS: 27320 | Reward: 0.089 | Value: 0.174 | VLoss: 0.0476 | PLoss: 0.0001 | Ent: 0.6922
293
+ [ 48.0%] Iter 293/610 | SPS: 27320 | Reward: 0.088 | Value: 0.179 | VLoss: 0.0470 | PLoss: -0.0000 | Ent: 0.6922
294
+ [ 48.2%] Iter 294/610 | SPS: 27321 | Reward: 0.089 | Value: 0.175 | VLoss: 0.0460 | PLoss: -0.0000 | Ent: 0.6921
295
+ [ 48.4%] Iter 295/610 | SPS: 27323 | Reward: 0.088 | Value: 0.177 | VLoss: 0.0485 | PLoss: 0.0000 | Ent: 0.6919
296
+ [ 48.5%] Iter 296/610 | SPS: 27324 | Reward: 0.089 | Value: 0.175 | VLoss: 0.0480 | PLoss: 0.0000 | Ent: 0.6922
297
+ [ 48.7%] Iter 297/610 | SPS: 27324 | Reward: 0.089 | Value: 0.177 | VLoss: 0.0503 | PLoss: -0.0000 | Ent: 0.6923
298
+ [ 48.9%] Iter 298/610 | SPS: 27325 | Reward: 0.090 | Value: 0.176 | VLoss: 0.0498 | PLoss: 0.0000 | Ent: 0.6923
299
+ [ 49.0%] Iter 299/610 | SPS: 27325 | Reward: 0.089 | Value: 0.179 | VLoss: 0.0508 | PLoss: -0.0001 | Ent: 0.6924
300
+ [ 49.2%] Iter 300/610 | SPS: 27325 | Reward: 0.087 | Value: 0.176 | VLoss: 0.0470 | PLoss: 0.0000 | Ent: 0.6924
301
+ [ 49.3%] Iter 301/610 | SPS: 27326 | Reward: 0.090 | Value: 0.173 | VLoss: 0.0488 | PLoss: -0.0001 | Ent: 0.6923
302
+ [ 49.5%] Iter 302/610 | SPS: 27325 | Reward: 0.086 | Value: 0.180 | VLoss: 0.0461 | PLoss: 0.0000 | Ent: 0.6921
303
+ [ 49.7%] Iter 303/610 | SPS: 27325 | Reward: 0.086 | Value: 0.170 | VLoss: 0.0466 | PLoss: -0.0001 | Ent: 0.6923
304
+ [ 49.8%] Iter 304/610 | SPS: 27327 | Reward: 0.088 | Value: 0.170 | VLoss: 0.0454 | PLoss: -0.0000 | Ent: 0.6923
305
+ [ 50.0%] Iter 305/610 | SPS: 27328 | Reward: 0.084 | Value: 0.177 | VLoss: 0.0449 | PLoss: 0.0000 | Ent: 0.6922
306
+ [ 50.2%] Iter 306/610 | SPS: 27329 | Reward: 0.087 | Value: 0.167 | VLoss: 0.0478 | PLoss: -0.0003 | Ent: 0.6920
307
+ [ 50.3%] Iter 307/610 | SPS: 27331 | Reward: 0.086 | Value: 0.173 | VLoss: 0.0467 | PLoss: -0.0000 | Ent: 0.6917
308
+ [ 50.5%] Iter 308/610 | SPS: 27332 | Reward: 0.089 | Value: 0.172 | VLoss: 0.0463 | PLoss: -0.0000 | Ent: 0.6919
309
+ [ 50.7%] Iter 309/610 | SPS: 27334 | Reward: 0.086 | Value: 0.179 | VLoss: 0.0458 | PLoss: -0.0000 | Ent: 0.6921
310
+ [ 50.8%] Iter 310/610 | SPS: 27335 | Reward: 0.087 | Value: 0.171 | VLoss: 0.0441 | PLoss: -0.0000 | Ent: 0.6921
311
+ [ 51.0%] Iter 311/610 | SPS: 27336 | Reward: 0.086 | Value: 0.173 | VLoss: 0.0487 | PLoss: 0.0000 | Ent: 0.6922
312
+ [ 51.1%] Iter 312/610 | SPS: 27338 | Reward: 0.090 | Value: 0.172 | VLoss: 0.0493 | PLoss: -0.0000 | Ent: 0.6925
313
+ [ 51.3%] Iter 313/610 | SPS: 27340 | Reward: 0.089 | Value: 0.178 | VLoss: 0.0492 | PLoss: -0.0001 | Ent: 0.6925
314
+ [ 51.5%] Iter 314/610 | SPS: 27342 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0468 | PLoss: -0.0000 | Ent: 0.6924
315
+ [ 51.6%] Iter 315/610 | SPS: 27342 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0460 | PLoss: -0.0000 | Ent: 0.6924
316
+ [ 51.8%] Iter 316/610 | SPS: 27343 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0462 | PLoss: 0.0000 | Ent: 0.6927
317
+ [ 52.0%] Iter 317/610 | SPS: 27344 | Reward: 0.086 | Value: 0.176 | VLoss: 0.0423 | PLoss: -0.0000 | Ent: 0.6926
318
+ [ 52.1%] Iter 318/610 | SPS: 27345 | Reward: 0.087 | Value: 0.170 | VLoss: 0.0456 | PLoss: -0.0000 | Ent: 0.6926
319
+ [ 52.3%] Iter 319/610 | SPS: 27345 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0453 | PLoss: 0.0000 | Ent: 0.6927
320
+ [ 52.5%] Iter 320/610 | SPS: 27345 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0458 | PLoss: 0.0000 | Ent: 0.6927
321
+ [ 52.6%] Iter 321/610 | SPS: 27346 | Reward: 0.089 | Value: 0.173 | VLoss: 0.0495 | PLoss: 0.0000 | Ent: 0.6927
322
+ [ 52.8%] Iter 322/610 | SPS: 27347 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0491 | PLoss: -0.0000 | Ent: 0.6926
323
+ [ 53.0%] Iter 323/610 | SPS: 27348 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0474 | PLoss: -0.0001 | Ent: 0.6924
324
+ [ 53.1%] Iter 324/610 | SPS: 27349 | Reward: 0.089 | Value: 0.174 | VLoss: 0.0495 | PLoss: -0.0000 | Ent: 0.6924
325
+ [ 53.3%] Iter 325/610 | SPS: 27350 | Reward: 0.087 | Value: 0.176 | VLoss: 0.0462 | PLoss: -0.0001 | Ent: 0.6924
326
+ [ 53.4%] Iter 326/610 | SPS: 27351 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0455 | PLoss: -0.0000 | Ent: 0.6923
327
+ [ 53.6%] Iter 327/610 | SPS: 27353 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0500 | PLoss: -0.0000 | Ent: 0.6920
328
+ [ 53.8%] Iter 328/610 | SPS: 27353 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0453 | PLoss: -0.0002 | Ent: 0.6923
329
+ [ 53.9%] Iter 329/610 | SPS: 27354 | Reward: 0.087 | Value: 0.172 | VLoss: 0.0471 | PLoss: 0.0000 | Ent: 0.6925
330
+ [ 54.1%] Iter 330/610 | SPS: 27355 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0463 | PLoss: -0.0000 | Ent: 0.6927
331
+ [ 54.3%] Iter 331/610 | SPS: 27356 | Reward: 0.089 | Value: 0.175 | VLoss: 0.0492 | PLoss: -0.0000 | Ent: 0.6928
332
+ [ 54.4%] Iter 332/610 | SPS: 27357 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0453 | PLoss: -0.0000 | Ent: 0.6928
333
+ [ 54.6%] Iter 333/610 | SPS: 27357 | Reward: 0.088 | Value: 0.178 | VLoss: 0.0443 | PLoss: -0.0000 | Ent: 0.6928
334
+ [ 54.8%] Iter 334/610 | SPS: 27359 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0450 | PLoss: -0.0000 | Ent: 0.6930
335
+ [ 54.9%] Iter 335/610 | SPS: 27359 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0451 | PLoss: -0.0000 | Ent: 0.6930
336
+ [ 55.1%] Iter 336/610 | SPS: 27358 | Reward: 0.088 | Value: 0.169 | VLoss: 0.0460 | PLoss: 0.0001 | Ent: 0.6931
337
+ [ 55.2%] Iter 337/610 | SPS: 27358 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0467 | PLoss: 0.0000 | Ent: 0.6931
338
+ [ 55.4%] Iter 338/610 | SPS: 27359 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0494 | PLoss: -0.0000 | Ent: 0.6931
339
+ [ 55.6%] Iter 339/610 | SPS: 27360 | Reward: 0.085 | Value: 0.176 | VLoss: 0.0444 | PLoss: 0.0000 | Ent: 0.6931
340
+ [ 55.7%] Iter 340/610 | SPS: 27361 | Reward: 0.084 | Value: 0.168 | VLoss: 0.0460 | PLoss: -0.0000 | Ent: 0.6931
341
+ [ 55.9%] Iter 341/610 | SPS: 27362 | Reward: 0.086 | Value: 0.166 | VLoss: 0.0466 | PLoss: -0.0000 | Ent: 0.6931
342
+ [ 56.1%] Iter 342/610 | SPS: 27363 | Reward: 0.088 | Value: 0.172 | VLoss: 0.0439 | PLoss: -0.0001 | Ent: 0.6931
343
+ [ 56.2%] Iter 343/610 | SPS: 27365 | Reward: 0.085 | Value: 0.176 | VLoss: 0.0450 | PLoss: 0.0000 | Ent: 0.6931
344
+ [ 56.4%] Iter 344/610 | SPS: 27366 | Reward: 0.090 | Value: 0.169 | VLoss: 0.0460 | PLoss: -0.0000 | Ent: 0.6931
345
+ [ 56.6%] Iter 345/610 | SPS: 27367 | Reward: 0.087 | Value: 0.180 | VLoss: 0.0474 | PLoss: 0.0000 | Ent: 0.6931
346
+ [ 56.7%] Iter 346/610 | SPS: 27368 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0470 | PLoss: 0.0000 | Ent: 0.6930
347
+ [ 56.9%] Iter 347/610 | SPS: 27369 | Reward: 0.086 | Value: 0.177 | VLoss: 0.0454 | PLoss: -0.0001 | Ent: 0.6929
348
+ [ 57.0%] Iter 348/610 | SPS: 27370 | Reward: 0.088 | Value: 0.172 | VLoss: 0.0474 | PLoss: -0.0001 | Ent: 0.6928
349
+ [ 57.2%] Iter 349/610 | SPS: 27371 | Reward: 0.084 | Value: 0.173 | VLoss: 0.0437 | PLoss: -0.0000 | Ent: 0.6928
350
+ [ 57.4%] Iter 350/610 | SPS: 27372 | Reward: 0.087 | Value: 0.166 | VLoss: 0.0486 | PLoss: -0.0000 | Ent: 0.6928
351
+ [ 57.5%] Iter 351/610 | SPS: 27373 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0456 | PLoss: 0.0000 | Ent: 0.6928
352
+ [ 57.7%] Iter 352/610 | SPS: 27374 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0458 | PLoss: 0.0000 | Ent: 0.6927
353
+ [ 57.9%] Iter 353/610 | SPS: 27372 | Reward: 0.091 | Value: 0.174 | VLoss: 0.0462 | PLoss: -0.0001 | Ent: 0.6927
354
+ [ 58.0%] Iter 354/610 | SPS: 27373 | Reward: 0.088 | Value: 0.182 | VLoss: 0.0455 | PLoss: -0.0002 | Ent: 0.6928
355
+ [ 58.2%] Iter 355/610 | SPS: 27373 | Reward: 0.088 | Value: 0.177 | VLoss: 0.0467 | PLoss: 0.0001 | Ent: 0.6930
356
+ [ 58.4%] Iter 356/610 | SPS: 27374 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0451 | PLoss: 0.0000 | Ent: 0.6930
357
+ [ 58.5%] Iter 357/610 | SPS: 27374 | Reward: 0.090 | Value: 0.172 | VLoss: 0.0482 | PLoss: -0.0001 | Ent: 0.6929
358
+ [ 58.7%] Iter 358/610 | SPS: 27375 | Reward: 0.089 | Value: 0.180 | VLoss: 0.0490 | PLoss: -0.0000 | Ent: 0.6929
359
+ [ 58.9%] Iter 359/610 | SPS: 27375 | Reward: 0.087 | Value: 0.179 | VLoss: 0.0457 | PLoss: 0.0001 | Ent: 0.6930
360
+ [ 59.0%] Iter 360/610 | SPS: 27376 | Reward: 0.089 | Value: 0.172 | VLoss: 0.0464 | PLoss: -0.0000 | Ent: 0.6930
361
+ [ 59.2%] Iter 361/610 | SPS: 27376 | Reward: 0.087 | Value: 0.176 | VLoss: 0.0481 | PLoss: -0.0000 | Ent: 0.6930
362
+ [ 59.3%] Iter 362/610 | SPS: 27377 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0460 | PLoss: 0.0000 | Ent: 0.6931
363
+ [ 59.5%] Iter 363/610 | SPS: 27377 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0454 | PLoss: 0.0000 | Ent: 0.6931
364
+ [ 59.7%] Iter 364/610 | SPS: 27378 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0442 | PLoss: 0.0000 | Ent: 0.6931
365
+ [ 59.8%] Iter 365/610 | SPS: 27377 | Reward: 0.088 | Value: 0.179 | VLoss: 0.0461 | PLoss: 0.0000 | Ent: 0.6931
366
+ [ 60.0%] Iter 366/610 | SPS: 27378 | Reward: 0.089 | Value: 0.175 | VLoss: 0.0447 | PLoss: -0.0001 | Ent: 0.6931
367
+ [ 60.2%] Iter 367/610 | SPS: 27378 | Reward: 0.083 | Value: 0.177 | VLoss: 0.0439 | PLoss: 0.0000 | Ent: 0.6931
368
+ [ 60.3%] Iter 368/610 | SPS: 27378 | Reward: 0.087 | Value: 0.165 | VLoss: 0.0437 | PLoss: -0.0000 | Ent: 0.6931
369
+ [ 60.5%] Iter 369/610 | SPS: 27378 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0487 | PLoss: 0.0000 | Ent: 0.6931
370
+ [ 60.7%] Iter 370/610 | SPS: 27377 | Reward: 0.088 | Value: 0.178 | VLoss: 0.0473 | PLoss: -0.0000 | Ent: 0.6931
371
+ [ 60.8%] Iter 371/610 | SPS: 27377 | Reward: 0.085 | Value: 0.174 | VLoss: 0.0433 | PLoss: -0.0000 | Ent: 0.6931
372
+ [ 61.0%] Iter 372/610 | SPS: 27377 | Reward: 0.087 | Value: 0.169 | VLoss: 0.0433 | PLoss: 0.0000 | Ent: 0.6931
373
+ [ 61.1%] Iter 373/610 | SPS: 27378 | Reward: 0.090 | Value: 0.173 | VLoss: 0.0489 | PLoss: -0.0000 | Ent: 0.6931
374
+ [ 61.3%] Iter 374/610 | SPS: 27378 | Reward: 0.088 | Value: 0.180 | VLoss: 0.0478 | PLoss: -0.0000 | Ent: 0.6931
375
+ [ 61.5%] Iter 375/610 | SPS: 27379 | Reward: 0.089 | Value: 0.174 | VLoss: 0.0478 | PLoss: -0.0000 | Ent: 0.6931
376
+ [ 61.6%] Iter 376/610 | SPS: 27380 | Reward: 0.087 | Value: 0.176 | VLoss: 0.0481 | PLoss: 0.0000 | Ent: 0.6931
377
+ [ 61.8%] Iter 377/610 | SPS: 27380 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0457 | PLoss: -0.0000 | Ent: 0.6931
378
+ [ 62.0%] Iter 378/610 | SPS: 27381 | Reward: 0.089 | Value: 0.170 | VLoss: 0.0485 | PLoss: 0.0000 | Ent: 0.6931
379
+ [ 62.1%] Iter 379/610 | SPS: 27382 | Reward: 0.089 | Value: 0.179 | VLoss: 0.0460 | PLoss: -0.0000 | Ent: 0.6931
380
+ [ 62.3%] Iter 380/610 | SPS: 27383 | Reward: 0.088 | Value: 0.178 | VLoss: 0.0480 | PLoss: -0.0001 | Ent: 0.6931
381
+ [ 62.5%] Iter 381/610 | SPS: 27383 | Reward: 0.088 | Value: 0.172 | VLoss: 0.0469 | PLoss: -0.0000 | Ent: 0.6931
382
+ [ 62.6%] Iter 382/610 | SPS: 27384 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0485 | PLoss: -0.0000 | Ent: 0.6931
383
+ [ 62.8%] Iter 383/610 | SPS: 27385 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0473 | PLoss: -0.0000 | Ent: 0.6931
384
+ [ 63.0%] Iter 384/610 | SPS: 27386 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0468 | PLoss: -0.0000 | Ent: 0.6931
385
+ [ 63.1%] Iter 385/610 | SPS: 27387 | Reward: 0.086 | Value: 0.176 | VLoss: 0.0447 | PLoss: 0.0000 | Ent: 0.6931
386
+ [ 63.3%] Iter 386/610 | SPS: 27387 | Reward: 0.087 | Value: 0.171 | VLoss: 0.0488 | PLoss: -0.0000 | Ent: 0.6931
387
+ [ 63.4%] Iter 387/610 | SPS: 27387 | Reward: 0.085 | Value: 0.172 | VLoss: 0.0448 | PLoss: 0.0000 | Ent: 0.6931
388
+ [ 63.6%] Iter 388/610 | SPS: 27388 | Reward: 0.086 | Value: 0.169 | VLoss: 0.0469 | PLoss: 0.0000 | Ent: 0.6931
389
+ [ 63.8%] Iter 389/610 | SPS: 27389 | Reward: 0.089 | Value: 0.172 | VLoss: 0.0455 | PLoss: -0.0000 | Ent: 0.6931
390
+ [ 63.9%] Iter 390/610 | SPS: 27390 | Reward: 0.088 | Value: 0.180 | VLoss: 0.0479 | PLoss: 0.0000 | Ent: 0.6931
391
+ [ 64.1%] Iter 391/610 | SPS: 27391 | Reward: 0.091 | Value: 0.176 | VLoss: 0.0502 | PLoss: -0.0000 | Ent: 0.6931
392
+ [ 64.3%] Iter 392/610 | SPS: 27392 | Reward: 0.087 | Value: 0.179 | VLoss: 0.0476 | PLoss: -0.0000 | Ent: 0.6931
393
+ [ 64.4%] Iter 393/610 | SPS: 27392 | Reward: 0.084 | Value: 0.173 | VLoss: 0.0459 | PLoss: 0.0000 | Ent: 0.6931
394
+ [ 64.6%] Iter 394/610 | SPS: 27392 | Reward: 0.085 | Value: 0.165 | VLoss: 0.0445 | PLoss: -0.0000 | Ent: 0.6931
395
+ [ 64.8%] Iter 395/610 | SPS: 27393 | Reward: 0.087 | Value: 0.170 | VLoss: 0.0481 | PLoss: 0.0000 | Ent: 0.6931
396
+ [ 64.9%] Iter 396/610 | SPS: 27393 | Reward: 0.090 | Value: 0.174 | VLoss: 0.0483 | PLoss: -0.0001 | Ent: 0.6931
397
+ [ 65.1%] Iter 397/610 | SPS: 27393 | Reward: 0.088 | Value: 0.181 | VLoss: 0.0467 | PLoss: -0.0001 | Ent: 0.6930
398
+ [ 65.2%] Iter 398/610 | SPS: 27394 | Reward: 0.086 | Value: 0.175 | VLoss: 0.0453 | PLoss: -0.0000 | Ent: 0.6930
399
+ [ 65.4%] Iter 399/610 | SPS: 27394 | Reward: 0.088 | Value: 0.171 | VLoss: 0.0469 | PLoss: 0.0000 | Ent: 0.6930
400
+ [ 65.6%] Iter 400/610 | SPS: 27393 | Reward: 0.085 | Value: 0.174 | VLoss: 0.0459 | PLoss: 0.0000 | Ent: 0.6931
401
+ [ 65.7%] Iter 401/610 | SPS: 27393 | Reward: 0.089 | Value: 0.167 | VLoss: 0.0480 | PLoss: -0.0000 | Ent: 0.6931
402
+ [ 65.9%] Iter 402/610 | SPS: 27393 | Reward: 0.086 | Value: 0.178 | VLoss: 0.0454 | PLoss: -0.0000 | Ent: 0.6931
403
+ [ 66.1%] Iter 403/610 | SPS: 27393 | Reward: 0.089 | Value: 0.172 | VLoss: 0.0459 | PLoss: -0.0000 | Ent: 0.6931
404
+ [ 66.2%] Iter 404/610 | SPS: 27393 | Reward: 0.088 | Value: 0.177 | VLoss: 0.0509 | PLoss: -0.0001 | Ent: 0.6930
405
+ [ 66.4%] Iter 405/610 | SPS: 27393 | Reward: 0.086 | Value: 0.176 | VLoss: 0.0439 | PLoss: -0.0000 | Ent: 0.6930
406
+ [ 66.6%] Iter 406/610 | SPS: 27393 | Reward: 0.089 | Value: 0.170 | VLoss: 0.0475 | PLoss: -0.0000 | Ent: 0.6931
407
+ [ 66.7%] Iter 407/610 | SPS: 27393 | Reward: 0.088 | Value: 0.178 | VLoss: 0.0459 | PLoss: 0.0000 | Ent: 0.6931
408
+ [ 66.9%] Iter 408/610 | SPS: 27393 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0462 | PLoss: 0.0000 | Ent: 0.6931
409
+ [ 67.0%] Iter 409/610 | SPS: 27393 | Reward: 0.086 | Value: 0.175 | VLoss: 0.0461 | PLoss: -0.0000 | Ent: 0.6931
410
+ [ 67.2%] Iter 410/610 | SPS: 27393 | Reward: 0.090 | Value: 0.170 | VLoss: 0.0474 | PLoss: -0.0001 | Ent: 0.6931
411
+ [ 67.4%] Iter 411/610 | SPS: 27393 | Reward: 0.091 | Value: 0.181 | VLoss: 0.0471 | PLoss: -0.0001 | Ent: 0.6931
412
+ [ 67.5%] Iter 412/610 | SPS: 27394 | Reward: 0.086 | Value: 0.181 | VLoss: 0.0467 | PLoss: 0.0000 | Ent: 0.6931
413
+ [ 67.7%] Iter 413/610 | SPS: 27394 | Reward: 0.086 | Value: 0.170 | VLoss: 0.0467 | PLoss: -0.0000 | Ent: 0.6931
414
+ [ 67.9%] Iter 414/610 | SPS: 27394 | Reward: 0.089 | Value: 0.172 | VLoss: 0.0473 | PLoss: -0.0000 | Ent: 0.6931
415
+ [ 68.0%] Iter 415/610 | SPS: 27394 | Reward: 0.085 | Value: 0.178 | VLoss: 0.0457 | PLoss: -0.0000 | Ent: 0.6931
416
+ [ 68.2%] Iter 416/610 | SPS: 27394 | Reward: 0.087 | Value: 0.169 | VLoss: 0.0456 | PLoss: -0.0000 | Ent: 0.6931
417
+ [ 68.4%] Iter 417/610 | SPS: 27394 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0468 | PLoss: -0.0000 | Ent: 0.6931
418
+ [ 68.5%] Iter 418/610 | SPS: 27395 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0458 | PLoss: 0.0000 | Ent: 0.6931
419
+ [ 68.7%] Iter 419/610 | SPS: 27395 | Reward: 0.088 | Value: 0.170 | VLoss: 0.0471 | PLoss: -0.0000 | Ent: 0.6931
420
+ [ 68.9%] Iter 420/610 | SPS: 27393 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0452 | PLoss: 0.0000 | Ent: 0.6931
421
+ [ 69.0%] Iter 421/610 | SPS: 27393 | Reward: 0.087 | Value: 0.178 | VLoss: 0.0489 | PLoss: -0.0000 | Ent: 0.6931
422
+ [ 69.2%] Iter 422/610 | SPS: 27393 | Reward: 0.084 | Value: 0.171 | VLoss: 0.0434 | PLoss: -0.0000 | Ent: 0.6931
423
+ [ 69.3%] Iter 423/610 | SPS: 27393 | Reward: 0.086 | Value: 0.167 | VLoss: 0.0468 | PLoss: -0.0000 | Ent: 0.6931
424
+ [ 69.5%] Iter 424/610 | SPS: 27393 | Reward: 0.089 | Value: 0.173 | VLoss: 0.0472 | PLoss: 0.0000 | Ent: 0.6931
425
+ [ 69.7%] Iter 425/610 | SPS: 27393 | Reward: 0.086 | Value: 0.176 | VLoss: 0.0450 | PLoss: 0.0000 | Ent: 0.6931
426
+ [ 69.8%] Iter 426/610 | SPS: 27393 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0464 | PLoss: -0.0000 | Ent: 0.6931
427
+ [ 70.0%] Iter 427/610 | SPS: 27393 | Reward: 0.090 | Value: 0.172 | VLoss: 0.0461 | PLoss: 0.0000 | Ent: 0.6931
428
+ [ 70.2%] Iter 428/610 | SPS: 27393 | Reward: 0.087 | Value: 0.178 | VLoss: 0.0459 | PLoss: -0.0000 | Ent: 0.6931
429
+ [ 70.3%] Iter 429/610 | SPS: 27393 | Reward: 0.089 | Value: 0.173 | VLoss: 0.0477 | PLoss: -0.0001 | Ent: 0.6931
430
+ [ 70.5%] Iter 430/610 | SPS: 27393 | Reward: 0.087 | Value: 0.178 | VLoss: 0.0473 | PLoss: -0.0000 | Ent: 0.6931
431
+ [ 70.7%] Iter 431/610 | SPS: 27394 | Reward: 0.087 | Value: 0.172 | VLoss: 0.0445 | PLoss: -0.0000 | Ent: 0.6931
432
+ [ 70.8%] Iter 432/610 | SPS: 27394 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0458 | PLoss: -0.0000 | Ent: 0.6931
433
+ [ 71.0%] Iter 433/610 | SPS: 27394 | Reward: 0.088 | Value: 0.171 | VLoss: 0.0482 | PLoss: 0.0000 | Ent: 0.6931
434
+ [ 71.1%] Iter 434/610 | SPS: 27394 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0490 | PLoss: -0.0000 | Ent: 0.6931
435
+ [ 71.3%] Iter 435/610 | SPS: 27395 | Reward: 0.084 | Value: 0.173 | VLoss: 0.0453 | PLoss: -0.0000 | Ent: 0.6931
436
+ [ 71.5%] Iter 436/610 | SPS: 27394 | Reward: 0.089 | Value: 0.170 | VLoss: 0.0464 | PLoss: -0.0000 | Ent: 0.6931
437
+ [ 71.6%] Iter 437/610 | SPS: 27393 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0485 | PLoss: -0.0000 | Ent: 0.6931
438
+ [ 71.8%] Iter 438/610 | SPS: 27393 | Reward: 0.087 | Value: 0.178 | VLoss: 0.0465 | PLoss: 0.0000 | Ent: 0.6931
439
+ [ 72.0%] Iter 439/610 | SPS: 27394 | Reward: 0.090 | Value: 0.173 | VLoss: 0.0467 | PLoss: -0.0000 | Ent: 0.6931
440
+ [ 72.1%] Iter 440/610 | SPS: 27394 | Reward: 0.087 | Value: 0.179 | VLoss: 0.0453 | PLoss: 0.0000 | Ent: 0.6931
441
+ [ 72.3%] Iter 441/610 | SPS: 27394 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0470 | PLoss: 0.0000 | Ent: 0.6931
442
+ [ 72.5%] Iter 442/610 | SPS: 27394 | Reward: 0.087 | Value: 0.177 | VLoss: 0.0457 | PLoss: -0.0001 | Ent: 0.6931
443
+ [ 72.6%] Iter 443/610 | SPS: 27394 | Reward: 0.087 | Value: 0.171 | VLoss: 0.0469 | PLoss: 0.0000 | Ent: 0.6931
444
+ [ 72.8%] Iter 444/610 | SPS: 27394 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0460 | PLoss: -0.0000 | Ent: 0.6931
445
+ [ 73.0%] Iter 445/610 | SPS: 27395 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0449 | PLoss: -0.0000 | Ent: 0.6931
446
+ [ 73.1%] Iter 446/610 | SPS: 27395 | Reward: 0.086 | Value: 0.173 | VLoss: 0.0455 | PLoss: 0.0000 | Ent: 0.6931
447
+ [ 73.3%] Iter 447/610 | SPS: 27395 | Reward: 0.088 | Value: 0.171 | VLoss: 0.0470 | PLoss: -0.0000 | Ent: 0.6931
448
+ [ 73.4%] Iter 448/610 | SPS: 27395 | Reward: 0.087 | Value: 0.176 | VLoss: 0.0451 | PLoss: 0.0000 | Ent: 0.6931
449
+ [ 73.6%] Iter 449/610 | SPS: 27395 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0484 | PLoss: -0.0001 | Ent: 0.6931
450
+ [ 73.8%] Iter 450/610 | SPS: 27396 | Reward: 0.088 | Value: 0.171 | VLoss: 0.0481 | PLoss: -0.0000 | Ent: 0.6931
451
+ [ 73.9%] Iter 451/610 | SPS: 27396 | Reward: 0.088 | Value: 0.177 | VLoss: 0.0475 | PLoss: -0.0000 | Ent: 0.6931
452
+ [ 74.1%] Iter 452/610 | SPS: 27396 | Reward: 0.090 | Value: 0.176 | VLoss: 0.0482 | PLoss: 0.0000 | Ent: 0.6931
453
+ [ 74.3%] Iter 453/610 | SPS: 27396 | Reward: 0.091 | Value: 0.178 | VLoss: 0.0494 | PLoss: -0.0000 | Ent: 0.6931
454
+ [ 74.4%] Iter 454/610 | SPS: 27395 | Reward: 0.087 | Value: 0.181 | VLoss: 0.0456 | PLoss: -0.0001 | Ent: 0.6931
455
+ [ 74.6%] Iter 455/610 | SPS: 27395 | Reward: 0.086 | Value: 0.172 | VLoss: 0.0459 | PLoss: -0.0001 | Ent: 0.6931
456
+ [ 74.8%] Iter 456/610 | SPS: 27395 | Reward: 0.088 | Value: 0.172 | VLoss: 0.0456 | PLoss: -0.0000 | Ent: 0.6930
457
+ [ 74.9%] Iter 457/610 | SPS: 27395 | Reward: 0.084 | Value: 0.175 | VLoss: 0.0461 | PLoss: -0.0001 | Ent: 0.6930
458
+ [ 75.1%] Iter 458/610 | SPS: 27396 | Reward: 0.090 | Value: 0.166 | VLoss: 0.0522 | PLoss: -0.0000 | Ent: 0.6930
459
+ [ 75.2%] Iter 459/610 | SPS: 27396 | Reward: 0.087 | Value: 0.180 | VLoss: 0.0472 | PLoss: -0.0000 | Ent: 0.6930
460
+ [ 75.4%] Iter 460/610 | SPS: 27396 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0442 | PLoss: -0.0000 | Ent: 0.6931
461
+ [ 75.6%] Iter 461/610 | SPS: 27396 | Reward: 0.083 | Value: 0.171 | VLoss: 0.0405 | PLoss: 0.0000 | Ent: 0.6931
462
+ [ 75.7%] Iter 462/610 | SPS: 27396 | Reward: 0.090 | Value: 0.165 | VLoss: 0.0470 | PLoss: -0.0000 | Ent: 0.6931
463
+ [ 75.9%] Iter 463/610 | SPS: 27397 | Reward: 0.086 | Value: 0.181 | VLoss: 0.0451 | PLoss: 0.0000 | Ent: 0.6931
464
+ [ 76.1%] Iter 464/610 | SPS: 27398 | Reward: 0.087 | Value: 0.171 | VLoss: 0.0454 | PLoss: 0.0000 | Ent: 0.6931
465
+ [ 76.2%] Iter 465/610 | SPS: 27399 | Reward: 0.089 | Value: 0.174 | VLoss: 0.0476 | PLoss: -0.0000 | Ent: 0.6931
466
+ [ 76.4%] Iter 466/610 | SPS: 27400 | Reward: 0.090 | Value: 0.177 | VLoss: 0.0486 | PLoss: -0.0000 | Ent: 0.6931
467
+ [ 76.6%] Iter 467/610 | SPS: 27401 | Reward: 0.087 | Value: 0.180 | VLoss: 0.0448 | PLoss: -0.0000 | Ent: 0.6930
468
+ [ 76.7%] Iter 468/610 | SPS: 27402 | Reward: 0.086 | Value: 0.172 | VLoss: 0.0459 | PLoss: 0.0000 | Ent: 0.6930
469
+ [ 76.9%] Iter 469/610 | SPS: 27402 | Reward: 0.088 | Value: 0.172 | VLoss: 0.0480 | PLoss: -0.0000 | Ent: 0.6929
470
+ [ 77.0%] Iter 470/610 | SPS: 27403 | Reward: 0.091 | Value: 0.173 | VLoss: 0.0468 | PLoss: 0.0000 | Ent: 0.6929
471
+ [ 77.2%] Iter 471/610 | SPS: 27403 | Reward: 0.087 | Value: 0.182 | VLoss: 0.0473 | PLoss: 0.0000 | Ent: 0.6929
472
+ [ 77.4%] Iter 472/610 | SPS: 27404 | Reward: 0.087 | Value: 0.170 | VLoss: 0.0479 | PLoss: -0.0001 | Ent: 0.6930
473
+ [ 77.5%] Iter 473/610 | SPS: 27405 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0451 | PLoss: -0.0000 | Ent: 0.6930
474
+ [ 77.7%] Iter 474/610 | SPS: 27407 | Reward: 0.087 | Value: 0.171 | VLoss: 0.0469 | PLoss: 0.0000 | Ent: 0.6929
475
+ [ 77.9%] Iter 475/610 | SPS: 27407 | Reward: 0.090 | Value: 0.174 | VLoss: 0.0468 | PLoss: 0.0000 | Ent: 0.6929
476
+ [ 78.0%] Iter 476/610 | SPS: 27407 | Reward: 0.086 | Value: 0.178 | VLoss: 0.0436 | PLoss: -0.0000 | Ent: 0.6929
477
+ [ 78.2%] Iter 477/610 | SPS: 27407 | Reward: 0.085 | Value: 0.171 | VLoss: 0.0450 | PLoss: 0.0000 | Ent: 0.6929
478
+ [ 78.4%] Iter 478/610 | SPS: 27407 | Reward: 0.088 | Value: 0.167 | VLoss: 0.0465 | PLoss: -0.0000 | Ent: 0.6929
479
+ [ 78.5%] Iter 479/610 | SPS: 27408 | Reward: 0.086 | Value: 0.177 | VLoss: 0.0420 | PLoss: -0.0001 | Ent: 0.6928
480
+ [ 78.7%] Iter 480/610 | SPS: 27408 | Reward: 0.085 | Value: 0.170 | VLoss: 0.0455 | PLoss: -0.0000 | Ent: 0.6926
481
+ [ 78.9%] Iter 481/610 | SPS: 27409 | Reward: 0.089 | Value: 0.171 | VLoss: 0.0479 | PLoss: -0.0000 | Ent: 0.6926
482
+ [ 79.0%] Iter 482/610 | SPS: 27409 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0450 | PLoss: -0.0000 | Ent: 0.6926
483
+ [ 79.2%] Iter 483/610 | SPS: 27409 | Reward: 0.088 | Value: 0.178 | VLoss: 0.0482 | PLoss: -0.0000 | Ent: 0.6925
484
+ [ 79.3%] Iter 484/610 | SPS: 27409 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0462 | PLoss: -0.0000 | Ent: 0.6925
485
+ [ 79.5%] Iter 485/610 | SPS: 27409 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0468 | PLoss: -0.0000 | Ent: 0.6926
486
+ [ 79.7%] Iter 486/610 | SPS: 27409 | Reward: 0.089 | Value: 0.175 | VLoss: 0.0458 | PLoss: -0.0000 | Ent: 0.6926
487
+ [ 79.8%] Iter 487/610 | SPS: 27409 | Reward: 0.086 | Value: 0.176 | VLoss: 0.0477 | PLoss: -0.0000 | Ent: 0.6926
488
+ [ 80.0%] Iter 488/610 | SPS: 27409 | Reward: 0.087 | Value: 0.172 | VLoss: 0.0465 | PLoss: 0.0000 | Ent: 0.6926
489
+ [ 80.2%] Iter 489/610 | SPS: 27409 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0454 | PLoss: -0.0000 | Ent: 0.6926
490
+ [ 80.3%] Iter 490/610 | SPS: 27409 | Reward: 0.089 | Value: 0.172 | VLoss: 0.0506 | PLoss: -0.0000 | Ent: 0.6925
491
+ [ 80.5%] Iter 491/610 | SPS: 27410 | Reward: 0.089 | Value: 0.178 | VLoss: 0.0467 | PLoss: 0.0000 | Ent: 0.6924
492
+ [ 80.7%] Iter 492/610 | SPS: 27410 | Reward: 0.087 | Value: 0.176 | VLoss: 0.0438 | PLoss: -0.0000 | Ent: 0.6924
493
+ [ 80.8%] Iter 493/610 | SPS: 27410 | Reward: 0.090 | Value: 0.174 | VLoss: 0.0473 | PLoss: -0.0000 | Ent: 0.6925
494
+ [ 81.0%] Iter 494/610 | SPS: 27411 | Reward: 0.087 | Value: 0.177 | VLoss: 0.0483 | PLoss: 0.0000 | Ent: 0.6926
495
+ [ 81.1%] Iter 495/610 | SPS: 27412 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0503 | PLoss: -0.0001 | Ent: 0.6927
496
+ [ 81.3%] Iter 496/610 | SPS: 27413 | Reward: 0.086 | Value: 0.176 | VLoss: 0.0473 | PLoss: -0.0000 | Ent: 0.6928
497
+ [ 81.5%] Iter 497/610 | SPS: 27414 | Reward: 0.086 | Value: 0.171 | VLoss: 0.0473 | PLoss: -0.0000 | Ent: 0.6929
498
+ [ 81.6%] Iter 498/610 | SPS: 27415 | Reward: 0.087 | Value: 0.171 | VLoss: 0.0436 | PLoss: 0.0000 | Ent: 0.6929
499
+ [ 81.8%] Iter 499/610 | SPS: 27417 | Reward: 0.087 | Value: 0.172 | VLoss: 0.0465 | PLoss: -0.0000 | Ent: 0.6929
500
+ [ 82.0%] Iter 500/610 | SPS: 27418 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0470 | PLoss: -0.0000 | Ent: 0.6929
501
+ [ 82.1%] Iter 501/610 | SPS: 27418 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0474 | PLoss: -0.0000 | Ent: 0.6929
502
+ [ 82.3%] Iter 502/610 | SPS: 27419 | Reward: 0.087 | Value: 0.172 | VLoss: 0.0455 | PLoss: 0.0000 | Ent: 0.6929
503
+ [ 82.5%] Iter 503/610 | SPS: 27420 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0468 | PLoss: -0.0000 | Ent: 0.6929
504
+ [ 82.6%] Iter 504/610 | SPS: 27420 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0482 | PLoss: 0.0000 | Ent: 0.6929
505
+ [ 82.8%] Iter 505/610 | SPS: 27420 | Reward: 0.090 | Value: 0.173 | VLoss: 0.0481 | PLoss: -0.0001 | Ent: 0.6930
506
+ [ 83.0%] Iter 506/610 | SPS: 27421 | Reward: 0.089 | Value: 0.179 | VLoss: 0.0466 | PLoss: -0.0000 | Ent: 0.6930
507
+ [ 83.1%] Iter 507/610 | SPS: 27423 | Reward: 0.088 | Value: 0.178 | VLoss: 0.0478 | PLoss: -0.0000 | Ent: 0.6930
508
+ [ 83.3%] Iter 508/610 | SPS: 27424 | Reward: 0.085 | Value: 0.175 | VLoss: 0.0469 | PLoss: -0.0000 | Ent: 0.6930
509
+ [ 83.4%] Iter 509/610 | SPS: 27425 | Reward: 0.089 | Value: 0.169 | VLoss: 0.0509 | PLoss: -0.0000 | Ent: 0.6930
510
+ [ 83.6%] Iter 510/610 | SPS: 27426 | Reward: 0.089 | Value: 0.180 | VLoss: 0.0472 | PLoss: -0.0000 | Ent: 0.6930
511
+ [ 83.8%] Iter 511/610 | SPS: 27427 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0468 | PLoss: -0.0000 | Ent: 0.6930
512
+ [ 83.9%] Iter 512/610 | SPS: 27428 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0484 | PLoss: 0.0000 | Ent: 0.6930
513
+ [ 84.1%] Iter 513/610 | SPS: 27429 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0478 | PLoss: 0.0000 | Ent: 0.6930
514
+ [ 84.3%] Iter 514/610 | SPS: 27429 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0446 | PLoss: -0.0000 | Ent: 0.6930
515
+ [ 84.4%] Iter 515/610 | SPS: 27430 | Reward: 0.085 | Value: 0.174 | VLoss: 0.0424 | PLoss: 0.0000 | Ent: 0.6930
516
+ [ 84.6%] Iter 516/610 | SPS: 27431 | Reward: 0.089 | Value: 0.170 | VLoss: 0.0473 | PLoss: 0.0000 | Ent: 0.6930
517
+ [ 84.8%] Iter 517/610 | SPS: 27432 | Reward: 0.087 | Value: 0.179 | VLoss: 0.0478 | PLoss: -0.0000 | Ent: 0.6929
518
+ [ 84.9%] Iter 518/610 | SPS: 27432 | Reward: 0.088 | Value: 0.170 | VLoss: 0.0471 | PLoss: 0.0000 | Ent: 0.6929
519
+ [ 85.1%] Iter 519/610 | SPS: 27433 | Reward: 0.087 | Value: 0.176 | VLoss: 0.0462 | PLoss: -0.0000 | Ent: 0.6928
520
+ [ 85.2%] Iter 520/610 | SPS: 27434 | Reward: 0.084 | Value: 0.176 | VLoss: 0.0423 | PLoss: 0.0000 | Ent: 0.6928
521
+ [ 85.4%] Iter 521/610 | SPS: 27434 | Reward: 0.085 | Value: 0.166 | VLoss: 0.0445 | PLoss: 0.0000 | Ent: 0.6928
522
+ [ 85.6%] Iter 522/610 | SPS: 27434 | Reward: 0.088 | Value: 0.169 | VLoss: 0.0477 | PLoss: 0.0000 | Ent: 0.6928
523
+ [ 85.7%] Iter 523/610 | SPS: 27434 | Reward: 0.089 | Value: 0.173 | VLoss: 0.0481 | PLoss: -0.0000 | Ent: 0.6929
524
+ [ 85.9%] Iter 524/610 | SPS: 27434 | Reward: 0.088 | Value: 0.178 | VLoss: 0.0473 | PLoss: -0.0000 | Ent: 0.6929
525
+ [ 86.1%] Iter 525/610 | SPS: 27434 | Reward: 0.086 | Value: 0.175 | VLoss: 0.0480 | PLoss: -0.0000 | Ent: 0.6929
526
+ [ 86.2%] Iter 526/610 | SPS: 27434 | Reward: 0.089 | Value: 0.170 | VLoss: 0.0485 | PLoss: -0.0000 | Ent: 0.6929
527
+ [ 86.4%] Iter 527/610 | SPS: 27434 | Reward: 0.084 | Value: 0.176 | VLoss: 0.0459 | PLoss: -0.0000 | Ent: 0.6929
528
+ [ 86.6%] Iter 528/610 | SPS: 27434 | Reward: 0.089 | Value: 0.170 | VLoss: 0.0495 | PLoss: 0.0000 | Ent: 0.6930
529
+ [ 86.7%] Iter 529/610 | SPS: 27434 | Reward: 0.084 | Value: 0.175 | VLoss: 0.0455 | PLoss: -0.0000 | Ent: 0.6930
530
+ [ 86.9%] Iter 530/610 | SPS: 27434 | Reward: 0.090 | Value: 0.169 | VLoss: 0.0498 | PLoss: -0.0000 | Ent: 0.6930
531
+ [ 87.0%] Iter 531/610 | SPS: 27434 | Reward: 0.087 | Value: 0.176 | VLoss: 0.0491 | PLoss: -0.0000 | Ent: 0.6930
532
+ [ 87.2%] Iter 532/610 | SPS: 27434 | Reward: 0.089 | Value: 0.175 | VLoss: 0.0454 | PLoss: -0.0000 | Ent: 0.6930
533
+ [ 87.4%] Iter 533/610 | SPS: 27435 | Reward: 0.085 | Value: 0.179 | VLoss: 0.0453 | PLoss: -0.0000 | Ent: 0.6930
534
+ [ 87.5%] Iter 534/610 | SPS: 27436 | Reward: 0.086 | Value: 0.169 | VLoss: 0.0453 | PLoss: -0.0000 | Ent: 0.6930
535
+ [ 87.7%] Iter 535/610 | SPS: 27437 | Reward: 0.088 | Value: 0.170 | VLoss: 0.0470 | PLoss: -0.0000 | Ent: 0.6930
536
+ [ 87.9%] Iter 536/610 | SPS: 27438 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0485 | PLoss: -0.0000 | Ent: 0.6930
537
+ [ 88.0%] Iter 537/610 | SPS: 27425 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0468 | PLoss: 0.0000 | Ent: 0.6930
538
+ [ 88.2%] Iter 538/610 | SPS: 27411 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0455 | PLoss: 0.0000 | Ent: 0.6930
539
+ [ 88.4%] Iter 539/610 | SPS: 27412 | Reward: 0.090 | Value: 0.176 | VLoss: 0.0483 | PLoss: -0.0000 | Ent: 0.6930
540
+ [ 88.5%] Iter 540/610 | SPS: 27413 | Reward: 0.089 | Value: 0.178 | VLoss: 0.0481 | PLoss: -0.0000 | Ent: 0.6930
541
+ [ 88.7%] Iter 541/610 | SPS: 27414 | Reward: 0.090 | Value: 0.178 | VLoss: 0.0448 | PLoss: -0.0000 | Ent: 0.6930
542
+ [ 88.9%] Iter 542/610 | SPS: 27415 | Reward: 0.088 | Value: 0.179 | VLoss: 0.0474 | PLoss: 0.0000 | Ent: 0.6930
543
+ [ 89.0%] Iter 543/610 | SPS: 27416 | Reward: 0.087 | Value: 0.176 | VLoss: 0.0461 | PLoss: -0.0000 | Ent: 0.6930
544
+ [ 89.2%] Iter 544/610 | SPS: 27417 | Reward: 0.085 | Value: 0.172 | VLoss: 0.0437 | PLoss: 0.0000 | Ent: 0.6930
545
+ [ 89.3%] Iter 545/610 | SPS: 27418 | Reward: 0.088 | Value: 0.170 | VLoss: 0.0461 | PLoss: -0.0000 | Ent: 0.6930
546
+ [ 89.5%] Iter 546/610 | SPS: 27419 | Reward: 0.090 | Value: 0.174 | VLoss: 0.0489 | PLoss: -0.0000 | Ent: 0.6930
547
+ [ 89.7%] Iter 547/610 | SPS: 27420 | Reward: 0.085 | Value: 0.177 | VLoss: 0.0465 | PLoss: 0.0000 | Ent: 0.6930
548
+ [ 89.8%] Iter 548/610 | SPS: 27421 | Reward: 0.086 | Value: 0.173 | VLoss: 0.0465 | PLoss: 0.0000 | Ent: 0.6930
549
+ [ 90.0%] Iter 549/610 | SPS: 27422 | Reward: 0.091 | Value: 0.173 | VLoss: 0.0460 | PLoss: -0.0000 | Ent: 0.6930
550
+ [ 90.2%] Iter 550/610 | SPS: 27423 | Reward: 0.090 | Value: 0.179 | VLoss: 0.0502 | PLoss: -0.0000 | Ent: 0.6930
551
+ [ 90.3%] Iter 551/610 | SPS: 27423 | Reward: 0.087 | Value: 0.178 | VLoss: 0.0445 | PLoss: 0.0000 | Ent: 0.6930
552
+ [ 90.5%] Iter 552/610 | SPS: 27424 | Reward: 0.087 | Value: 0.176 | VLoss: 0.0441 | PLoss: -0.0000 | Ent: 0.6930
553
+ [ 90.7%] Iter 553/610 | SPS: 27425 | Reward: 0.090 | Value: 0.174 | VLoss: 0.0482 | PLoss: -0.0000 | Ent: 0.6930
554
+ [ 90.8%] Iter 554/610 | SPS: 27425 | Reward: 0.089 | Value: 0.177 | VLoss: 0.0478 | PLoss: 0.0000 | Ent: 0.6930
555
+ [ 91.0%] Iter 555/610 | SPS: 27425 | Reward: 0.089 | Value: 0.178 | VLoss: 0.0464 | PLoss: -0.0000 | Ent: 0.6930
556
+ [ 91.1%] Iter 556/610 | SPS: 27426 | Reward: 0.088 | Value: 0.177 | VLoss: 0.0474 | PLoss: 0.0000 | Ent: 0.6930
557
+ [ 91.3%] Iter 557/610 | SPS: 27427 | Reward: 0.091 | Value: 0.176 | VLoss: 0.0476 | PLoss: 0.0000 | Ent: 0.6930
558
+ [ 91.5%] Iter 558/610 | SPS: 27427 | Reward: 0.087 | Value: 0.178 | VLoss: 0.0465 | PLoss: 0.0000 | Ent: 0.6930
559
+ [ 91.6%] Iter 559/610 | SPS: 27428 | Reward: 0.089 | Value: 0.175 | VLoss: 0.0514 | PLoss: -0.0000 | Ent: 0.6930
560
+ [ 91.8%] Iter 560/610 | SPS: 27429 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0475 | PLoss: -0.0000 | Ent: 0.6930
561
+ [ 92.0%] Iter 561/610 | SPS: 27430 | Reward: 0.087 | Value: 0.178 | VLoss: 0.0456 | PLoss: -0.0000 | Ent: 0.6930
562
+ [ 92.1%] Iter 562/610 | SPS: 27431 | Reward: 0.089 | Value: 0.173 | VLoss: 0.0476 | PLoss: 0.0000 | Ent: 0.6930
563
+ [ 92.3%] Iter 563/610 | SPS: 27432 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0485 | PLoss: -0.0000 | Ent: 0.6930
564
+ [ 92.5%] Iter 564/610 | SPS: 27432 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0457 | PLoss: 0.0000 | Ent: 0.6929
565
+ [ 92.6%] Iter 565/610 | SPS: 27433 | Reward: 0.088 | Value: 0.178 | VLoss: 0.0472 | PLoss: -0.0000 | Ent: 0.6930
566
+ [ 92.8%] Iter 566/610 | SPS: 27434 | Reward: 0.087 | Value: 0.178 | VLoss: 0.0483 | PLoss: -0.0000 | Ent: 0.6929
567
+ [ 93.0%] Iter 567/610 | SPS: 27435 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0465 | PLoss: 0.0000 | Ent: 0.6929
568
+ [ 93.1%] Iter 568/610 | SPS: 27436 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0460 | PLoss: -0.0000 | Ent: 0.6929
569
+ [ 93.3%] Iter 569/610 | SPS: 27437 | Reward: 0.087 | Value: 0.172 | VLoss: 0.0463 | PLoss: 0.0000 | Ent: 0.6929
570
+ [ 93.4%] Iter 570/610 | SPS: 27438 | Reward: 0.084 | Value: 0.173 | VLoss: 0.0439 | PLoss: -0.0000 | Ent: 0.6930
571
+ [ 93.6%] Iter 571/610 | SPS: 27438 | Reward: 0.087 | Value: 0.172 | VLoss: 0.0489 | PLoss: -0.0000 | Ent: 0.6930
572
+ [ 93.8%] Iter 572/610 | SPS: 27438 | Reward: 0.090 | Value: 0.172 | VLoss: 0.0475 | PLoss: -0.0000 | Ent: 0.6929
573
+ [ 93.9%] Iter 573/610 | SPS: 27439 | Reward: 0.087 | Value: 0.176 | VLoss: 0.0457 | PLoss: 0.0000 | Ent: 0.6929
574
+ [ 94.1%] Iter 574/610 | SPS: 27440 | Reward: 0.087 | Value: 0.175 | VLoss: 0.0470 | PLoss: -0.0000 | Ent: 0.6929
575
+ [ 94.3%] Iter 575/610 | SPS: 27441 | Reward: 0.087 | Value: 0.173 | VLoss: 0.0501 | PLoss: 0.0000 | Ent: 0.6929
576
+ [ 94.4%] Iter 576/610 | SPS: 27441 | Reward: 0.090 | Value: 0.172 | VLoss: 0.0486 | PLoss: -0.0000 | Ent: 0.6929
577
+ [ 94.6%] Iter 577/610 | SPS: 27442 | Reward: 0.090 | Value: 0.175 | VLoss: 0.0478 | PLoss: 0.0000 | Ent: 0.6929
578
+ [ 94.8%] Iter 578/610 | SPS: 27443 | Reward: 0.089 | Value: 0.178 | VLoss: 0.0482 | PLoss: -0.0000 | Ent: 0.6929
579
+ [ 94.9%] Iter 579/610 | SPS: 27444 | Reward: 0.087 | Value: 0.179 | VLoss: 0.0445 | PLoss: -0.0000 | Ent: 0.6929
580
+ [ 95.1%] Iter 580/610 | SPS: 27444 | Reward: 0.091 | Value: 0.176 | VLoss: 0.0498 | PLoss: 0.0000 | Ent: 0.6929
581
+ [ 95.2%] Iter 581/610 | SPS: 27445 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0444 | PLoss: -0.0000 | Ent: 0.6929
582
+ [ 95.4%] Iter 582/610 | SPS: 27446 | Reward: 0.085 | Value: 0.175 | VLoss: 0.0453 | PLoss: -0.0000 | Ent: 0.6929
583
+ [ 95.6%] Iter 583/610 | SPS: 27447 | Reward: 0.088 | Value: 0.173 | VLoss: 0.0467 | PLoss: 0.0000 | Ent: 0.6929
584
+ [ 95.7%] Iter 584/610 | SPS: 27448 | Reward: 0.085 | Value: 0.174 | VLoss: 0.0472 | PLoss: -0.0000 | Ent: 0.6929
585
+ [ 95.9%] Iter 585/610 | SPS: 27449 | Reward: 0.086 | Value: 0.173 | VLoss: 0.0439 | PLoss: -0.0000 | Ent: 0.6930
586
+ [ 96.1%] Iter 586/610 | SPS: 27450 | Reward: 0.088 | Value: 0.171 | VLoss: 0.0471 | PLoss: 0.0000 | Ent: 0.6930
587
+ [ 96.2%] Iter 587/610 | SPS: 27450 | Reward: 0.088 | Value: 0.172 | VLoss: 0.0473 | PLoss: -0.0000 | Ent: 0.6930
588
+ [ 96.4%] Iter 588/610 | SPS: 27450 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0442 | PLoss: -0.0000 | Ent: 0.6930
589
+ [ 96.6%] Iter 589/610 | SPS: 27450 | Reward: 0.090 | Value: 0.174 | VLoss: 0.0485 | PLoss: 0.0000 | Ent: 0.6930
590
+ [ 96.7%] Iter 590/610 | SPS: 27451 | Reward: 0.090 | Value: 0.175 | VLoss: 0.0495 | PLoss: -0.0000 | Ent: 0.6930
591
+ [ 96.9%] Iter 591/610 | SPS: 27452 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0497 | PLoss: -0.0000 | Ent: 0.6930
592
+ [ 97.0%] Iter 592/610 | SPS: 27452 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0465 | PLoss: 0.0000 | Ent: 0.6930
593
+ [ 97.2%] Iter 593/610 | SPS: 27453 | Reward: 0.089 | Value: 0.176 | VLoss: 0.0471 | PLoss: 0.0000 | Ent: 0.6930
594
+ [ 97.4%] Iter 594/610 | SPS: 27454 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0463 | PLoss: -0.0000 | Ent: 0.6930
595
+ [ 97.5%] Iter 595/610 | SPS: 27454 | Reward: 0.088 | Value: 0.176 | VLoss: 0.0476 | PLoss: 0.0000 | Ent: 0.6930
596
+ [ 97.7%] Iter 596/610 | SPS: 27455 | Reward: 0.088 | Value: 0.175 | VLoss: 0.0443 | PLoss: -0.0000 | Ent: 0.6930
597
+ [ 97.9%] Iter 597/610 | SPS: 27456 | Reward: 0.085 | Value: 0.175 | VLoss: 0.0451 | PLoss: -0.0000 | Ent: 0.6930
598
+ [ 98.0%] Iter 598/610 | SPS: 27457 | Reward: 0.085 | Value: 0.174 | VLoss: 0.0448 | PLoss: -0.0000 | Ent: 0.6930
599
+ [ 98.2%] Iter 599/610 | SPS: 27458 | Reward: 0.085 | Value: 0.173 | VLoss: 0.0455 | PLoss: -0.0000 | Ent: 0.6930
600
+ [ 98.4%] Iter 600/610 | SPS: 27458 | Reward: 0.086 | Value: 0.172 | VLoss: 0.0471 | PLoss: -0.0000 | Ent: 0.6930
601
+ [ 98.5%] Iter 601/610 | SPS: 27459 | Reward: 0.085 | Value: 0.172 | VLoss: 0.0451 | PLoss: -0.0000 | Ent: 0.6930
602
+ [ 98.7%] Iter 602/610 | SPS: 27460 | Reward: 0.084 | Value: 0.172 | VLoss: 0.0445 | PLoss: 0.0000 | Ent: 0.6930
603
+ [ 98.9%] Iter 603/610 | SPS: 27460 | Reward: 0.093 | Value: 0.171 | VLoss: 0.0519 | PLoss: -0.0000 | Ent: 0.6930
604
+ [ 99.0%] Iter 604/610 | SPS: 27461 | Reward: 0.088 | Value: 0.172 | VLoss: 0.0478 | PLoss: -0.0000 | Ent: 0.6930
605
+ [ 99.2%] Iter 605/610 | SPS: 27461 | Reward: 0.086 | Value: 0.174 | VLoss: 0.0453 | PLoss: -0.0000 | Ent: 0.6930
606
+ [ 99.3%] Iter 606/610 | SPS: 27461 | Reward: 0.089 | Value: 0.174 | VLoss: 0.0493 | PLoss: -0.0000 | Ent: 0.6930
607
+ [ 99.5%] Iter 607/610 | SPS: 27462 | Reward: 0.089 | Value: 0.174 | VLoss: 0.0473 | PLoss: -0.0000 | Ent: 0.6930
608
+ [ 99.7%] Iter 608/610 | SPS: 27463 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0465 | PLoss: -0.0000 | Ent: 0.6930
609
+ [ 99.8%] Iter 609/610 | SPS: 27463 | Reward: 0.088 | Value: 0.174 | VLoss: 0.0465 | PLoss: 0.0000 | Ent: 0.6930
610
+ [100.0%] Iter 610/610 | SPS: 27464 | Reward: 0.087 | Value: 0.174 | VLoss: 0.0440 | PLoss: 0.0000 | Ent: 0.6930
cleanrl/cleanrl/wandb/run-20251107_100911-8xuf7idy/files/requirements.txt ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ragen==0.1
2
+ setuptools==80.9.0
3
+ wheel==0.45.1
4
+ pip==25.2
5
+ zipp==3.23.0
6
+ verl==0.2.0.dev0
7
+ ragen==0.1
8
+ triton==3.2.0
9
+ nvidia-cusparselt-cu12==0.6.2
10
+ mpmath==1.3.0
11
+ typing_extensions==4.15.0
12
+ sympy==1.13.1
13
+ nvidia-nvtx-cu12==12.4.127
14
+ nvidia-nvjitlink-cu12==12.4.127
15
+ nvidia-nccl-cu12==2.21.5
16
+ nvidia-curand-cu12==10.3.5.147
17
+ nvidia-cufft-cu12==11.2.1.3
18
+ nvidia-cuda-runtime-cu12==12.4.127
19
+ nvidia-cuda-nvrtc-cu12==12.4.127
20
+ nvidia-cuda-cupti-cu12==12.4.127
21
+ nvidia-cublas-cu12==12.4.5.8
22
+ networkx==3.5
23
+ MarkupSafe==2.1.5
24
+ fsspec==2025.9.0
25
+ filelock==3.19.1
26
+ nvidia-cusparse-cu12==12.3.1.170
27
+ nvidia-cudnn-cu12==9.1.0.70
28
+ Jinja2==3.1.6
29
+ nvidia-cusolver-cu12==11.6.1.9
30
+ torch==2.6.0+cu124
31
+ einops==0.8.1
32
+ flash_attn==2.7.4.post1
33
+ pytz==2025.2
34
+ pyperclip==1.11.0
35
+ pylatexenc==2.10
36
+ pyjnius==1.7.0
37
+ py-cpuinfo==9.0.0
38
+ pure_eval==0.2.3
39
+ ptyprocess==0.7.0
40
+ gym-notices==0.1.0
41
+ flatbuffers==25.9.23
42
+ fastrlock==0.8.3
43
+ Farama-Notifications==0.0.4
44
+ cymem==2.0.11
45
+ antlr4-python3-runtime==4.9.3
46
+ xxhash==3.6.0
47
+ wrapt==2.0.0
48
+ Werkzeug==3.1.3
49
+ websockets==15.0.1
50
+ wcwidth==0.2.14
51
+ wasabi==1.1.3
52
+ uvloop==0.22.1
53
+ urllib3==2.5.0
54
+ tzdata==2025.2
55
+ typing-inspection==0.4.2
56
+ traitlets==5.14.3
57
+ tqdm==4.67.1
58
+ threadpoolctl==3.6.0
59
+ tabulate==0.9.0
60
+ spacy-loggers==1.0.5
61
+ spacy-legacy==3.0.12
62
+ soupsieve==2.8
63
+ sniffio==1.3.1
64
+ smmap==5.0.2
65
+ six==1.17.0
66
+ shellingham==1.5.4
67
+ sentencepiece==0.2.1
68
+ safetensors==0.6.2
69
+ rpds-py==0.28.0
70
+ rignore==0.7.6
71
+ regex==2025.11.3
72
+ RapidFuzz==3.14.3
73
+ pyzmq==27.1.0
74
+ PyYAML==6.0.3
75
+ pytokens==0.3.0
76
+ python-multipart==0.0.20
77
+ python-json-logger==4.0.0
78
+ python-dotenv==1.2.1
79
+ PySocks==1.7.1
80
+ pyparsing==3.2.5
81
+ PyJWT==2.10.1
82
+ Pygments==2.19.2
83
+ pygame==2.6.1
84
+ pydantic_core==2.41.5
85
+ pycparser==2.23
86
+ pycountry==24.6.1
87
+ pybind11==3.0.1
88
+ pyarrow==22.0.0
89
+ psutil==7.1.3
90
+ protobuf==6.33.0
91
+ propcache==0.4.1
92
+ prometheus_client==0.23.1
93
+ platformdirs==4.5.0
94
+ pillow==11.3.0
95
+ pexpect==4.9.0
96
+ pathvalidate==3.3.1
97
+ pathspec==0.12.1
98
+ pathable==0.4.4
99
+ partial-json-parser==0.2.1.1.post6
100
+ parso==0.8.5
101
+ packaging==25.0
102
+ orjson==3.11.4
103
+ numpy==1.26.4
104
+ ninja==1.13.0
105
+ nest-asyncio==1.6.0
106
+ mypy_extensions==1.1.0
107
+ murmurhash==1.0.13
108
+ multidict==6.7.0
109
+ msgspec==0.19.0
110
+ msgpack==1.1.2
111
+ more-itertools==10.8.0
112
+ mdurl==0.1.2
113
+ marisa-trie==1.3.1
114
+ llvmlite==0.43.0
115
+ llguidance==0.7.30
116
+ lark==1.2.2
117
+ kiwisolver==1.4.9
118
+ joblib==1.5.2
119
+ jiter==0.11.1
120
+ jeepney==0.9.0
121
+ jaraco.context==6.0.1
122
+ itsdangerous==2.2.0
123
+ interegular==0.3.3
124
+ idna==3.11
125
+ humanfriendly==10.0
126
+ httpx-sse==0.4.3
127
+ httptools==0.7.1
128
+ html2text==2025.4.15
129
+ hf-xet==1.2.0
130
+ h11==0.16.0
131
+ frozenlist==1.8.0
132
+ fonttools==4.60.1
133
+ executing==2.2.1
134
+ exceptiongroup==1.3.0
135
+ eval_type_backport==0.2.2
136
+ docutils==0.22.3
137
+ docstring_parser==0.17.0
138
+ dnspython==2.8.0
139
+ distro==1.9.0
140
+ diskcache==5.6.3
141
+ dill==0.4.0
142
+ decorator==5.2.1
143
+ debugpy==1.8.17
144
+ Cython==3.2.0
145
+ cycler==0.12.1
146
+ codetiming==1.4.0
147
+ cloudpickle==3.1.2
148
+ cloudpathlib==0.23.0
149
+ click==8.2.1
150
+ charset-normalizer==3.4.4
151
+ certifi==2025.10.5
152
+ catalogue==2.0.10
153
+ cachetools==6.2.1
154
+ blinker==1.9.0
155
+ blake3==1.0.8
156
+ beartype==0.22.5
157
+ attrs==25.4.0
158
+ asttokens==3.0.0
159
+ astor==0.8.1
160
+ annotated-types==0.7.0
161
+ annotated-doc==0.0.3
162
+ airportsdata==20250909
163
+ aiohappyeyeballs==2.6.1
164
+ yarl==1.22.0
165
+ uvicorn==0.38.0
166
+ typer-slim==0.20.0
167
+ thefuzz==0.22.1
168
+ stack-data==0.6.3
169
+ srsly==2.5.1
170
+ smart_open==7.4.4
171
+ sentry-sdk==2.43.0
172
+ scipy==1.16.3
173
+ requests==2.32.5
174
+ referencing==0.36.2
175
+ rank-bm25==0.2.2
176
+ python-dateutil==2.9.0.post0
177
+ pydantic==2.12.4
178
+ py-key-value-shared==0.2.8
179
+ prompt_toolkit==3.0.52
180
+ preshed==3.0.10
181
+ opencv-python-headless==4.11.0.86
182
+ omegaconf==2.3.0
183
+ numba==0.60.0
184
+ nltk==3.9.2
185
+ multiprocess==0.70.18
186
+ matplotlib-inline==0.2.1
187
+ markdown-it-py==4.0.0
188
+ language_data==1.3.0
189
+ jedi==0.19.2
190
+ jaraco.functools==4.3.0
191
+ jaraco.classes==3.4.0
192
+ ipython_pygments_lexers==1.1.1
193
+ importlib_metadata==8.7.0
194
+ ImageIO==2.37.2
195
+ httpcore==1.0.9
196
+ gymnasium==1.2.2
197
+ gym==0.26.2
198
+ gitdb==4.0.12
199
+ gguf==0.10.0
200
+ Flask==3.1.2
201
+ faiss-cpu==1.12.0
202
+ email-validator==2.3.0
203
+ depyf==0.18.0
204
+ cupy-cuda12x==13.6.0
205
+ contourpy==1.3.3
206
+ coloredlogs==15.0.1
207
+ cffi==2.0.0
208
+ blis==1.3.0
209
+ black==25.9.0
210
+ beautifulsoup4==4.14.2
211
+ anyio==4.11.0
212
+ aiosignal==1.4.0
213
+ watchfiles==1.1.1
214
+ tiktoken==0.12.0
215
+ starlette==0.49.3
216
+ sse-starlette==3.0.3
217
+ scikit-learn==1.7.2
218
+ rich==14.2.0
219
+ pydantic-settings==2.11.0
220
+ pydantic-extra-types==2.10.6
221
+ py-key-value-aio==0.2.8
222
+ pandas==2.3.3
223
+ openapi-pydantic==0.5.1
224
+ onnxruntime==1.23.2
225
+ matplotlib==3.10.7
226
+ lm-format-enforcer==0.10.12
227
+ langcodes==3.5.0
228
+ jsonschema-specifications==2025.9.1
229
+ jsonschema-path==0.3.4
230
+ ipython==9.7.0
231
+ hydra-core==1.3.2
232
+ huggingface-hub==0.36.0
233
+ httpx==0.28.1
234
+ gym-sokoban==0.0.6
235
+ GitPython==3.1.45
236
+ cryptography==46.0.3
237
+ confection==0.1.5
238
+ cleantext==1.1.4
239
+ aiohttp==3.13.2
240
+ xformers==0.0.29.post2
241
+ weasel==0.4.2
242
+ wandb==0.22.3
243
+ typer==0.19.2
244
+ torchvision==0.21.0
245
+ torchdata==0.11.0
246
+ torchaudio==2.6.0
247
+ tokenizers==0.22.1
248
+ thinc==8.3.7
249
+ tensordict==0.8.3
250
+ SecretStorage==3.4.0
251
+ rich-toolkit==0.15.1
252
+ rich-rst==1.3.2
253
+ prometheus-fastapi-instrumentator==7.1.0
254
+ openai==2.7.1
255
+ jsonschema==4.25.1
256
+ gdown==5.2.0
257
+ fastapi==0.121.0
258
+ Authlib==1.6.5
259
+ anthropic==0.72.0
260
+ accelerate==1.11.0
261
+ transformers==4.57.1
262
+ together==1.5.30
263
+ spacy==3.8.7
264
+ ray==2.51.1
265
+ outlines_core==0.1.26
266
+ mistral_common==1.8.5
267
+ mcp==1.20.0
268
+ keyring==25.6.0
269
+ fastapi-cloud-cli==0.3.1
270
+ fastapi-cli==0.0.14
271
+ datasets==4.4.1
272
+ cyclopts==4.2.1
273
+ xgrammar==0.1.16
274
+ peft==0.17.1
275
+ outlines==0.1.11
276
+ compressed-tensors==0.9.2
277
+ fastmcp==2.13.0.2
278
+ vllm==0.8.2
279
+ pyserini==1.3.0
280
+ typeguard==4.4.4
281
+ shtab==1.7.2
282
+ tyro==0.9.35
283
+ tensorboard-data-server==0.7.2
284
+ Markdown==3.10
285
+ grpcio==1.76.0
286
+ absl-py==2.3.1
287
+ tensorboard==2.20.0
288
+ ragen==0.1
289
+ verl==0.2.0.dev0
290
+ autocommand==2.2.2
291
+ backports.tarfile==1.2.0
292
+ importlib_metadata==8.0.0
293
+ inflect==7.3.1
294
+ jaraco.collections==5.1.0
295
+ jaraco.context==5.3.0
296
+ jaraco.functools==4.0.1
297
+ jaraco.text==3.12.1
298
+ more-itertools==10.3.0
299
+ packaging==24.2
300
+ platformdirs==4.2.2
301
+ tomli==2.0.1
302
+ typeguard==4.3.0
303
+ typing_extensions==4.12.2
304
+ wheel==0.45.1
305
+ zipp==3.19.2
cleanrl/cleanrl/wandb/run-20251107_100911-8xuf7idy/logs/debug-internal.log ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"time":"2025-11-07T10:09:11.966826198+08:00","level":"INFO","msg":"stream: starting","core version":"0.22.3"}
2
+ {"time":"2025-11-07T10:09:12.342225544+08:00","level":"INFO","msg":"stream: created new stream","id":"8xuf7idy"}
3
+ {"time":"2025-11-07T10:09:12.342405699+08:00","level":"INFO","msg":"handler: started","stream_id":"8xuf7idy"}
4
+ {"time":"2025-11-07T10:09:12.345368242+08:00","level":"INFO","msg":"stream: started","id":"8xuf7idy"}
5
+ {"time":"2025-11-07T10:09:12.345387564+08:00","level":"INFO","msg":"writer: started","stream_id":"8xuf7idy"}
6
+ {"time":"2025-11-07T10:09:12.345394576+08:00","level":"INFO","msg":"sender: started","stream_id":"8xuf7idy"}
7
+ {"time":"2025-11-07T10:09:12.675299434+08:00","level":"ERROR","msg":"git repo not found","error":"repository does not exist"}
8
+ {"time":"2025-11-07T10:09:22.810401519+08:00","level":"WARN","msg":"tensorboard: no root directory","error":"timed out after 10s"}
9
+ {"time":"2025-11-07T10:09:22.811137223+08:00","level":"INFO","msg":"tensorboard: tracking new log directory","rootDir":{},"logDir":"LocalOrCloudPath(LocalPath=\"/mnt/general/wanghy/RAGEN/cleanrl/cleanrl/runs/Bandit__ppo_bandit__1__1762481344\")","namespace":""}
10
+ {"time":"2025-11-07T10:09:22.812700965+08:00","level":"INFO","msg":"tensorboard: saving file","fileLocation":"/mnt/general/wanghy/RAGEN/cleanrl/cleanrl/runs/Bandit__ppo_bandit__1__1762481344/events.out.tfevents.1762481352.pt-4d654cf4576f4d23ad3d3919f12932fe-worker-0.131665.0","runPath":"runs/Bandit__ppo_bandit__1__1762481344/events.out.tfevents.1762481352.pt-4d654cf4576f4d23ad3d3919f12932fe-worker-0.131665.0"}
11
+ {"time":"2025-11-07T10:09:22.81544715+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":82}
12
+ {"time":"2025-11-07T10:09:22.81554868+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
13
+ {"time":"2025-11-07T10:09:22.815598042+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":114}
14
+ {"time":"2025-11-07T10:09:22.818968124+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":428}
15
+ {"time":"2025-11-07T10:09:27.822509065+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":594}
16
+ {"time":"2025-11-07T10:09:28.148323264+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":281}
17
+ {"time":"2025-11-07T10:09:32.828622741+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":925}
18
+ {"time":"2025-11-07T10:09:32.828726578+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
19
+ {"time":"2025-11-07T10:09:32.829137611+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":957}
20
+ {"time":"2025-11-07T10:09:32.831661291+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":285}
21
+ {"time":"2025-11-07T10:09:42.842979832+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":1623}
22
+ {"time":"2025-11-07T10:09:43.158591355+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":318}
23
+ {"time":"2025-11-07T10:09:47.848778763+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":2085}
24
+ {"time":"2025-11-07T10:09:47.848872784+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
25
+ {"time":"2025-11-07T10:09:47.849368143+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":2117}
26
+ {"time":"2025-11-07T10:09:47.853329609+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":152}
27
+ {"time":"2025-11-07T10:09:52.855987214+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":2320}
28
+ {"time":"2025-11-07T10:09:52.856056786+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
29
+ {"time":"2025-11-07T10:09:52.856467985+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":2352}
30
+ {"time":"2025-11-07T10:09:52.858961503+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":245}
31
+ {"time":"2025-11-07T10:09:57.862444736+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":2650}
32
+ {"time":"2025-11-07T10:09:58.175098246+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":318}
33
+ {"time":"2025-11-07T10:10:02.869141467+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":3018}
34
+ {"time":"2025-11-07T10:10:02.869227383+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
35
+ {"time":"2025-11-07T10:10:02.86975056+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":3050}
36
+ {"time":"2025-11-07T10:10:02.872366834+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":246}
37
+ {"time":"2025-11-07T10:10:07.876457838+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":3347}
38
+ {"time":"2025-11-07T10:10:07.876575967+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
39
+ {"time":"2025-11-07T10:10:07.876891994+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":3379}
40
+ {"time":"2025-11-07T10:10:07.87944904+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":286}
41
+ {"time":"2025-11-07T10:10:12.882750276+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":3716}
42
+ {"time":"2025-11-07T10:10:13.072297571+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":279}
43
+ {"time":"2025-11-07T10:10:22.896229902+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":4414}
44
+ {"time":"2025-11-07T10:10:22.896340216+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
45
+ {"time":"2025-11-07T10:10:22.896744337+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":4446}
46
+ {"time":"2025-11-07T10:10:22.900121026+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":246}
47
+ {"time":"2025-11-07T10:10:27.904510442+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":4743}
48
+ {"time":"2025-11-07T10:10:28.157449561+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":320}
49
+ {"time":"2025-11-07T10:10:32.931281796+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":5123}
50
+ {"time":"2025-11-07T10:10:32.931391826+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
51
+ {"time":"2025-11-07T10:10:32.931855488+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":5155}
52
+ {"time":"2025-11-07T10:10:32.935989943+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":236}
53
+ {"time":"2025-11-07T10:10:37.938755169+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":5440}
54
+ {"time":"2025-11-07T10:10:37.93888417+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
55
+ {"time":"2025-11-07T10:10:37.939237843+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":5472}
56
+ {"time":"2025-11-07T10:10:37.94204248+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":247}
57
+ {"time":"2025-11-07T10:10:42.945142652+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":5772}
58
+ {"time":"2025-11-07T10:10:43.099123604+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":318}
59
+ {"time":"2025-11-07T10:10:47.954626916+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":6265}
60
+ {"time":"2025-11-07T10:10:47.954706268+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
61
+ {"time":"2025-11-07T10:10:47.955184557+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":6297}
62
+ {"time":"2025-11-07T10:10:47.956394614+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":121}
63
+ {"time":"2025-11-07T10:10:52.960924481+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":6614}
64
+ {"time":"2025-11-07T10:10:52.960980558+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
65
+ {"time":"2025-11-07T10:10:52.961444009+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":6646}
66
+ {"time":"2025-11-07T10:10:52.963630532+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":141}
67
+ {"time":"2025-11-07T10:10:57.967852858+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":6838}
68
+ {"time":"2025-11-07T10:10:58.06695384+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":279}
69
+ {"time":"2025-11-07T10:11:02.974120659+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":7168}
70
+ {"time":"2025-11-07T10:11:02.974241971+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
71
+ {"time":"2025-11-07T10:11:02.975227134+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":7201}
72
+ {"time":"2025-11-07T10:11:02.977256695+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":285}
73
+ {"time":"2025-11-07T10:11:07.980152756+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":7568}
74
+ {"time":"2025-11-07T10:11:07.980229786+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
75
+ {"time":"2025-11-07T10:11:07.980707581+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":7600}
76
+ {"time":"2025-11-07T10:11:07.982877998+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":155}
77
+ {"time":"2025-11-07T10:11:12.994240702+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":7824}
78
+ {"time":"2025-11-07T10:11:13.160351751+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":279}
79
+ {"time":"2025-11-07T10:11:18.002699541+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":8154}
80
+ {"time":"2025-11-07T10:11:18.002788149+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
81
+ {"time":"2025-11-07T10:11:18.003229269+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":8186}
82
+ {"time":"2025-11-07T10:11:18.005808172+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":245}
83
+ {"time":"2025-11-07T10:11:23.010421518+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":8483}
84
+ {"time":"2025-11-07T10:11:23.014679182+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":317}
85
+ {"time":"2025-11-07T10:11:28.019757498+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":8851}
86
+ {"time":"2025-11-07T10:11:28.075431015+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":281}
87
+ {"time":"2025-11-07T10:11:33.026553411+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":9192}
88
+ {"time":"2025-11-07T10:11:33.026624538+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
89
+ {"time":"2025-11-07T10:11:33.027141253+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":9224}
90
+ {"time":"2025-11-07T10:11:33.031451151+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":275}
91
+ {"time":"2025-11-07T10:11:38.038561028+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":9601}
92
+ {"time":"2025-11-07T10:11:38.038678348+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
93
+ {"time":"2025-11-07T10:11:38.039027821+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":9633}
94
+ {"time":"2025-11-07T10:11:38.040504549+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":194}
95
+ {"time":"2025-11-07T10:11:43.046677526+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":9877}
96
+ {"time":"2025-11-07T10:11:43.06573047+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":321}
97
+ {"time":"2025-11-07T10:11:48.053736852+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":10304}
98
+ {"time":"2025-11-07T10:11:48.053803012+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
99
+ {"time":"2025-11-07T10:11:48.054938099+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":10337}
100
+ {"time":"2025-11-07T10:11:48.05666238+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":189}
101
+ {"time":"2025-11-07T10:11:53.060888105+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":10665}
102
+ {"time":"2025-11-07T10:11:53.060944679+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
103
+ {"time":"2025-11-07T10:11:53.061391772+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":10697}
104
+ {"time":"2025-11-07T10:11:53.063097501+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":157}
105
+ {"time":"2025-11-07T10:12:03.092667398+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":11335}
106
+ {"time":"2025-11-07T10:12:03.092721576+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
107
+ {"time":"2025-11-07T10:12:03.093163508+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":11367}
108
+ {"time":"2025-11-07T10:12:03.094999483+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":186}
109
+ {"time":"2025-11-07T10:12:08.100540689+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":11603}
110
+ {"time":"2025-11-07T10:12:08.100683211+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
111
+ {"time":"2025-11-07T10:12:08.101093087+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":11635}
112
+ {"time":"2025-11-07T10:12:08.104101991+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":246}
113
+ {"time":"2025-11-07T10:12:13.108627845+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":11932}
114
+ {"time":"2025-11-07T10:12:13.112796809+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":320}
115
+ {"time":"2025-11-07T10:12:23.120208627+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":12631}
116
+ {"time":"2025-11-07T10:12:23.120349654+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
117
+ {"time":"2025-11-07T10:12:23.120842427+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":12663}
118
+ {"time":"2025-11-07T10:12:23.123194297+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":286}
119
+ {"time":"2025-11-07T10:12:28.127063984+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":13071}
120
+ {"time":"2025-11-07T10:12:28.127126888+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
121
+ {"time":"2025-11-07T10:12:28.12753951+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":13103}
122
+ {"time":"2025-11-07T10:12:28.129156841+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":176}
123
+ {"time":"2025-11-07T10:12:33.134846093+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":13351}
124
+ {"time":"2025-11-07T10:12:33.134932231+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
125
+ {"time":"2025-11-07T10:12:33.135304256+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":13383}
126
+ {"time":"2025-11-07T10:12:33.137691215+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":232}
127
+ {"time":"2025-11-07T10:12:38.158698045+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":13813}
128
+ {"time":"2025-11-07T10:12:38.158793146+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
129
+ {"time":"2025-11-07T10:12:38.159214256+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":13845}
130
+ {"time":"2025-11-07T10:12:38.160537232+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":131}
131
+ {"time":"2025-11-07T10:12:43.165062325+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":14028}
132
+ {"time":"2025-11-07T10:12:43.165152442+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
133
+ {"time":"2025-11-07T10:12:43.165644175+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":14060}
134
+ {"time":"2025-11-07T10:12:43.167545893+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":246}
135
+ {"time":"2025-11-07T10:12:48.171489906+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":14357}
136
+ {"time":"2025-11-07T10:12:48.171688673+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
137
+ {"time":"2025-11-07T10:12:48.171984157+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":14389}
138
+ {"time":"2025-11-07T10:12:48.175462994+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":286}
139
+ {"time":"2025-11-07T10:12:53.180918259+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":14725}
140
+ {"time":"2025-11-07T10:12:53.181009051+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
141
+ {"time":"2025-11-07T10:12:53.181407852+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":14757}
142
+ {"time":"2025-11-07T10:12:53.184249723+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":246}
143
+ {"time":"2025-11-07T10:12:58.188596289+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":15084}
144
+ {"time":"2025-11-07T10:12:58.188658496+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
145
+ {"time":"2025-11-07T10:12:58.189076631+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":15116}
146
+ {"time":"2025-11-07T10:12:58.192681825+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":258}
147
+ {"time":"2025-11-07T10:13:03.196504848+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":15424}
148
+ {"time":"2025-11-07T10:13:03.196630701+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
149
+ {"time":"2025-11-07T10:13:03.197098842+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":15456}
150
+ {"time":"2025-11-07T10:13:03.199929985+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":246}
151
+ {"time":"2025-11-07T10:13:18.221423379+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":16509}
152
+ {"time":"2025-11-07T10:13:18.221494321+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
153
+ {"time":"2025-11-07T10:13:18.221921307+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":16541}
154
+ {"time":"2025-11-07T10:13:18.223883783+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":188}
155
+ {"time":"2025-11-07T10:13:23.228308162+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":16783}
156
+ {"time":"2025-11-07T10:13:23.228453474+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
157
+ {"time":"2025-11-07T10:13:23.228727631+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":16815}
158
+ {"time":"2025-11-07T10:13:23.231666988+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":283}
159
+ {"time":"2025-11-07T10:13:28.236219887+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":17300}
160
+ {"time":"2025-11-07T10:13:28.236298051+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
161
+ {"time":"2025-11-07T10:13:28.23665126+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":17332}
162
+ {"time":"2025-11-07T10:13:28.237811871+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":96}
163
+ {"time":"2025-11-07T10:13:43.258714416+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":18213}
164
+ {"time":"2025-11-07T10:13:43.25885979+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
165
+ {"time":"2025-11-07T10:13:43.259500985+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":18245}
166
+ {"time":"2025-11-07T10:13:43.261236795+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":210}
167
+ {"time":"2025-11-07T10:13:48.265158923+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":18543}
168
+ {"time":"2025-11-07T10:13:48.265336635+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
169
+ {"time":"2025-11-07T10:13:48.265752339+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":18575}
170
+ {"time":"2025-11-07T10:13:48.268370012+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":249}
171
+ {"time":"2025-11-07T10:13:53.272195814+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":18874}
172
+ {"time":"2025-11-07T10:13:53.272328834+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
173
+ {"time":"2025-11-07T10:13:53.272671318+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":18906}
174
+ {"time":"2025-11-07T10:13:53.276471403+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":246}
175
+ {"time":"2025-11-07T10:13:58.280327443+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":19305}
176
+ {"time":"2025-11-07T10:13:58.280391127+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
177
+ {"time":"2025-11-07T10:13:58.280757709+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":19337}
178
+ {"time":"2025-11-07T10:13:58.282286802+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":186}
179
+ {"time":"2025-11-07T10:14:08.294534894+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":19952}
180
+ {"time":"2025-11-07T10:14:08.294635147+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
181
+ {"time":"2025-11-07T10:14:08.295007424+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":19984}
182
+ {"time":"2025-11-07T10:14:08.297041354+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":195}
183
+ {"time":"2025-11-07T10:14:13.301996538+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":20232}
184
+ {"time":"2025-11-07T10:14:13.302158576+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
185
+ {"time":"2025-11-07T10:14:13.302951633+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":20265}
186
+ {"time":"2025-11-07T10:14:13.305004383+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":285}
187
+ {"time":"2025-11-07T10:14:18.310228549+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":20599}
188
+ {"time":"2025-11-07T10:14:18.310322321+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
189
+ {"time":"2025-11-07T10:14:18.310676475+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":20631}
190
+ {"time":"2025-11-07T10:14:18.313232224+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":247}
191
+ {"time":"2025-11-07T10:14:23.317720376+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":20929}
192
+ {"time":"2025-11-07T10:14:23.317866228+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
193
+ {"time":"2025-11-07T10:14:23.318198118+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":20961}
194
+ {"time":"2025-11-07T10:14:23.320943116+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":286}
195
+ {"time":"2025-11-07T10:14:28.327603484+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":21496}
196
+ {"time":"2025-11-07T10:14:28.327687895+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
197
+ {"time":"2025-11-07T10:14:28.328049086+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":21528}
198
+ {"time":"2025-11-07T10:14:28.328828301+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":49}
199
+ {"time":"2025-11-07T10:14:33.333285025+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":21630}
200
+ {"time":"2025-11-07T10:14:33.33337794+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
201
+ {"time":"2025-11-07T10:14:33.333778835+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":21662}
202
+ {"time":"2025-11-07T10:14:33.337830594+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":284}
203
+ {"time":"2025-11-07T10:14:38.341518497+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":22142}
204
+ {"time":"2025-11-07T10:14:38.341578698+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
205
+ {"time":"2025-11-07T10:14:38.342096344+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":22174}
206
+ {"time":"2025-11-07T10:14:38.34310572+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":100}
207
+ {"time":"2025-11-07T10:14:43.348258984+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":22497}
208
+ {"time":"2025-11-07T10:14:43.348347545+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
209
+ {"time":"2025-11-07T10:14:43.348700883+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":22529}
210
+ {"time":"2025-11-07T10:14:43.349769283+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":75}
211
+ {"time":"2025-11-07T10:14:48.353974971+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":22680}
212
+ {"time":"2025-11-07T10:14:48.354050306+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
213
+ {"time":"2025-11-07T10:14:48.354514355+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":22712}
214
+ {"time":"2025-11-07T10:14:48.357181845+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":261}
215
+ {"time":"2025-11-07T10:14:53.361374066+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":23023}
216
+ {"time":"2025-11-07T10:14:53.361443277+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
217
+ {"time":"2025-11-07T10:14:53.361839829+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":23055}
218
+ {"time":"2025-11-07T10:14:53.364316471+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":246}
219
+ {"time":"2025-11-07T10:14:58.369454725+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":23440}
220
+ {"time":"2025-11-07T10:14:58.369520979+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
221
+ {"time":"2025-11-07T10:14:58.369885747+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":23472}
222
+ {"time":"2025-11-07T10:14:58.371284742+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":200}
223
+ {"time":"2025-11-07T10:15:08.386820073+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":24052}
224
+ {"time":"2025-11-07T10:15:08.386918709+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
225
+ {"time":"2025-11-07T10:15:08.387408289+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":24084}
226
+ {"time":"2025-11-07T10:15:08.391285708+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":285}
227
+ {"time":"2025-11-07T10:15:13.396266192+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":24544}
228
+ {"time":"2025-11-07T10:15:13.396359183+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
229
+ {"time":"2025-11-07T10:15:13.396700881+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":24576}
230
+ {"time":"2025-11-07T10:15:13.398183342+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":123}
231
+ {"time":"2025-11-07T10:15:18.219934261+08:00","level":"INFO","msg":"stream: closing","id":"8xuf7idy"}
232
+ {"time":"2025-11-07T10:15:18.222879922+08:00","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":24750}
233
+ {"time":"2025-11-07T10:15:18.227486835+08:00","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":320}
234
+ {"time":"2025-11-07T10:15:20.022975156+08:00","level":"INFO","msg":"fileTransfer: Close: file transfer manager closed"}
235
+ {"time":"2025-11-07T10:15:20.387206479+08:00","level":"INFO","msg":"handler: closed","stream_id":"8xuf7idy"}
236
+ {"time":"2025-11-07T10:15:20.389093232+08:00","level":"INFO","msg":"sender: closed","stream_id":"8xuf7idy"}
237
+ {"time":"2025-11-07T10:15:20.389196771+08:00","level":"INFO","msg":"stream: closed","id":"8xuf7idy"}
cleanrl/convert_test_results.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Convert test results from one-hot vector format to human-readable 10x10 grid format.
4
+ This makes the environment observations easier for LLM analysis.
5
+ """
6
+
7
+ import json
8
+ import numpy as np
9
+ import os
10
+ import argparse
11
+ from pathlib import Path
12
+
13
+
14
+ def decode_letter(one_hot_vector):
15
+ """Decode one-hot vector back to letter"""
16
+ letter_map = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'X'}
17
+ idx = np.argmax(one_hot_vector)
18
+ return letter_map.get(idx, '?')
19
+
20
+
21
+ def parse_observation(obs_vector):
22
+ """
23
+ Parse observation vector into human-readable format.
24
+
25
+ Observation structure (605 dimensions):
26
+ - Position (x, y): indices 0-1 (normalized to [0, 1])
27
+ - Energy: index 2 (normalized)
28
+ - Score: index 3
29
+ - Steps: index 4 (normalized)
30
+ - Grid state: indices 5-604 (10x10 grid, each cell has 6 one-hot values)
31
+
32
+ Returns:
33
+ dict with parsed information
34
+ """
35
+ obs = np.array(obs_vector)
36
+
37
+ # Extract position (denormalize from [0, 1] to [0, 9])
38
+ x = int(round(obs[0] * 9.0))
39
+ y = int(round(obs[1] * 9.0))
40
+
41
+ # Extract other state info
42
+ energy = obs[2] * 20.0 # Denormalize energy
43
+ score = obs[3]
44
+ steps = obs[4] * 30.0 # Denormalize steps
45
+
46
+ # Extract grid (10x10 grid with 6-dimensional one-hot encoding per cell)
47
+ grid_encoding = obs[5:] # 600 values = 10x10x6
48
+
49
+ # Reconstruct 10x10 grid
50
+ grid = []
51
+ for y_coord in range(10):
52
+ row = []
53
+ for x_coord in range(10):
54
+ # Each cell has 6 one-hot values
55
+ cell_idx = (y_coord * 10 + x_coord) * 6
56
+ one_hot = grid_encoding[cell_idx:cell_idx + 6]
57
+ letter = decode_letter(one_hot)
58
+ row.append(letter)
59
+ grid.append(row)
60
+
61
+ return {
62
+ 'position': {'x': x, 'y': y},
63
+ 'energy': round(energy, 2),
64
+ 'score': round(score, 2),
65
+ 'steps': round(steps, 2),
66
+ 'grid': grid
67
+ }
68
+
69
+
70
+ def grid_to_string(grid, current_pos=None):
71
+ """
72
+ Convert grid to a formatted string representation.
73
+ If current_pos is provided, mark the agent's position with '@'.
74
+
75
+ Coordinate system explanation:
76
+ - In env: grid[0] = y=9 (top), grid[9] = y=0 (bottom)
77
+ - In wrapper encoding: y_coord=0 -> env.grid[9], y_coord=9 -> env.grid[0]
78
+ - Our reconstructed grid[0] = env.grid[9] = env y=0 (bottom)
79
+ - Our reconstructed grid[9] = env.grid[0] = env y=9 (top)
80
+ - Display: Show y=0 at top, y=9 at bottom (array index order, matching typical grid display)
81
+ """
82
+ lines = []
83
+ lines.append(" " + " ".join(str(i) for i in range(10)))
84
+ lines.append(" " + "-" * 19)
85
+
86
+ for display_row in range(10):
87
+ # Display from top to bottom: y=0, y=1, ..., y=9
88
+ env_y = display_row
89
+ row_str = f"{env_y}|"
90
+ for x in range(10):
91
+ # grid[env_y] has the data for env_y
92
+ if current_pos and current_pos['x'] == x and current_pos['y'] == env_y:
93
+ # Mark agent position
94
+ row_str += "@" + " "
95
+ else:
96
+ row_str += grid[env_y][x] + " "
97
+ lines.append(row_str)
98
+
99
+ return "\n".join(lines)
100
+
101
+
102
+ def convert_trajectory(trajectory):
103
+ """Convert a single trajectory to human-readable format"""
104
+ action_names = {0: 'up', 1: 'down', 2: 'left', 3: 'right'}
105
+
106
+ # Extract energy values from all observations
107
+ energies = []
108
+ observations = []
109
+
110
+ for i, obs_vector in enumerate(trajectory['observations']):
111
+ parsed_obs = parse_observation(obs_vector)
112
+ energies.append(parsed_obs['energy'])
113
+
114
+ # Create a readable representation
115
+ readable_obs = {
116
+ 'step': i,
117
+ 'position': parsed_obs['position'],
118
+ 'score': parsed_obs['score'],
119
+ 'steps': parsed_obs['steps'],
120
+ 'grid': parsed_obs['grid'],
121
+ 'grid_string': grid_to_string(parsed_obs['grid'], parsed_obs['position'])
122
+ }
123
+
124
+ # Add action taken at this step if available
125
+ if i < len(trajectory['actions']):
126
+ readable_obs['action'] = action_names.get(trajectory['actions'][i], 'unknown')
127
+ readable_obs['reward'] = trajectory['rewards'][i]
128
+
129
+ observations.append(readable_obs)
130
+
131
+ converted = {
132
+ 'actions': trajectory['actions'],
133
+ 'rewards': trajectory['rewards'],
134
+ 'dones': trajectory['dones'],
135
+ 'energies': energies,
136
+ 'observations': observations
137
+ }
138
+
139
+ return converted
140
+
141
+
142
+ def convert_test_results(input_file, output_file=None):
143
+ """
144
+ Convert test results file from one-hot format to readable format.
145
+
146
+ Args:
147
+ input_file: Path to input JSON file with test results
148
+ output_file: Path to output JSON file (if None, will add '_readable' suffix)
149
+ """
150
+ # Read input file
151
+ with open(input_file, 'r') as f:
152
+ data = json.load(f)
153
+
154
+ # Convert trajectories
155
+ test_results = data['test_results']
156
+ converted_trajectories = []
157
+
158
+ print(f"Converting {len(test_results['trajectories'])} trajectories...")
159
+
160
+ for i, trajectory in enumerate(test_results['trajectories']):
161
+ print(f" Processing trajectory {i+1}/{len(test_results['trajectories'])}...")
162
+ converted_traj = convert_trajectory(trajectory)
163
+ converted_trajectories.append(converted_traj)
164
+
165
+ # Create output data structure
166
+ output_data = {
167
+ 'iteration': data['iteration'],
168
+ 'global_step': data['global_step'],
169
+ 'training_progress': data['training_progress'],
170
+ 'test_results': {
171
+ 'episode_returns': test_results['episode_returns'],
172
+ 'episode_lengths': test_results['episode_lengths'],
173
+ 'final_scores': test_results['final_scores'],
174
+ 'mean_return': test_results['mean_return'],
175
+ 'std_return': test_results['std_return'],
176
+ 'mean_length': test_results['mean_length'],
177
+ 'mean_final_score': test_results['mean_final_score'],
178
+ 'std_final_score': test_results['std_final_score'],
179
+ 'trajectories': converted_trajectories
180
+ }
181
+ }
182
+
183
+ # Determine output file path
184
+ if output_file is None:
185
+ input_path = Path(input_file)
186
+ output_file = input_path.parent / f"{input_path.stem}_readable{input_path.suffix}"
187
+
188
+ # Write output file
189
+ with open(output_file, 'w') as f:
190
+ json.dump(output_data, f, indent=2)
191
+
192
+ print(f"\nConversion complete!")
193
+ print(f"Output saved to: {output_file}")
194
+ print(f"File size: {os.path.getsize(output_file) / 1024:.2f} KB")
195
+
196
+ return output_file
197
+
198
+
199
+ def convert_all_test_results(runs_dir, pattern="test_iter_*.json"):
200
+ """
201
+ Convert all test result files in a runs directory.
202
+
203
+ Args:
204
+ runs_dir: Path to runs directory
205
+ pattern: Glob pattern for test result files
206
+ """
207
+ runs_path = Path(runs_dir)
208
+
209
+ # Find all test result files
210
+ test_files = list(runs_path.rglob(pattern))
211
+
212
+ if not test_files:
213
+ print(f"No test result files found matching pattern '{pattern}' in {runs_dir}")
214
+ return
215
+
216
+ print(f"Found {len(test_files)} test result files to convert\n")
217
+
218
+ for i, test_file in enumerate(test_files, 1):
219
+ print(f"\n{'='*60}")
220
+ print(f"[{i}/{len(test_files)}] Converting: {test_file.name}")
221
+ print(f"{'='*60}")
222
+
223
+ try:
224
+ convert_test_results(test_file)
225
+ except Exception as e:
226
+ print(f"Error converting {test_file}: {e}")
227
+ continue
228
+
229
+ print(f"\n{'='*60}")
230
+ print(f"Batch conversion complete! Converted {len(test_files)} files.")
231
+ print(f"{'='*60}")
232
+
233
+
234
+ def main():
235
+ parser = argparse.ArgumentParser(
236
+ description="Convert test results from one-hot format to readable 10x10 grid format"
237
+ )
238
+ parser.add_argument(
239
+ 'input',
240
+ help='Input file or directory containing test results'
241
+ )
242
+ parser.add_argument(
243
+ '-o', '--output',
244
+ help='Output file path (only for single file conversion)',
245
+ default=None
246
+ )
247
+ parser.add_argument(
248
+ '-a', '--all',
249
+ action='store_true',
250
+ help='Convert all test result files in the directory'
251
+ )
252
+ parser.add_argument(
253
+ '-p', '--pattern',
254
+ default='test_iter_*.json',
255
+ help='Glob pattern for batch conversion (default: test_iter_*.json)'
256
+ )
257
+
258
+ args = parser.parse_args()
259
+
260
+ input_path = Path(args.input)
261
+
262
+ if args.all or input_path.is_dir():
263
+ # Batch conversion
264
+ convert_all_test_results(input_path, args.pattern)
265
+ else:
266
+ # Single file conversion
267
+ if not input_path.exists():
268
+ print(f"Error: File not found: {input_path}")
269
+ return
270
+
271
+ convert_test_results(input_path, args.output)
272
+
273
+
274
+ if __name__ == "__main__":
275
+ main()
cleanrl/entrypoint.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ Xvfb :1 -screen 0 1024x768x24 -ac +extension GLX +render -noreset &> xvfb.log &
3
+ export DISPLAY=:1
4
+ set -e
5
+ # bash -c "echo vm.overcommit_memory=1 >> /etc/sysctl.conf" && sysctl -p
6
+ exec "$@"
cleanrl/mkdocs.yml ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ site_name: CleanRL
2
+ theme:
3
+ name: material
4
+ features:
5
+ # - navigation.instant
6
+ - navigation.tracking
7
+ # - navigation.tabs
8
+ # - navigation.tabs.sticky
9
+ - navigation.sections
10
+ - navigation.expand
11
+ - navigation.top
12
+ - search.suggest
13
+ - search.highlight
14
+ palette:
15
+ - media: "(prefers-color-scheme: dark)"
16
+ scheme: slate
17
+ primary: teal
18
+ accent: light green
19
+ toggle:
20
+ icon: material/lightbulb
21
+ name: Switch to light mode
22
+ - media: "(prefers-color-scheme: light)"
23
+ scheme: default
24
+ primary: green
25
+ accent: deep orange
26
+ toggle:
27
+ icon: material/lightbulb-outline
28
+ name: Switch to dark mode
29
+ plugins:
30
+ - search
31
+ nav:
32
+ - Overview: index.md
33
+ - Get Started:
34
+ - get-started/installation.md
35
+ - get-started/basic-usage.md
36
+ - get-started/experiment-tracking.md
37
+ - get-started/examples.md
38
+ - get-started/benchmark-utility.md
39
+ - get-started/zoo.md
40
+ - RL Algorithms:
41
+ - rl-algorithms/overview.md
42
+ - rl-algorithms/ppo.md
43
+ - rl-algorithms/dqn.md
44
+ - rl-algorithms/c51.md
45
+ - rl-algorithms/ddpg.md
46
+ - rl-algorithms/sac.md
47
+ - rl-algorithms/td3.md
48
+ - rl-algorithms/ppg.md
49
+ - rl-algorithms/ppo-rnd.md
50
+ - rl-algorithms/rpo.md
51
+ - rl-algorithms/qdagger.md
52
+ - rl-algorithms/ppo-trxl.md
53
+ - rl-algorithms/pqn.md
54
+ - rl-algorithms/rainbow.md
55
+ - Advanced:
56
+ - advanced/hyperparameter-tuning.md
57
+ - advanced/resume-training.md
58
+ - Community:
59
+ - contribution.md
60
+ - cleanrl-supported-papers-projects.md
61
+ - Cloud Integration:
62
+ - cloud/installation.md
63
+ - cloud/submit-experiments.md
64
+ #adding git repo
65
+ repo_url: https://github.com/vwxyzjn/cleanrl
66
+ repo_name: vwxyzjn/cleanrl
67
+ #markdown_extensions
68
+ markdown_extensions:
69
+ - pymdownx.superfences
70
+ - pymdownx.tabbed:
71
+ alternate_style: true
72
+ - abbr
73
+ - pymdownx.highlight
74
+ - pymdownx.inlinehilite
75
+ - pymdownx.superfences
76
+ - pymdownx.snippets
77
+ - admonition
78
+ - pymdownx.details
79
+ - attr_list
80
+ - md_in_html
81
+ - footnotes
82
+ - markdown_include.include:
83
+ base_path: docs
84
+ - pymdownx.emoji:
85
+ emoji_index: !!python/name:materialx.emoji.twemoji
86
+ emoji_generator: !!python/name:materialx.emoji.to_svg
87
+ - pymdownx.arithmatex:
88
+ generic: true
89
+ # - toc:
90
+ # permalink: true
91
+ # - markdown.extensions.codehilite:
92
+ # guess_lang: false
93
+ # - admonition
94
+ # - codehilite
95
+ # - extra
96
+ # - pymdownx.superfences:
97
+ # custom_fences:
98
+ # - name: mermaid
99
+ # class: mermaid
100
+ # format: !!python/name:pymdownx.superfences.fence_code_format ''
101
+ # - pymdownx.tabbed
102
+ extra_css:
103
+ - stylesheets/extra.css
104
+ # extra_javascript:
105
+ # - js/termynal.js
106
+ # - js/custom.js
107
+ #footer
108
+ extra:
109
+ social:
110
+ - icon: fontawesome/solid/envelope
111
+ link: mailto:costa.huang@outlook.com
112
+ - icon: fontawesome/brands/twitter
113
+ link: https://twitter.com/vwxyzjn
114
+ - icon: fontawesome/brands/github
115
+ link: https://github.com/vwxyzjn/cleanrl
116
+ copyright: Copyright &copy; 2021, CleanRL. All rights reserved.
117
+ extra_javascript:
118
+ # - javascripts/mathjax.js
119
+ # - https://polyfill.io/v3/polyfill.min.js?features=es6
120
+ - https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js
cleanrl/ultrahorizon_gym_wrapper.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gymnasium wrapper for Ultrahorizon_grid_env to make it compatible with CleanRL PPO
3
+ """
4
+ import gymnasium as gym
5
+ import numpy as np
6
+ import asyncio
7
+ from typing import Dict, Any, Tuple
8
+ from Ultrahorizon_grid_env import MysteryGridEnvironment, Difficulty
9
+
10
+
11
+ class UltrahorizonGymWrapper(gym.Env):
12
+ """
13
+ Gymnasium wrapper for the Ultrahorizon grid environment.
14
+ Converts the async text-based environment into a sync gym-compatible interface.
15
+
16
+ Goal: Train RL agent to maximize score (not to understand world rules).
17
+ Observation: Full global observation of 10x10 grid.
18
+ Episode length: 20-30 steps (limited by energy=20 and max_steps=30).
19
+ """
20
+
21
+ metadata = {"render_modes": ["human"]}
22
+
23
+ def __init__(self, difficulty: Difficulty = Difficulty.HARD, required_steps: int = 50, free: bool = True):
24
+ super().__init__()
25
+
26
+ # Initialize the underlying environment
27
+ self.env = MysteryGridEnvironment(difficulty=difficulty, required_steps=required_steps, free=free)
28
+
29
+ # Define action space: 0=up, 1=down, 2=left, 3=right
30
+ self.action_space = gym.spaces.Discrete(4)
31
+ self.action_map = {0: "up", 1: "down", 2: "left", 3: "right"}
32
+
33
+ # Define observation space
34
+ # We'll create a feature vector with:
35
+ # - Position (x, y): 2 values normalized to [0, 1]
36
+ # - Energy: 1 value normalized
37
+ # - Score: 1 value (can be negative)
38
+ # - Steps: 1 value normalized
39
+ # - Grid state: 10x10 one-hot encoded letters (A-E, X) = 10x10x6 = 600 values
40
+ # Total: 2 + 1 + 1 + 1 + 600 = 605 dimensional vector
41
+
42
+ # For simplicity, we'll use a flattened representation
43
+ # Position (2) + energy (1) + score (1) + steps (1) + grid (600) = 605
44
+ obs_dim = 605
45
+ self.observation_space = gym.spaces.Box(
46
+ low=-np.inf, high=np.inf, shape=(obs_dim,), dtype=np.float32
47
+ )
48
+
49
+ self.current_state = None
50
+ self.episode_return = 0
51
+ self.episode_length = 0
52
+
53
+ def _encode_letter(self, letter: str) -> np.ndarray:
54
+ """One-hot encode a letter (A, B, C, D, E, X)"""
55
+ letter_map = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'X': 5}
56
+ encoding = np.zeros(6, dtype=np.float32)
57
+ if letter in letter_map:
58
+ encoding[letter_map[letter]] = 1.0
59
+ return encoding
60
+
61
+ def _get_observation(self) -> np.ndarray:
62
+ """Convert environment state to observation vector"""
63
+ # Get current state synchronously
64
+ state_dict = asyncio.run(self.env.get_current_state())
65
+
66
+ # Extract position from string format "(x,y,letter)"
67
+ pos_str = state_dict["current_position"]
68
+ x, y, current_letter = pos_str.strip("()").split(",")
69
+ x, y = int(x), int(y)
70
+
71
+ # Normalize position to [0, 1]
72
+ pos_normalized = np.array([x / 9.0, y / 9.0], dtype=np.float32)
73
+
74
+ # Normalize energy (max is typically 20, but can increase)
75
+ energy_normalized = np.array([state_dict["energy"] / 20.0], dtype=np.float32)
76
+
77
+ # Score (not normalized, can be negative)
78
+ score = np.array([state_dict["score"]], dtype=np.float32)
79
+
80
+ # Normalize steps
81
+ steps_normalized = np.array([state_dict["steps"] / 30.0], dtype=np.float32)
82
+
83
+ # Encode grid state (10x10 grid with letters)
84
+ grid_encoding = []
85
+ for y_coord in range(10):
86
+ for x_coord in range(10):
87
+ letter = self.env.grid[9 - y_coord][x_coord]
88
+ grid_encoding.append(self._encode_letter(letter))
89
+ grid_flat = np.concatenate(grid_encoding)
90
+
91
+ # Concatenate all features
92
+ observation = np.concatenate([
93
+ pos_normalized,
94
+ energy_normalized,
95
+ score,
96
+ steps_normalized,
97
+ grid_flat
98
+ ])
99
+
100
+ return observation
101
+
102
+ def reset(self, seed=None, options=None) -> Tuple[np.ndarray, Dict[str, Any]]:
103
+ """Reset the environment"""
104
+ super().reset(seed=seed)
105
+
106
+ if seed is not None:
107
+ np.random.seed(seed)
108
+
109
+ # Reset the underlying environment
110
+ result = asyncio.run(self.env.reset())
111
+
112
+ # Reset episode tracking
113
+ self.episode_return = 0
114
+ self.episode_length = 0
115
+
116
+ # Get initial observation
117
+ observation = self._get_observation()
118
+ info = {}
119
+
120
+ return observation, info
121
+
122
+ def step(self, action: int) -> Tuple[np.ndarray, float, bool, bool, Dict[str, Any]]:
123
+ """Execute one step in the environment"""
124
+ # Store previous cumulative score
125
+ # Note: score in the environment is cumulative (total score so far)
126
+ prev_score = self.env.state.score
127
+
128
+ # Convert action to direction
129
+ direction = self.action_map[action]
130
+
131
+ # Execute move
132
+ result = asyncio.run(self.env.move(direction))
133
+
134
+ # Get new observation
135
+ observation = self._get_observation()
136
+
137
+ # Calculate single-step reward from cumulative score change
138
+ # score = cumulative total score (not single-step reward)
139
+ # reward = score_change = this step's contribution to total score
140
+ if result["success"]:
141
+ current_score = result.get("score", self.env.state.score)
142
+ # Single-step reward = change in cumulative score
143
+ reward = float(current_score - prev_score)
144
+ else:
145
+ # Invalid move: penalize heavily to avoid wasting steps
146
+ reward = -10
147
+
148
+ # Episode termination conditions:
149
+ # 1. Energy reaches 0 (game_over=True)
150
+ # 2. Steps reach 30 (game_over=True)
151
+ # 3. Invalid move (out of bounds or already terminated)
152
+ # Note: Episode length will be 20-30 steps due to energy constraint
153
+ terminated = self.env.state.game_over or not result["success"]
154
+ truncated = False
155
+ # Update episode tracking
156
+ self.episode_return += reward
157
+ self.episode_length += 1
158
+
159
+ # Info dict - don't add episode stats here, let RecordEpisodeStatistics handle it
160
+ info = {}
161
+ if terminated or truncated:
162
+ # Add the final cumulative score from the environment
163
+ info["final_score"] = float(self.env.state.score)
164
+
165
+ return observation, reward, terminated, truncated, info
166
+
167
+ def render(self):
168
+ """Render the environment (optional)"""
169
+ pass
170
+
171
+ def close(self):
172
+ """Clean up resources"""
173
+ pass
174
+
175
+
176
+ def make_ultrahorizon_env(difficulty: Difficulty = Difficulty.HARD, required_steps: int = 50, free: bool = True):
177
+ """Factory function to create Ultrahorizon environment"""
178
+ def thunk():
179
+ env = UltrahorizonGymWrapper(difficulty=difficulty, required_steps=required_steps, free=free)
180
+ env = gym.wrappers.RecordEpisodeStatistics(env)
181
+ return env
182
+ return thunk
183
+
184
+
185
+ if __name__ == "__main__":
186
+ # Test the wrapper
187
+ env = UltrahorizonGymWrapper(difficulty=Difficulty.EASY, free=True)
188
+ obs, info = env.reset()
189
+ print(f"Observation shape: {obs.shape}")
190
+ print(f"Action space: {env.action_space}")
191
+ # import pdb;pdb.set_trace()
192
+ for i in range(5):
193
+ action = env.action_space.sample()
194
+ import pdb;pdb.set_trace()
195
+ obs, reward, terminated, truncated, info = env.step(action)
196
+ print(f"Step {i+1}: action={action}, reward={reward}, terminated={terminated}")
197
+ if terminated:
198
+ break
199
+
200
+ env.close()
train_starpo-s_qwen7B_frommlp_326.sh ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -e
2
+ export MASTER_PORT=29501 #
3
+ # Section 1: Base Experiments
4
+ USE_GRPO="algorithm.adv_estimator=grpo"
5
+ # USE_GRPO="algorithm.adv_estimator=grpo agent_proxy.reward_normalization.method=mean_std actor_rollout_ref.actor.use_kl_loss=True"
6
+ USE_PPO="algorithm.adv_estimator=gae" # by default.
7
+ USE_BASE="algorithm.kl_ctrl.kl_coef=0.0 actor_rollout_ref.actor.kl_loss_coef=0.0 actor_rollout_ref.actor.clip_ratio_high=0.28 actor_rollout_ref.rollout.rollout_filter_ratio=0.25"
8
+ export WANDB_API_KEY="wandb_v1_Ahkqz2osih1TkZ4XAAg0iz2t3Lv"
9
+
10
+ # python -m verl.model_merger merge \
11
+ # --backend fsdp \
12
+ # --local_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_bandit_multitask/global_step_200/actor \
13
+ # --target_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_bandit_multitask/global_step_200/qwen2.5_7B_actor_hf
14
+
15
+ # **************************************bandit*********************************
16
+ ########## 0.5B #############
17
+ # python train.py --config-name _1_bandit system.CUDA_VISIBLE_DEVICES="'0,1,2,3,4,5,6,7'" \
18
+ # trainer.project_name=ragen_latest_qwen2.5_7B_it_sequence_multitask_frommlp \
19
+ # trainer.n_gpus_per_node=8 \
20
+ # model_path=/mnt/general/wanghy/LLaMA-Factory/saves/qwen3/full/sft/qwen2.5_7B_it_multitask \
21
+ # trainer.total_training_steps=100 \
22
+ # trainer.save_freq=100 \
23
+ # agent_proxy.enable_think=True\
24
+ # trainer.default_local_dir=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_bandit_multitask \
25
+ # trainer.experiment_name=bandit--starpos-fromit_sequence_multitask_326 $USE_PPO $USE_BASE
26
+
27
+ # python -m verl.model_merger merge \
28
+ # --backend fsdp \
29
+ # --local_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_bandit_multitask/global_step_100/actor \
30
+ # --target_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_bandit_multitask/global_step_100/qwen2.5_7B_actor_hf
31
+
32
+ # # #**************************************Frozenlake*********************************
33
+ # python train.py --config-name _3_frozen_lake \
34
+ # system.CUDA_VISIBLE_DEVICES="'0,1,2,3,4,5,6,7'" \
35
+ # trainer.project_name=ragen_latest_qwen2.5_7B_it_sequence_multitask_frommlp \
36
+ # trainer.n_gpus_per_node=8 \
37
+ # model_path=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_bandit_multitask/global_step_100/qwen2.5_7B_actor_hf \
38
+ # trainer.save_freq=200 \
39
+ # agent_proxy.enable_think=True\
40
+ # trainer.default_local_dir=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_frozenlake_sequence_multitask \
41
+ # trainer.experiment_name=frozen_lake--starpos-slippery_fromit_sequence_multitask_326 $USE_PPO $USE_BASE
42
+
43
+ # python -m verl.model_merger merge \
44
+ # --backend fsdp \
45
+ # --local_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_frozenlake_sequence_multitask/global_step_200/actor \
46
+ # --target_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_frozenlake_sequence_multitask/global_step_200/qwen2.5_7B_actor_hf
47
+
48
+
49
+ # # #**************************************sokoban-box1*********************************
50
+ # python train.py --config-name _2_sokoban system.CUDA_VISIBLE_DEVICES="'0,1,2,3,4,5,6,7'" \
51
+ # trainer.project_name=ragen_latest_qwen2.5_7B_it_sequence_multitask_frommlp \
52
+ # trainer.n_gpus_per_node=8 \
53
+ # model_path=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_frozenlake_sequence_multitask/global_step_200/qwen2.5_7B_actor_hf \
54
+ # custom_envs.CoordSokoban.env_config.num_boxes=1 \
55
+ # trainer.save_freq=200 \
56
+ # agent_proxy.enable_think=True\
57
+ # trainer.default_local_dir=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_sokobanbox1_sequence_multitask \
58
+ # trainer.experiment_name=sokoban-box1--starpos_fromit_sequence_multitask_326 $USE_PPO $USE_BASE
59
+
60
+ # python -m verl.model_merger merge \
61
+ # --backend fsdp \
62
+ # --local_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_sokobanbox1_sequence_multitask/global_step_200/actor \
63
+ # --target_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_sokobanbox1_sequence_multitask/global_step_200/qwen2.5_7B_actor_hf
64
+ # # #**************************************sokoban-box2*********************************
65
+ # python train.py --config-name _2_sokoban system.CUDA_VISIBLE_DEVICES="'0,1,2,3,4,5,6,7'" \
66
+ # trainer.project_name=ragen_latest_qwen2.5_7B_it_sequence_multitask_frommlp \
67
+ # trainer.n_gpus_per_node=8 \
68
+ # model_path=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_sokobanbox1_sequence_multitask/global_step_200/qwen2.5_7B_actor_hf \
69
+ # custom_envs.CoordSokoban.env_config.num_boxes=2 \
70
+ # trainer.total_training_steps=100 \
71
+ # trainer.save_freq=100 \
72
+ # agent_proxy.enable_think=True\
73
+ # trainer.default_local_dir=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_sokobanbox2_sequence_multitask \
74
+ # trainer.experiment_name=sokoban-box2--starpos_fromit_sequence_multitask_326 $USE_PPO $USE_BASE
75
+
76
+ # python -m verl.model_merger merge \
77
+ # --backend fsdp \
78
+ # --local_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_sokobanbox2_sequence_multitask/global_step_100/actor \
79
+ # --target_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_sokobanbox2_sequence_multitask/global_step_100/qwen2.5_7B_actor_hf
80
+
81
+ # # #**************************************rubikscube-rotato1*********************************
82
+ # # ########### 0.5B #############
83
+ # python train.py --config-name _10_rubikscube system.CUDA_VISIBLE_DEVICES="'0,1,2,3,4,5,6,7'" \
84
+ # trainer.project_name=ragen_latest_qwen2.5_7B_it_sequence_multitask_frommlp \
85
+ # trainer.n_gpus_per_node=8 \
86
+ # model_path=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_sokobanbox2_sequence_multitask/global_step_100/qwen2.5_7B_actor_hf \
87
+ # custom_envs.rubikscube.env_config.scramble_depth=1 \
88
+ # trainer.total_training_steps=100 \
89
+ # trainer.save_freq=100 \
90
+ # agent_proxy.enable_think=True\
91
+ # trainer.default_local_dir=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_cube1_sequence_multitask \
92
+ # trainer.experiment_name=rubikscube-1-starpos_fromit_sequence_multitask_326 $USE_PPO $USE_BASE
93
+
94
+
95
+ # python -m verl.model_merger merge \
96
+ # --backend fsdp \
97
+ # --local_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_cube1_sequence_multitask/global_step_100/actor \
98
+ # --target_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_cube1_sequence_multitask/global_step_100/qwen2.5_7B_actor_hf
99
+
100
+ # # #**************************************rubikscube-rotato2*********************************
101
+ # # ########### 0.5B #############
102
+ # python train.py --config-name _10_rubikscube system.CUDA_VISIBLE_DEVICES="'0,1,2,3,4,5,6,7'" \
103
+ # trainer.project_name=ragen_latest_qwen2.5_7B_it_sequence_multitask_frommlp \
104
+ # trainer.n_gpus_per_node=8 \
105
+ # model_path=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_cube1_sequence_multitask/global_step_100/qwen2.5_7B_actor_hf \
106
+ # custom_envs.rubikscube.env_config.scramble_depth=2 \
107
+ # trainer.total_training_steps=100 \
108
+ # trainer.save_freq=100 \
109
+ # agent_proxy.enable_think=True\
110
+ # trainer.default_local_dir=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_cube2_sequence_multitask \
111
+ # trainer.experiment_name=rubikscube-2-starpos_fromit_sequence_multitask_326 $USE_PPO $USE_BASE
112
+
113
+
114
+ python -m verl.model_merger merge \
115
+ --backend fsdp \
116
+ --local_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_cube2_sequence_multitask/global_step_100/actor \
117
+ --target_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_cube2_sequence_multitask/global_step_100/qwen2.5_7B_actor_hf
118
+
119
+ # #**************************************rubikscube-rotato3*********************************
120
+ # ########### 0.5B #############
121
+ python train.py --config-name _10_rubikscube system.CUDA_VISIBLE_DEVICES="'0,1,2,3,4,5,6,7'" \
122
+ trainer.project_name=ragen_latest_qwen2.5_7B_it_sequence_multitask_frommlp \
123
+ trainer.n_gpus_per_node=8 \
124
+ model_path=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_cube2_sequence_multitask/global_step_100/qwen2.5_7B_actor_hf \
125
+ custom_envs.rubikscube.env_config.scramble_depth=3 \
126
+ trainer.total_training_steps=100 \
127
+ trainer.save_freq=100 \
128
+ agent_proxy.enable_think=True\
129
+ trainer.default_local_dir=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_cube3_sequence_multitask \
130
+ trainer.experiment_name=rubikscube-3-starpos_fromit_sequence_multitask_326 $USE_PPO $USE_BASE
131
+
132
+
133
+ python -m verl.model_merger merge \
134
+ --backend fsdp \
135
+ --local_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_cube3_sequence_multitask/global_step_100/actor \
136
+ --target_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_cube3_sequence_multitask/global_step_100/qwen2.5_7B_actor_hf
137
+
138
+ #**********************************sudoku****************************************
139
+
140
+ python train.py --config-name _11_sudoku \
141
+ system.CUDA_VISIBLE_DEVICES="'0,1,2,3,4,5,6,7'" \
142
+ trainer.project_name=ragen_latest_qwen2.5_7B_it_sequence_multitask_frommlp\
143
+ trainer.n_gpus_per_node=8 \
144
+ model_path=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_cube3_sequence_multitask/global_step_100/qwen2.5_7B_actor_hf \
145
+ trainer.save_freq=200 \
146
+ actor_rollout_ref.rollout.gpu_memory_utilization=0.5\
147
+ agent_proxy.enable_think=True\
148
+ trainer.default_local_dir=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_sudoku_sequence_multitask \
149
+ trainer.experiment_name=sudoku-4x4-nohint-starpos_fromit_sequence_multitask_326 $USE_PPO $USE_BASE
150
+
151
+ python -m verl.model_merger merge \
152
+ --backend fsdp \
153
+ --local_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_sudoku_sequence_multitask/global_step_200/actor \
154
+ --target_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_sudoku_sequence_multitask/global_step_200/qwen2.5_7B_actor_hf
155
+
156
+ # # **************************************2048*********************************
157
+ # python train.py --config-name _8_2048 system.CUDA_VISIBLE_DEVICES="'0,1,2,3,4,5,6,7'" \
158
+ # trainer.project_name=ragen_latest_qwen2.5_7B_it_sequence_multitask_frommlp \
159
+ # trainer.n_gpus_per_node=8 \
160
+ # model_path=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_sudoku_sequence_multitask/global_step_200/qwen2.5_7B_actor_hf \
161
+ # trainer.save_freq=200 \
162
+ # agent_proxy.enable_think=True\
163
+ # trainer.default_local_dir=/mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_2048_sequence_multitask \
164
+ # actor_rollout_ref.rollout.gpu_memory_utilization=0.5\
165
+ # actor_rollout_ref.rollout.max_model_len=14400\
166
+ # agent_proxy.max_turn=700\
167
+ # trainer.experiment_name=_2048_-starpos_fromit_sequence_multitask_326 $USE_PPO $USE_BASE
168
+
169
+ # python -m verl.model_merger merge \
170
+ # --backend fsdp \
171
+ # --local_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_2048_sequence_multitask/global_step_200/actor \
172
+ # --target_dir /mnt/general/wanghy/RAGEN/saves/qwen7B_it_fromit_326_think_2048_sequence_multitask/global_step_200/qwen2.5_7B_actor_hf