Harryis commited on
Commit
dd58921
·
verified ·
1 Parent(s): 13621bf

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. cleanrl/cleanrl/ppo_procgen.py +346 -0
  2. cleanrl/cleanrl/ppo_rnd_envpool.py +539 -0
  3. cleanrl/cleanrl/ppo_rubikscube_generalization.py +561 -0
  4. cleanrl/cleanrl/ppo_sudoku_actionmask.py +588 -0
  5. cleanrl/cleanrl/ppo_sudoku_strongactionmask.py +616 -0
  6. cleanrl/cleanrl/ppo_trxl/pom_env.py +186 -0
  7. cleanrl/cleanrl/ppo_trxl/ppo_trxl.py +682 -0
  8. cleanrl/cleanrl/ppo_trxl/pyproject.toml +34 -0
  9. cleanrl/cleanrl/ppo_ultrahorizon.py +490 -0
  10. cleanrl/cleanrl/pqn.py +248 -0
  11. cleanrl/cleanrl/pqn_atari_envpool_lstm.py +339 -0
  12. cleanrl/cleanrl/qdagger_dqn_atari_impalacnn.py +466 -0
  13. cleanrl/cleanrl/ragen_wrappers.py +235 -0
  14. cleanrl/cleanrl/sac_atari.py +343 -0
  15. cleanrl/cleanrl/scout_dqn/dqn_bandit_nochangeenv.py +422 -0
  16. cleanrl/cleanrl/scout_dqn/dqn_frozenlake.py +428 -0
  17. cleanrl/cleanrl/scout_dqn/dqn_rubikscube.py +454 -0
  18. cleanrl/cleanrl/scout_dqn/dqn_sudoku.py +485 -0
  19. cleanrl/cleanrl/scout_dqn/noisy_dqn_sokoban.py +541 -0
  20. cleanrl/cleanrl/scout_dqn/ragen_wrappers.py +235 -0
  21. cleanrl/cleanrl/scout_ppo/ppo_2048.py +514 -0
  22. cleanrl/cleanrl/scout_ppo/ppo_bandit_small.py +410 -0
  23. cleanrl/cleanrl/scout_ppo/ppo_sokoban.py +501 -0
  24. cleanrl/cleanrl/scout_ppo/ppo_sudoku_actionmask.py +588 -0
  25. cleanrl/cleanrl/scout_ppo/ragen_wrappers.py +235 -0
  26. cleanrl/cleanrl/td3_continuous_action.py +317 -0
  27. cleanrl/cleanrl/td3_continuous_action_jax.py +361 -0
  28. cleanrl/cleanrl/wandb/debug-internal.log +15 -0
  29. cleanrl/cleanrl/wandb/debug.log +388 -0
  30. cleanrl/cleanrl/wandb/run-20251107_102633-lu2iu68t/files/config.yaml +153 -0
  31. cleanrl/cleanrl/wandb/run-20251107_102633-lu2iu68t/files/wandb-summary.json +1 -0
  32. cleanrl/cleanrl/wandb/run-20251107_103331-e2e7wd2b/files/code/cleanrl/ppo_frozenlake.py +347 -0
  33. cleanrl/cleanrl/wandb/run-20251107_103331-e2e7wd2b/files/config.yaml +157 -0
  34. cleanrl/cleanrl/wandb/run-20251107_103331-e2e7wd2b/files/output.log +0 -0
  35. cleanrl/cleanrl/wandb/run-20251107_103331-e2e7wd2b/files/wandb-metadata.json +94 -0
  36. cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/files/code/cleanrl/ppo_sokoban.py +352 -0
  37. cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/files/config.yaml +163 -0
  38. cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/files/output.log +16 -0
  39. cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/files/requirements.txt +305 -0
  40. cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/files/wandb-metadata.json +94 -0
  41. cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/logs/debug.log +24 -0
  42. cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/run-9utis4xx.wandb +0 -0
  43. cleanrl/cleanrl/wandb/run-20251107_112903-8xop3upl/files/wandb-metadata.json +94 -0
  44. cleanrl/cleanrl/wandb/run-20251107_113856-k31oio6c/files/code/cleanrl/ppo_frozenlake.py +347 -0
  45. cleanrl/cleanrl/wandb/run-20251107_113856-k31oio6c/files/output.log +0 -0
  46. cleanrl/cleanrl/wandb/run-20251107_113856-k31oio6c/files/wandb-metadata.json +94 -0
  47. cleanrl/cleanrl/wandb/run-20251107_113856-k31oio6c/logs/debug-internal.log +0 -0
  48. cleanrl/cleanrl/wandb/run-20251107_113856-k31oio6c/logs/debug.log +24 -0
  49. cleanrl/cleanrl/wandb/run-20251107_125210-py6fnjml/files/code/cleanrl/dqn_bandit.py +274 -0
  50. cleanrl/cleanrl/wandb/run-20251107_125210-py6fnjml/files/config.yaml +145 -0
cleanrl/cleanrl/ppo_procgen.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/ppo/#ppo_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.distributions.categorical import Categorical
15
+ from torch.utils.tensorboard import SummaryWriter
16
+
17
+
18
+ @dataclass
19
+ class Args:
20
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
21
+ """the name of this experiment"""
22
+ seed: int = 1
23
+ """seed of the experiment"""
24
+ torch_deterministic: bool = True
25
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
26
+ cuda: bool = True
27
+ """if toggled, cuda will be enabled by default"""
28
+ track: bool = False
29
+ """if toggled, this experiment will be tracked with Weights and Biases"""
30
+ wandb_project_name: str = "cleanRL"
31
+ """the wandb's project name"""
32
+ wandb_entity: str = None
33
+ """the entity (team) of wandb's project"""
34
+ capture_video: bool = False
35
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
36
+
37
+ # Algorithm specific arguments
38
+ env_id: str = "starpilot"
39
+ """the id of the environment"""
40
+ total_timesteps: int = int(25e6)
41
+ """total timesteps of the experiments"""
42
+ learning_rate: float = 5e-4
43
+ """the learning rate of the optimizer"""
44
+ num_envs: int = 64
45
+ """the number of parallel game environments"""
46
+ num_steps: int = 256
47
+ """the number of steps to run in each environment per policy rollout"""
48
+ anneal_lr: bool = False
49
+ """Toggle learning rate annealing for policy and value networks"""
50
+ gamma: float = 0.999
51
+ """the discount factor gamma"""
52
+ gae_lambda: float = 0.95
53
+ """the lambda for the general advantage estimation"""
54
+ num_minibatches: int = 8
55
+ """the number of mini-batches"""
56
+ update_epochs: int = 3
57
+ """the K epochs to update the policy"""
58
+ norm_adv: bool = True
59
+ """Toggles advantages normalization"""
60
+ clip_coef: float = 0.2
61
+ """the surrogate clipping coefficient"""
62
+ clip_vloss: bool = True
63
+ """Toggles whether or not to use a clipped loss for the value function, as per the paper."""
64
+ ent_coef: float = 0.01
65
+ """coefficient of the entropy"""
66
+ vf_coef: float = 0.5
67
+ """coefficient of the value function"""
68
+ max_grad_norm: float = 0.5
69
+ """the maximum norm for the gradient clipping"""
70
+ target_kl: float = None
71
+ """the target KL divergence threshold"""
72
+
73
+ # to be filled in runtime
74
+ batch_size: int = 0
75
+ """the batch size (computed in runtime)"""
76
+ minibatch_size: int = 0
77
+ """the mini-batch size (computed in runtime)"""
78
+ num_iterations: int = 0
79
+ """the number of iterations (computed in runtime)"""
80
+
81
+
82
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
83
+ torch.nn.init.orthogonal_(layer.weight, std)
84
+ torch.nn.init.constant_(layer.bias, bias_const)
85
+ return layer
86
+
87
+
88
+ # taken from https://github.com/AIcrowd/neurips2020-procgen-starter-kit/blob/142d09586d2272a17f44481a115c4bd817cf6a94/models/impala_cnn_torch.py
89
+ class ResidualBlock(nn.Module):
90
+ def __init__(self, channels):
91
+ super().__init__()
92
+ self.conv0 = nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=3, padding=1)
93
+ self.conv1 = nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=3, padding=1)
94
+
95
+ def forward(self, x):
96
+ inputs = x
97
+ x = nn.functional.relu(x)
98
+ x = self.conv0(x)
99
+ x = nn.functional.relu(x)
100
+ x = self.conv1(x)
101
+ return x + inputs
102
+
103
+
104
+ class ConvSequence(nn.Module):
105
+ def __init__(self, input_shape, out_channels):
106
+ super().__init__()
107
+ self._input_shape = input_shape
108
+ self._out_channels = out_channels
109
+ self.conv = nn.Conv2d(in_channels=self._input_shape[0], out_channels=self._out_channels, kernel_size=3, padding=1)
110
+ self.res_block0 = ResidualBlock(self._out_channels)
111
+ self.res_block1 = ResidualBlock(self._out_channels)
112
+
113
+ def forward(self, x):
114
+ x = self.conv(x)
115
+ x = nn.functional.max_pool2d(x, kernel_size=3, stride=2, padding=1)
116
+ x = self.res_block0(x)
117
+ x = self.res_block1(x)
118
+ assert x.shape[1:] == self.get_output_shape()
119
+ return x
120
+
121
+ def get_output_shape(self):
122
+ _c, h, w = self._input_shape
123
+ return (self._out_channels, (h + 1) // 2, (w + 1) // 2)
124
+
125
+
126
+ class Agent(nn.Module):
127
+ def __init__(self, envs):
128
+ super().__init__()
129
+ h, w, c = envs.single_observation_space.shape
130
+ shape = (c, h, w)
131
+ conv_seqs = []
132
+ for out_channels in [16, 32, 32]:
133
+ conv_seq = ConvSequence(shape, out_channels)
134
+ shape = conv_seq.get_output_shape()
135
+ conv_seqs.append(conv_seq)
136
+ conv_seqs += [
137
+ nn.Flatten(),
138
+ nn.ReLU(),
139
+ nn.Linear(in_features=shape[0] * shape[1] * shape[2], out_features=256),
140
+ nn.ReLU(),
141
+ ]
142
+ self.network = nn.Sequential(*conv_seqs)
143
+ self.actor = layer_init(nn.Linear(256, envs.single_action_space.n), std=0.01)
144
+ self.critic = layer_init(nn.Linear(256, 1), std=1)
145
+
146
+ def get_value(self, x):
147
+ return self.critic(self.network(x.permute((0, 3, 1, 2)) / 255.0)) # "bhwc" -> "bchw"
148
+
149
+ def get_action_and_value(self, x, action=None):
150
+ hidden = self.network(x.permute((0, 3, 1, 2)) / 255.0) # "bhwc" -> "bchw"
151
+ logits = self.actor(hidden)
152
+ probs = Categorical(logits=logits)
153
+ if action is None:
154
+ action = probs.sample()
155
+ return action, probs.log_prob(action), probs.entropy(), self.critic(hidden)
156
+
157
+
158
+ if __name__ == "__main__":
159
+ args = tyro.cli(Args)
160
+ args.batch_size = int(args.num_envs * args.num_steps)
161
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
162
+ args.num_iterations = args.total_timesteps // args.batch_size
163
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
164
+ if args.track:
165
+ import wandb
166
+
167
+ wandb.init(
168
+ project=args.wandb_project_name,
169
+ entity=args.wandb_entity,
170
+ sync_tensorboard=True,
171
+ config=vars(args),
172
+ name=run_name,
173
+ monitor_gym=True,
174
+ save_code=True,
175
+ )
176
+ writer = SummaryWriter(f"runs/{run_name}")
177
+ writer.add_text(
178
+ "hyperparameters",
179
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
180
+ )
181
+
182
+ # TRY NOT TO MODIFY: seeding
183
+ random.seed(args.seed)
184
+ np.random.seed(args.seed)
185
+ torch.manual_seed(args.seed)
186
+ torch.backends.cudnn.deterministic = args.torch_deterministic
187
+
188
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
189
+
190
+ # env setup
191
+ envs = ProcgenEnv(num_envs=args.num_envs, env_name=args.env_id, num_levels=0, start_level=0, distribution_mode="easy")
192
+ envs = gym.wrappers.TransformObservation(envs, lambda obs: obs["rgb"])
193
+ envs.single_action_space = envs.action_space
194
+ envs.single_observation_space = envs.observation_space["rgb"]
195
+ envs.is_vector_env = True
196
+ envs = gym.wrappers.RecordEpisodeStatistics(envs)
197
+ if args.capture_video:
198
+ envs = gym.wrappers.RecordVideo(envs, f"videos/{run_name}")
199
+ envs = gym.wrappers.NormalizeReward(envs, gamma=args.gamma)
200
+ envs = gym.wrappers.TransformReward(envs, lambda reward: np.clip(reward, -10, 10))
201
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
202
+
203
+ agent = Agent(envs).to(device)
204
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
205
+
206
+ # ALGO Logic: Storage setup
207
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
208
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
209
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
210
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
211
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
212
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
213
+
214
+ # TRY NOT TO MODIFY: start the game
215
+ global_step = 0
216
+ start_time = time.time()
217
+ next_obs = torch.Tensor(envs.reset()).to(device)
218
+ next_done = torch.zeros(args.num_envs).to(device)
219
+
220
+ for iteration in range(1, args.num_iterations + 1):
221
+ # Annealing the rate if instructed to do so.
222
+ if args.anneal_lr:
223
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
224
+ lrnow = frac * args.learning_rate
225
+ optimizer.param_groups[0]["lr"] = lrnow
226
+
227
+ for step in range(0, args.num_steps):
228
+ global_step += args.num_envs
229
+ obs[step] = next_obs
230
+ dones[step] = next_done
231
+
232
+ # ALGO LOGIC: action logic
233
+ with torch.no_grad():
234
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
235
+ values[step] = value.flatten()
236
+ actions[step] = action
237
+ logprobs[step] = logprob
238
+
239
+ # TRY NOT TO MODIFY: execute the game and log data.
240
+ next_obs, reward, next_done, info = envs.step(action.cpu().numpy())
241
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
242
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
243
+
244
+ for item in info:
245
+ if "episode" in item.keys():
246
+ print(f"global_step={global_step}, episodic_return={item['episode']['r']}")
247
+ writer.add_scalar("charts/episodic_return", item["episode"]["r"], global_step)
248
+ writer.add_scalar("charts/episodic_length", item["episode"]["l"], global_step)
249
+ break
250
+
251
+ # bootstrap value if not done
252
+ with torch.no_grad():
253
+ next_value = agent.get_value(next_obs).reshape(1, -1)
254
+ advantages = torch.zeros_like(rewards).to(device)
255
+ lastgaelam = 0
256
+ for t in reversed(range(args.num_steps)):
257
+ if t == args.num_steps - 1:
258
+ nextnonterminal = 1.0 - next_done
259
+ nextvalues = next_value
260
+ else:
261
+ nextnonterminal = 1.0 - dones[t + 1]
262
+ nextvalues = values[t + 1]
263
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
264
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
265
+ returns = advantages + values
266
+
267
+ # flatten the batch
268
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
269
+ b_logprobs = logprobs.reshape(-1)
270
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
271
+ b_advantages = advantages.reshape(-1)
272
+ b_returns = returns.reshape(-1)
273
+ b_values = values.reshape(-1)
274
+
275
+ # Optimizing the policy and value network
276
+ b_inds = np.arange(args.batch_size)
277
+ clipfracs = []
278
+ for epoch in range(args.update_epochs):
279
+ np.random.shuffle(b_inds)
280
+ for start in range(0, args.batch_size, args.minibatch_size):
281
+ end = start + args.minibatch_size
282
+ mb_inds = b_inds[start:end]
283
+
284
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
285
+ logratio = newlogprob - b_logprobs[mb_inds]
286
+ ratio = logratio.exp()
287
+
288
+ with torch.no_grad():
289
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
290
+ old_approx_kl = (-logratio).mean()
291
+ approx_kl = ((ratio - 1) - logratio).mean()
292
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
293
+
294
+ mb_advantages = b_advantages[mb_inds]
295
+ if args.norm_adv:
296
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
297
+
298
+ # Policy loss
299
+ pg_loss1 = -mb_advantages * ratio
300
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
301
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
302
+
303
+ # Value loss
304
+ newvalue = newvalue.view(-1)
305
+ if args.clip_vloss:
306
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
307
+ v_clipped = b_values[mb_inds] + torch.clamp(
308
+ newvalue - b_values[mb_inds],
309
+ -args.clip_coef,
310
+ args.clip_coef,
311
+ )
312
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
313
+ v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped)
314
+ v_loss = 0.5 * v_loss_max.mean()
315
+ else:
316
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
317
+
318
+ entropy_loss = entropy.mean()
319
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
320
+
321
+ optimizer.zero_grad()
322
+ loss.backward()
323
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
324
+ optimizer.step()
325
+
326
+ if args.target_kl is not None and approx_kl > args.target_kl:
327
+ break
328
+
329
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
330
+ var_y = np.var(y_true)
331
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
332
+
333
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
334
+ writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step)
335
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
336
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
337
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
338
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
339
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
340
+ writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step)
341
+ writer.add_scalar("losses/explained_variance", explained_var, global_step)
342
+ print("SPS:", int(global_step / (time.time() - start_time)))
343
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
344
+
345
+ envs.close()
346
+ writer.close()
cleanrl/cleanrl/ppo_rnd_envpool.py ADDED
@@ -0,0 +1,539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/ppo-rnd/#ppo_rnd_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.nn.functional as F
14
+ import torch.optim as optim
15
+ import tyro
16
+ from gym.wrappers.normalize import RunningMeanStd
17
+ from torch.distributions.categorical import Categorical
18
+ from torch.utils.tensorboard import SummaryWriter
19
+
20
+
21
+ @dataclass
22
+ class Args:
23
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
24
+ """the name of this experiment"""
25
+ seed: int = 1
26
+ """seed of the experiment"""
27
+ torch_deterministic: bool = True
28
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
29
+ cuda: bool = True
30
+ """if toggled, cuda will be enabled by default"""
31
+ track: bool = False
32
+ """if toggled, this experiment will be tracked with Weights and Biases"""
33
+ wandb_project_name: str = "cleanRL"
34
+ """the wandb's project name"""
35
+ wandb_entity: str = None
36
+ """the entity (team) of wandb's project"""
37
+ capture_video: bool = False
38
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
39
+
40
+ # Algorithm specific arguments
41
+ env_id: str = "MontezumaRevenge-v5"
42
+ """the id of the environment"""
43
+ total_timesteps: int = 2000000000
44
+ """total timesteps of the experiments"""
45
+ learning_rate: float = 1e-4
46
+ """the learning rate of the optimizer"""
47
+ num_envs: int = 128
48
+ """the number of parallel game environments"""
49
+ num_steps: int = 128
50
+ """the number of steps to run in each environment per policy rollout"""
51
+ anneal_lr: bool = True
52
+ """Toggle learning rate annealing for policy and value networks"""
53
+ gamma: float = 0.999
54
+ """the discount factor gamma"""
55
+ gae_lambda: float = 0.95
56
+ """the lambda for the general advantage estimation"""
57
+ num_minibatches: int = 4
58
+ """the number of mini-batches"""
59
+ update_epochs: int = 4
60
+ """the K epochs to update the policy"""
61
+ norm_adv: bool = True
62
+ """Toggles advantages normalization"""
63
+ clip_coef: float = 0.1
64
+ """the surrogate clipping coefficient"""
65
+ clip_vloss: bool = True
66
+ """Toggles whether or not to use a clipped loss for the value function, as per the paper."""
67
+ ent_coef: float = 0.001
68
+ """coefficient of the entropy"""
69
+ vf_coef: float = 0.5
70
+ """coefficient of the value function"""
71
+ max_grad_norm: float = 0.5
72
+ """the maximum norm for the gradient clipping"""
73
+ target_kl: float = None
74
+ """the target KL divergence threshold"""
75
+
76
+ # RND arguments
77
+ update_proportion: float = 0.25
78
+ """proportion of exp used for predictor update"""
79
+ int_coef: float = 1.0
80
+ """coefficient of extrinsic reward"""
81
+ ext_coef: float = 2.0
82
+ """coefficient of intrinsic reward"""
83
+ int_gamma: float = 0.99
84
+ """Intrinsic reward discount rate"""
85
+ num_iterations_obs_norm_init: int = 50
86
+ """number of iterations to initialize the observations normalization parameters"""
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
+
96
+
97
+ class RecordEpisodeStatistics(gym.Wrapper):
98
+ def __init__(self, env, deque_size=100):
99
+ super().__init__(env)
100
+ self.num_envs = getattr(env, "num_envs", 1)
101
+ self.episode_returns = None
102
+ self.episode_lengths = None
103
+
104
+ def reset(self, **kwargs):
105
+ observations = super().reset(**kwargs)
106
+ self.episode_returns = np.zeros(self.num_envs, dtype=np.float32)
107
+ self.episode_lengths = np.zeros(self.num_envs, dtype=np.int32)
108
+ self.lives = np.zeros(self.num_envs, dtype=np.int32)
109
+ self.returned_episode_returns = np.zeros(self.num_envs, dtype=np.float32)
110
+ self.returned_episode_lengths = np.zeros(self.num_envs, dtype=np.int32)
111
+ return observations
112
+
113
+ def step(self, action):
114
+ observations, rewards, dones, infos = super().step(action)
115
+ self.episode_returns += infos["reward"]
116
+ self.episode_lengths += 1
117
+ self.returned_episode_returns[:] = self.episode_returns
118
+ self.returned_episode_lengths[:] = self.episode_lengths
119
+ self.episode_returns *= 1 - infos["terminated"]
120
+ self.episode_lengths *= 1 - infos["terminated"]
121
+ infos["r"] = self.returned_episode_returns
122
+ infos["l"] = self.returned_episode_lengths
123
+ return (
124
+ observations,
125
+ rewards,
126
+ dones,
127
+ infos,
128
+ )
129
+
130
+
131
+ # ALGO LOGIC: initialize agent here:
132
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
133
+ torch.nn.init.orthogonal_(layer.weight, std)
134
+ torch.nn.init.constant_(layer.bias, bias_const)
135
+ return layer
136
+
137
+
138
+ class Agent(nn.Module):
139
+ def __init__(self, envs):
140
+ super().__init__()
141
+ self.network = nn.Sequential(
142
+ layer_init(nn.Conv2d(4, 32, 8, stride=4)),
143
+ nn.ReLU(),
144
+ layer_init(nn.Conv2d(32, 64, 4, stride=2)),
145
+ nn.ReLU(),
146
+ layer_init(nn.Conv2d(64, 64, 3, stride=1)),
147
+ nn.ReLU(),
148
+ nn.Flatten(),
149
+ layer_init(nn.Linear(64 * 7 * 7, 256)),
150
+ nn.ReLU(),
151
+ layer_init(nn.Linear(256, 448)),
152
+ nn.ReLU(),
153
+ )
154
+ self.extra_layer = nn.Sequential(layer_init(nn.Linear(448, 448), std=0.1), nn.ReLU())
155
+ self.actor = nn.Sequential(
156
+ layer_init(nn.Linear(448, 448), std=0.01),
157
+ nn.ReLU(),
158
+ layer_init(nn.Linear(448, envs.single_action_space.n), std=0.01),
159
+ )
160
+ self.critic_ext = layer_init(nn.Linear(448, 1), std=0.01)
161
+ self.critic_int = layer_init(nn.Linear(448, 1), std=0.01)
162
+
163
+ def get_action_and_value(self, x, action=None):
164
+ hidden = self.network(x / 255.0)
165
+ logits = self.actor(hidden)
166
+ probs = Categorical(logits=logits)
167
+ features = self.extra_layer(hidden)
168
+ if action is None:
169
+ action = probs.sample()
170
+ return (
171
+ action,
172
+ probs.log_prob(action),
173
+ probs.entropy(),
174
+ self.critic_ext(features + hidden),
175
+ self.critic_int(features + hidden),
176
+ )
177
+
178
+ def get_value(self, x):
179
+ hidden = self.network(x / 255.0)
180
+ features = self.extra_layer(hidden)
181
+ return self.critic_ext(features + hidden), self.critic_int(features + hidden)
182
+
183
+
184
+ class RNDModel(nn.Module):
185
+ def __init__(self, input_size, output_size):
186
+ super().__init__()
187
+
188
+ self.input_size = input_size
189
+ self.output_size = output_size
190
+
191
+ feature_output = 7 * 7 * 64
192
+
193
+ # Prediction network
194
+ self.predictor = nn.Sequential(
195
+ layer_init(nn.Conv2d(in_channels=1, out_channels=32, kernel_size=8, stride=4)),
196
+ nn.LeakyReLU(),
197
+ layer_init(nn.Conv2d(in_channels=32, out_channels=64, kernel_size=4, stride=2)),
198
+ nn.LeakyReLU(),
199
+ layer_init(nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1)),
200
+ nn.LeakyReLU(),
201
+ nn.Flatten(),
202
+ layer_init(nn.Linear(feature_output, 512)),
203
+ nn.ReLU(),
204
+ layer_init(nn.Linear(512, 512)),
205
+ nn.ReLU(),
206
+ layer_init(nn.Linear(512, 512)),
207
+ )
208
+
209
+ # Target network
210
+ self.target = nn.Sequential(
211
+ layer_init(nn.Conv2d(in_channels=1, out_channels=32, kernel_size=8, stride=4)),
212
+ nn.LeakyReLU(),
213
+ layer_init(nn.Conv2d(in_channels=32, out_channels=64, kernel_size=4, stride=2)),
214
+ nn.LeakyReLU(),
215
+ layer_init(nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1)),
216
+ nn.LeakyReLU(),
217
+ nn.Flatten(),
218
+ layer_init(nn.Linear(feature_output, 512)),
219
+ )
220
+
221
+ # target network is not trainable
222
+ for param in self.target.parameters():
223
+ param.requires_grad = False
224
+
225
+ def forward(self, next_obs):
226
+ target_feature = self.target(next_obs)
227
+ predict_feature = self.predictor(next_obs)
228
+
229
+ return predict_feature, target_feature
230
+
231
+
232
+ class RewardForwardFilter:
233
+ def __init__(self, gamma):
234
+ self.rewems = None
235
+ self.gamma = gamma
236
+
237
+ def update(self, rews):
238
+ if self.rewems is None:
239
+ self.rewems = rews
240
+ else:
241
+ self.rewems = self.rewems * self.gamma + rews
242
+ return self.rewems
243
+
244
+
245
+ if __name__ == "__main__":
246
+ args = tyro.cli(Args)
247
+ args.batch_size = int(args.num_envs * args.num_steps)
248
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
249
+ args.num_iterations = args.total_timesteps // args.batch_size
250
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
251
+ if args.track:
252
+ import wandb
253
+
254
+ wandb.init(
255
+ project=args.wandb_project_name,
256
+ entity=args.wandb_entity,
257
+ sync_tensorboard=True,
258
+ config=vars(args),
259
+ name=run_name,
260
+ monitor_gym=True,
261
+ save_code=True,
262
+ )
263
+ writer = SummaryWriter(f"runs/{run_name}")
264
+ writer.add_text(
265
+ "hyperparameters",
266
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
267
+ )
268
+
269
+ # TRY NOT TO MODIFY: seeding
270
+ random.seed(args.seed)
271
+ np.random.seed(args.seed)
272
+ torch.manual_seed(args.seed)
273
+ torch.backends.cudnn.deterministic = args.torch_deterministic
274
+
275
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
276
+
277
+ # env setup
278
+ envs = envpool.make(
279
+ args.env_id,
280
+ env_type="gym",
281
+ num_envs=args.num_envs,
282
+ episodic_life=True,
283
+ reward_clip=True,
284
+ seed=args.seed,
285
+ repeat_action_probability=0.25,
286
+ )
287
+ envs.num_envs = args.num_envs
288
+ envs.single_action_space = envs.action_space
289
+ envs.single_observation_space = envs.observation_space
290
+ envs = RecordEpisodeStatistics(envs)
291
+ assert isinstance(envs.action_space, gym.spaces.Discrete), "only discrete action space is supported"
292
+
293
+ agent = Agent(envs).to(device)
294
+ rnd_model = RNDModel(4, envs.single_action_space.n).to(device)
295
+ combined_parameters = list(agent.parameters()) + list(rnd_model.predictor.parameters())
296
+ optimizer = optim.Adam(
297
+ combined_parameters,
298
+ lr=args.learning_rate,
299
+ eps=1e-5,
300
+ )
301
+
302
+ reward_rms = RunningMeanStd()
303
+ obs_rms = RunningMeanStd(shape=(1, 1, 84, 84))
304
+ discounted_reward = RewardForwardFilter(args.int_gamma)
305
+
306
+ # ALGO Logic: Storage setup
307
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
308
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
309
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
310
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
311
+ curiosity_rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
312
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
313
+ ext_values = torch.zeros((args.num_steps, args.num_envs)).to(device)
314
+ int_values = torch.zeros((args.num_steps, args.num_envs)).to(device)
315
+ avg_returns = deque(maxlen=20)
316
+
317
+ # TRY NOT TO MODIFY: start the game
318
+ global_step = 0
319
+ start_time = time.time()
320
+ next_obs = torch.Tensor(envs.reset()).to(device)
321
+ next_done = torch.zeros(args.num_envs).to(device)
322
+ num_updates = args.total_timesteps // args.batch_size
323
+
324
+ print("Start to initialize observation normalization parameter.....")
325
+ next_ob = []
326
+ for step in range(args.num_steps * args.num_iterations_obs_norm_init):
327
+ acs = np.random.randint(0, envs.single_action_space.n, size=(args.num_envs,))
328
+ s, r, d, _ = envs.step(acs)
329
+ next_ob += s[:, 3, :, :].reshape([-1, 1, 84, 84]).tolist()
330
+
331
+ if len(next_ob) % (args.num_steps * args.num_envs) == 0:
332
+ next_ob = np.stack(next_ob)
333
+ obs_rms.update(next_ob)
334
+ next_ob = []
335
+ print("End to initialize...")
336
+
337
+ for update in range(1, num_updates + 1):
338
+ # Annealing the rate if instructed to do so.
339
+ if args.anneal_lr:
340
+ frac = 1.0 - (update - 1.0) / num_updates
341
+ lrnow = frac * args.learning_rate
342
+ optimizer.param_groups[0]["lr"] = lrnow
343
+
344
+ for step in range(0, args.num_steps):
345
+ global_step += 1 * args.num_envs
346
+ obs[step] = next_obs
347
+ dones[step] = next_done
348
+
349
+ # ALGO LOGIC: action logic
350
+ with torch.no_grad():
351
+ value_ext, value_int = agent.get_value(obs[step])
352
+ ext_values[step], int_values[step] = (
353
+ value_ext.flatten(),
354
+ value_int.flatten(),
355
+ )
356
+ action, logprob, _, _, _ = agent.get_action_and_value(obs[step])
357
+
358
+ actions[step] = action
359
+ logprobs[step] = logprob
360
+
361
+ # TRY NOT TO MODIFY: execute the game and log data.
362
+ next_obs, reward, done, info = envs.step(action.cpu().numpy())
363
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
364
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(done).to(device)
365
+ rnd_next_obs = (
366
+ (
367
+ (next_obs[:, 3, :, :].reshape(args.num_envs, 1, 84, 84) - torch.from_numpy(obs_rms.mean).to(device))
368
+ / torch.sqrt(torch.from_numpy(obs_rms.var).to(device))
369
+ ).clip(-5, 5)
370
+ ).float()
371
+ target_next_feature = rnd_model.target(rnd_next_obs)
372
+ predict_next_feature = rnd_model.predictor(rnd_next_obs)
373
+ curiosity_rewards[step] = ((target_next_feature - predict_next_feature).pow(2).sum(1) / 2).data
374
+ for idx, d in enumerate(done):
375
+ if d and info["lives"][idx] == 0:
376
+ avg_returns.append(info["r"][idx])
377
+ epi_ret = np.average(avg_returns)
378
+ print(
379
+ f"global_step={global_step}, episodic_return={info['r'][idx]}, curiosity_reward={np.mean(curiosity_rewards[step].cpu().numpy())}"
380
+ )
381
+ writer.add_scalar("charts/avg_episodic_return", epi_ret, global_step)
382
+ writer.add_scalar("charts/episodic_return", info["r"][idx], global_step)
383
+ writer.add_scalar(
384
+ "charts/episode_curiosity_reward",
385
+ curiosity_rewards[step][idx],
386
+ global_step,
387
+ )
388
+ writer.add_scalar("charts/episodic_length", info["l"][idx], global_step)
389
+
390
+ curiosity_reward_per_env = np.array(
391
+ [discounted_reward.update(reward_per_step) for reward_per_step in curiosity_rewards.cpu().data.numpy().T]
392
+ )
393
+ mean, std, count = (
394
+ np.mean(curiosity_reward_per_env),
395
+ np.std(curiosity_reward_per_env),
396
+ len(curiosity_reward_per_env),
397
+ )
398
+ reward_rms.update_from_moments(mean, std**2, count)
399
+
400
+ curiosity_rewards /= np.sqrt(reward_rms.var)
401
+
402
+ # bootstrap value if not done
403
+ with torch.no_grad():
404
+ next_value_ext, next_value_int = agent.get_value(next_obs)
405
+ next_value_ext, next_value_int = next_value_ext.reshape(1, -1), next_value_int.reshape(1, -1)
406
+ ext_advantages = torch.zeros_like(rewards, device=device)
407
+ int_advantages = torch.zeros_like(curiosity_rewards, device=device)
408
+ ext_lastgaelam = 0
409
+ int_lastgaelam = 0
410
+ for t in reversed(range(args.num_steps)):
411
+ if t == args.num_steps - 1:
412
+ ext_nextnonterminal = 1.0 - next_done
413
+ int_nextnonterminal = 1.0
414
+ ext_nextvalues = next_value_ext
415
+ int_nextvalues = next_value_int
416
+ else:
417
+ ext_nextnonterminal = 1.0 - dones[t + 1]
418
+ int_nextnonterminal = 1.0
419
+ ext_nextvalues = ext_values[t + 1]
420
+ int_nextvalues = int_values[t + 1]
421
+ ext_delta = rewards[t] + args.gamma * ext_nextvalues * ext_nextnonterminal - ext_values[t]
422
+ int_delta = curiosity_rewards[t] + args.int_gamma * int_nextvalues * int_nextnonterminal - int_values[t]
423
+ ext_advantages[t] = ext_lastgaelam = (
424
+ ext_delta + args.gamma * args.gae_lambda * ext_nextnonterminal * ext_lastgaelam
425
+ )
426
+ int_advantages[t] = int_lastgaelam = (
427
+ int_delta + args.int_gamma * args.gae_lambda * int_nextnonterminal * int_lastgaelam
428
+ )
429
+ ext_returns = ext_advantages + ext_values
430
+ int_returns = int_advantages + int_values
431
+
432
+ # flatten the batch
433
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
434
+ b_logprobs = logprobs.reshape(-1)
435
+ b_actions = actions.reshape(-1)
436
+ b_ext_advantages = ext_advantages.reshape(-1)
437
+ b_int_advantages = int_advantages.reshape(-1)
438
+ b_ext_returns = ext_returns.reshape(-1)
439
+ b_int_returns = int_returns.reshape(-1)
440
+ b_ext_values = ext_values.reshape(-1)
441
+
442
+ b_advantages = b_int_advantages * args.int_coef + b_ext_advantages * args.ext_coef
443
+
444
+ obs_rms.update(b_obs[:, 3, :, :].reshape(-1, 1, 84, 84).cpu().numpy())
445
+
446
+ # Optimizing the policy and value network
447
+ b_inds = np.arange(args.batch_size)
448
+
449
+ rnd_next_obs = (
450
+ (
451
+ (b_obs[:, 3, :, :].reshape(-1, 1, 84, 84) - torch.from_numpy(obs_rms.mean).to(device))
452
+ / torch.sqrt(torch.from_numpy(obs_rms.var).to(device))
453
+ ).clip(-5, 5)
454
+ ).float()
455
+
456
+ clipfracs = []
457
+ for epoch in range(args.update_epochs):
458
+ np.random.shuffle(b_inds)
459
+ for start in range(0, args.batch_size, args.minibatch_size):
460
+ end = start + args.minibatch_size
461
+ mb_inds = b_inds[start:end]
462
+
463
+ predict_next_state_feature, target_next_state_feature = rnd_model(rnd_next_obs[mb_inds])
464
+ forward_loss = F.mse_loss(
465
+ predict_next_state_feature, target_next_state_feature.detach(), reduction="none"
466
+ ).mean(-1)
467
+
468
+ mask = torch.rand(len(forward_loss), device=device)
469
+ mask = (mask < args.update_proportion).type(torch.FloatTensor).to(device)
470
+ forward_loss = (forward_loss * mask).sum() / torch.max(
471
+ mask.sum(), torch.tensor([1], device=device, dtype=torch.float32)
472
+ )
473
+ _, newlogprob, entropy, new_ext_values, new_int_values = agent.get_action_and_value(
474
+ b_obs[mb_inds], b_actions.long()[mb_inds]
475
+ )
476
+ logratio = newlogprob - b_logprobs[mb_inds]
477
+ ratio = logratio.exp()
478
+
479
+ with torch.no_grad():
480
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
481
+ old_approx_kl = (-logratio).mean()
482
+ approx_kl = ((ratio - 1) - logratio).mean()
483
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
484
+
485
+ mb_advantages = b_advantages[mb_inds]
486
+ if args.norm_adv:
487
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
488
+
489
+ # Policy loss
490
+ pg_loss1 = -mb_advantages * ratio
491
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
492
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
493
+
494
+ # Value loss
495
+ new_ext_values, new_int_values = new_ext_values.view(-1), new_int_values.view(-1)
496
+ if args.clip_vloss:
497
+ ext_v_loss_unclipped = (new_ext_values - b_ext_returns[mb_inds]) ** 2
498
+ ext_v_clipped = b_ext_values[mb_inds] + torch.clamp(
499
+ new_ext_values - b_ext_values[mb_inds],
500
+ -args.clip_coef,
501
+ args.clip_coef,
502
+ )
503
+ ext_v_loss_clipped = (ext_v_clipped - b_ext_returns[mb_inds]) ** 2
504
+ ext_v_loss_max = torch.max(ext_v_loss_unclipped, ext_v_loss_clipped)
505
+ ext_v_loss = 0.5 * ext_v_loss_max.mean()
506
+ else:
507
+ ext_v_loss = 0.5 * ((new_ext_values - b_ext_returns[mb_inds]) ** 2).mean()
508
+
509
+ int_v_loss = 0.5 * ((new_int_values - b_int_returns[mb_inds]) ** 2).mean()
510
+ v_loss = ext_v_loss + int_v_loss
511
+ entropy_loss = entropy.mean()
512
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef + forward_loss
513
+
514
+ optimizer.zero_grad()
515
+ loss.backward()
516
+ if args.max_grad_norm:
517
+ nn.utils.clip_grad_norm_(
518
+ combined_parameters,
519
+ args.max_grad_norm,
520
+ )
521
+ optimizer.step()
522
+
523
+ if args.target_kl is not None:
524
+ if approx_kl > args.target_kl:
525
+ break
526
+
527
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
528
+ writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step)
529
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
530
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
531
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
532
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
533
+ writer.add_scalar("losses/fwd_loss", forward_loss.item(), global_step)
534
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
535
+ print("SPS:", int(global_step / (time.time() - start_time)))
536
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
537
+
538
+ envs.close()
539
+ writer.close()
cleanrl/cleanrl/ppo_rubikscube_generalization.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(scramble_depth 即打乱步数 / 难度,可与 rotation 一一对应)
138
+ scramble_depth: int = 3
139
+ max_steps_env: int = 6
140
+ # 逗号分隔,如 "2,3,4,5"。在训练难度为 scramble_depth 下训练,仅在这些深度上做评估。
141
+ # 不设或留空则只在训练难度 scramble_depth 上评估(与旧行为一致)。
142
+ eval_scramble_depths: str | None = None
143
+
144
+ # runtime filled
145
+ batch_size: int = 0
146
+ minibatch_size: int = 0
147
+ num_iterations: int = 0
148
+ eval_splits: int = 20
149
+ eval_episodes: int = 10000
150
+
151
+
152
+ def make_env(idx, run_name, seed, scramble_depth, max_steps_env, capture_video=False):
153
+ def thunk():
154
+ config = RubiksCube2x2Config(scramble_depth=scramble_depth, max_steps=max_steps_env, render_mode='text')
155
+ env = RubiksCube2x2Env(config)
156
+ env = RubiksCubeWrapper(env)
157
+ env = gym.wrappers.TimeLimit(env, max_episode_steps=max_steps_env)
158
+ env = gym.wrappers.RecordEpisodeStatistics(env)
159
+ if capture_video and idx == 0:
160
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
161
+ return env
162
+ return thunk
163
+
164
+
165
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
166
+ torch.nn.init.orthogonal_(layer.weight, std)
167
+ torch.nn.init.constant_(layer.bias, bias_const)
168
+ return layer
169
+
170
+
171
+ class Agent(nn.Module):
172
+ def __init__(self, envs):
173
+ super().__init__()
174
+ obs_shape = int(np.array(envs.single_observation_space.shape).prod())
175
+ hidden = 128
176
+ self.critic = nn.Sequential(
177
+ layer_init(nn.Linear(obs_shape, hidden)),
178
+ nn.Tanh(),
179
+ layer_init(nn.Linear(hidden, hidden)),
180
+ nn.Tanh(),
181
+ layer_init(nn.Linear(hidden, 1), std=1.0),
182
+ )
183
+ self.actor = nn.Sequential(
184
+ layer_init(nn.Linear(obs_shape, hidden)),
185
+ nn.Tanh(),
186
+ layer_init(nn.Linear(hidden, hidden)),
187
+ nn.Tanh(),
188
+ layer_init(nn.Linear(hidden, envs.single_action_space.n), std=0.01),
189
+ )
190
+
191
+ def get_value(self, x):
192
+ return self.critic(x)
193
+
194
+ def get_action_and_value(self, x, action=None):
195
+ logits = self.actor(x)
196
+ probs = Categorical(logits=logits)
197
+ if action is None:
198
+ action = probs.sample()
199
+ return action, probs.log_prob(action), probs.entropy(), self.critic(x)
200
+
201
+
202
+ if __name__ == "__main__":
203
+ args = tyro.cli(Args)
204
+ args.batch_size = int(args.num_envs * args.num_steps)
205
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
206
+ args.num_iterations = args.total_timesteps // args.batch_size
207
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
208
+
209
+ if args.track:
210
+ import wandb
211
+ wandb.init(
212
+ project=args.wandb_project_name,
213
+ entity=args.wandb_entity,
214
+ config=vars(args),
215
+ name=run_name,
216
+ monitor_gym=True,
217
+ save_code=True,
218
+ )
219
+ try:
220
+ wandb.define_metric("global_step")
221
+ for prefix in ["train/*", "rollout/*", "eval/*", "losses/*", "charts/*", "perf/*"]:
222
+ wandb.define_metric(prefix, step_metric="global_step")
223
+ except Exception:
224
+ pass
225
+
226
+ # seeding
227
+ random.seed(args.seed)
228
+ np.random.seed(args.seed)
229
+ torch.manual_seed(args.seed)
230
+ torch.backends.cudnn.deterministic = args.torch_deterministic
231
+
232
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
233
+
234
+ # envs
235
+ envs = gym.vector.SyncVectorEnv([
236
+ make_env(i, run_name, args.seed, args.scramble_depth, args.max_steps_env, args.capture_video)
237
+ for i in range(args.num_envs)
238
+ ])
239
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete)
240
+
241
+ agent = Agent(envs).to(device)
242
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
243
+
244
+ # storage
245
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
246
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
247
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
248
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
249
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
250
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
251
+
252
+ # start
253
+ global_step = 0
254
+ start_time = time.time()
255
+ next_obs, _ = envs.reset(seed=args.seed)
256
+ next_obs = torch.Tensor(next_obs).to(device)
257
+ next_done = torch.zeros(args.num_envs).to(device)
258
+
259
+ # eval helper similar to FrozenLake: collect greedy eval trajectories and write metrics.json
260
+ def collect_eval_trajectories(
261
+ agent_model,
262
+ make_env_fn,
263
+ n_episodes,
264
+ step_tag,
265
+ trajectory_subtag: str | None = None,
266
+ scramble_depth_eval: int | None = None,
267
+ ):
268
+ sub = f"step_{step_tag}" if not trajectory_subtag else f"step_{step_tag}_{trajectory_subtag}"
269
+ out_dir = Path(f"runs/{run_name}/trajectories/{sub}")
270
+ out_dir.mkdir(parents=True, exist_ok=True)
271
+ out_path = out_dir / "trajectories.jsonl"
272
+ env = make_env_fn()
273
+ collected = 0
274
+ summary_returns = []
275
+ summary_success = []
276
+ with out_path.open("w") as f:
277
+ while collected < n_episodes:
278
+ state, _ = env.reset(seed=args.seed + 100000 + collected)
279
+ traj_states = [state.tolist()]
280
+ traj_actions = []
281
+ traj_rewards = []
282
+ traj_dones = []
283
+ traj_success = []
284
+ done = False
285
+ step_count = 0
286
+ max_eval_steps = getattr(env, '_max_episode_steps', None) or int(args.max_steps_env)
287
+ while not done:
288
+ with torch.no_grad():
289
+ logits = agent_model.actor(torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0))
290
+ action = int(torch.argmax(logits, dim=1).item())
291
+ next_state, reward, terminated, truncated, info = env.step(action)
292
+ traj_actions.append(int(action))
293
+ traj_rewards.append(float(reward))
294
+ step_count += 1
295
+ d = bool(terminated) or bool(truncated) or (step_count >= max_eval_steps)
296
+ traj_dones.append(d)
297
+ traj_success.append(bool((info or {}).get('success', False)))
298
+ state = next_state
299
+ traj_states.append(state.tolist())
300
+ done = d
301
+ ep_ret = float(sum(traj_rewards))
302
+ ep_succ = bool(any(traj_success))
303
+ record = {
304
+ "states": traj_states,
305
+ "actions": traj_actions,
306
+ "rewards": traj_rewards,
307
+ "dones": traj_dones,
308
+ "success": traj_success,
309
+ "episode_return": ep_ret,
310
+ "episode_success": ep_succ,
311
+ }
312
+ f.write(json.dumps(record) + "\n")
313
+ collected += 1
314
+ summary_returns.append(ep_ret)
315
+ summary_success.append(1.0 if ep_succ else 0.0)
316
+ env.close()
317
+ try:
318
+ metrics = {
319
+ "global_step": int(step_tag),
320
+ "episodes": int(n_episodes),
321
+ "success_rate": float(np.mean(summary_success)) if len(summary_success) else 0.0,
322
+ "avg_return": float(np.mean(summary_returns)) if len(summary_returns) else 0.0,
323
+ "std_return": float(np.std(summary_returns)) if len(summary_returns) else 0.0,
324
+ }
325
+ if scramble_depth_eval is not None:
326
+ metrics["scramble_depth_eval"] = int(scramble_depth_eval)
327
+ metrics["scramble_depth_train"] = int(args.scramble_depth)
328
+ with (out_dir / "metrics.json").open("w") as mf:
329
+ json.dump(metrics, mf)
330
+ except Exception as e:
331
+ print(f"Warning: failed to write eval metrics: {e}")
332
+
333
+ def parse_eval_scramble_depths(s: str | None, train_depth: int) -> List[int]:
334
+ if s is None or not str(s).strip():
335
+ return [train_depth]
336
+ return [int(x.strip()) for x in str(s).split(",") if x.strip()]
337
+
338
+ eval_depths_list = parse_eval_scramble_depths(args.eval_scramble_depths, args.scramble_depth)
339
+ print(
340
+ f"Train scramble_depth={args.scramble_depth} | "
341
+ f"Eval scramble_depths={eval_depths_list} (OOD 泛化评估)"
342
+ )
343
+
344
+ # training loop
345
+ eval_every_iters = max(1, args.num_iterations // args.eval_splits)
346
+ for iteration in range(1, args.num_iterations + 1):
347
+ # Anneal LR
348
+ if args.anneal_lr:
349
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
350
+ lrnow = frac * args.learning_rate
351
+ optimizer.param_groups[0]["lr"] = lrnow
352
+
353
+ # accumulate per-iteration episode successes
354
+ iter_successes = []
355
+ for step in range(0, args.num_steps):
356
+ global_step += args.num_envs
357
+ obs[step] = next_obs
358
+ dones[step] = next_done
359
+
360
+ with torch.no_grad():
361
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
362
+ values[step] = value.flatten()
363
+ actions[step] = action
364
+ logprobs[step] = logprob
365
+
366
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
367
+ next_done = np.logical_or(terminations, truncations)
368
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
369
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
370
+
371
+ # Episode stats logging similar to FrozenLake
372
+ try:
373
+ mask = None
374
+ if isinstance(infos, dict):
375
+ if "_episode" in infos:
376
+ mask = np.asarray(infos["_episode"]).astype(bool)
377
+ elif "episode" in infos and isinstance(infos["episode"], dict) and "_l" in infos["episode"]:
378
+ mask = np.asarray(infos["episode"]["_l"]).astype(bool)
379
+ if mask is not None and np.any(mask):
380
+ r_arr = np.asarray(infos.get("episode", {}).get("r", np.zeros_like(mask, dtype=float)))
381
+ l_arr = np.asarray(infos.get("episode", {}).get("l", np.zeros_like(mask, dtype=int)))
382
+ # prefer success from info; fallback to ep return > 0
383
+ if "success" in infos:
384
+ succ_arr = np.asarray(infos.get("success", np.zeros_like(mask, dtype=bool))).astype(float)
385
+ else:
386
+ try:
387
+ succ_arr = (np.asarray(r_arr) > 0).astype(float)
388
+ except Exception:
389
+ succ_arr = np.zeros_like(mask, dtype=float)
390
+ # collect iteration successes for training success rate
391
+ try:
392
+ for s in np.asarray(succ_arr)[mask]:
393
+ iter_successes.append(float(s))
394
+ except Exception:
395
+ pass
396
+ if args.track:
397
+ try:
398
+ import wandb
399
+ log_dict = {
400
+ "global_step": int(global_step),
401
+ "rollout/ep_rew_mean": float(np.mean(r_arr[mask])) if np.any(mask) else None,
402
+ "rollout/ep_len_mean": float(np.mean(l_arr[mask])) if np.any(mask) else None,
403
+ "rollout/success_rate": float(np.mean(succ_arr[mask])) if np.any(mask) else None,
404
+ }
405
+ wandb.log(log_dict, step=global_step)
406
+ except Exception:
407
+ pass
408
+ except Exception:
409
+ pass
410
+
411
+ # GAE
412
+ with torch.no_grad():
413
+ next_value = agent.get_value(next_obs).reshape(1, -1)
414
+ advantages = torch.zeros_like(rewards).to(device)
415
+ lastgaelam = 0
416
+ for t in reversed(range(args.num_steps)):
417
+ if t == args.num_steps - 1:
418
+ nextnonterminal = 1.0 - next_done
419
+ nextvalues = next_value
420
+ else:
421
+ nextnonterminal = 1.0 - dones[t + 1]
422
+ nextvalues = values[t + 1]
423
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
424
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
425
+ returns = advantages + values
426
+
427
+ # flatten batch
428
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
429
+ b_logprobs = logprobs.reshape(-1)
430
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
431
+ b_advantages = advantages.reshape(-1)
432
+ b_returns = returns.reshape(-1)
433
+ b_values = values.reshape(-1)
434
+
435
+ # update
436
+ b_inds = np.arange(args.batch_size)
437
+ clipfracs = []
438
+ for epoch in range(args.update_epochs):
439
+ np.random.shuffle(b_inds)
440
+ for start in range(0, args.batch_size, args.minibatch_size):
441
+ end = start + args.minibatch_size
442
+ mb_inds = b_inds[start:end]
443
+
444
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
445
+ logratio = newlogprob - b_logprobs[mb_inds]
446
+ ratio = logratio.exp()
447
+
448
+ with torch.no_grad():
449
+ old_approx_kl = (-logratio).mean()
450
+ approx_kl = ((ratio - 1) - logratio).mean()
451
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
452
+
453
+ mb_advantages = b_advantages[mb_inds]
454
+ if args.norm_adv:
455
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
456
+
457
+ pg_loss1 = -mb_advantages * ratio
458
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
459
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
460
+
461
+ newvalue = newvalue.view(-1)
462
+ if args.clip_vloss:
463
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
464
+ v_clipped = b_values[mb_inds] + torch.clamp(
465
+ newvalue - b_values[mb_inds], -args.clip_coef, args.clip_coef,
466
+ )
467
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
468
+ v_loss = 0.5 * torch.max(v_loss_unclipped, v_loss_clipped).mean()
469
+ else:
470
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
471
+
472
+ entropy_loss = entropy.mean()
473
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
474
+
475
+ optimizer.zero_grad()
476
+ loss.backward()
477
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
478
+ optimizer.step()
479
+
480
+ if args.target_kl is not None and approx_kl > args.target_kl:
481
+ break
482
+
483
+ # metrics
484
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
485
+ var_y = np.var(y_true)
486
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
487
+
488
+ sps = int(global_step / (time.time() - start_time))
489
+ train_success_rate = float(np.mean(iter_successes)) if len(iter_successes) else 0.0
490
+ print(f"Iter {iteration:4d}/{args.num_iterations} | SPS: {sps:5d} | R: {rewards.mean().item():6.3f}")
491
+ if args.track:
492
+ try:
493
+ import wandb
494
+ wandb.log({
495
+ "global_step": int(global_step),
496
+ "charts/progress": float(100.0 * iteration / max(1, args.num_iterations)),
497
+ "train/value_loss": float(v_loss.item()),
498
+ "train/policy_loss": float(pg_loss.item()),
499
+ "losses/value_loss": float(v_loss.item()),
500
+ "losses/policy_loss": float(pg_loss.item()),
501
+ "train/entropy": float(entropy_loss.item()),
502
+ "train/old_approx_kl": float(old_approx_kl.item()),
503
+ "train/approx_kl": float(approx_kl.item()),
504
+ "train/clipfrac": float(np.mean(clipfracs)) if len(clipfracs) else 0.0,
505
+ "losses/explained_variance": float(explained_var),
506
+ "charts/avg_reward": float(rewards.mean().item()),
507
+ "charts/avg_value": float(values.mean().item()),
508
+ "perf/SPS": int(sps),
509
+ "charts/SPS": int(sps),
510
+ "train/success_rate": train_success_rate,
511
+ "charts/train_success_rate": train_success_rate,
512
+ "train/learning_rate": float(optimizer.param_groups[0]["lr"]),
513
+ }, step=global_step)
514
+ except Exception:
515
+ pass
516
+
517
+ # periodic evaluation collection
518
+ if iteration % eval_every_iters == 0:
519
+ try:
520
+ wb_eval: Dict[str, Any] = {}
521
+ for ed in eval_depths_list:
522
+ subtag = f"scramble{ed}"
523
+ eval_thunk = make_env(0, run_name, args.seed + 9999, ed, args.max_steps_env, False)
524
+ collect_eval_trajectories(
525
+ agent,
526
+ eval_thunk,
527
+ n_episodes=args.eval_episodes,
528
+ step_tag=global_step,
529
+ trajectory_subtag=subtag,
530
+ scramble_depth_eval=ed,
531
+ )
532
+ if args.track:
533
+ try:
534
+ import json as _json
535
+ from pathlib import Path as _Path
536
+ mpath = _Path(f"runs/{run_name}/trajectories/step_{global_step}_{subtag}/metrics.json")
537
+ if mpath.exists():
538
+ with mpath.open("r") as mf:
539
+ metrics = _json.load(mf)
540
+ pfx = f"eval/scramble_{ed}"
541
+ wb_eval[f"{pfx}/success_rate"] = metrics.get("success_rate")
542
+ wb_eval[f"{pfx}/avg_return"] = metrics.get("avg_return")
543
+ wb_eval[f"{pfx}/std_return"] = metrics.get("std_return")
544
+ wb_eval[f"{pfx}/episodes"] = metrics.get("episodes")
545
+ except Exception:
546
+ pass
547
+ print(
548
+ f"Eval scramble_depth={ed}: collected {args.eval_episodes} trajectories "
549
+ f"at global_step {global_step}"
550
+ )
551
+ if args.track and wb_eval:
552
+ try:
553
+ import wandb
554
+ wb_eval["global_step"] = int(global_step)
555
+ wandb.log(wb_eval, step=global_step)
556
+ except Exception:
557
+ pass
558
+ except Exception as e:
559
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
560
+
561
+ envs.close()
cleanrl/cleanrl/ppo_sudoku_actionmask.py ADDED
@@ -0,0 +1,588 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PPO with Action Masking for RAGEN Sudoku (4x4, max_step=20)
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
+
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
+ # 假设 ragen 库在两级目录之上,请根据实际情况调整
20
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../'))
21
+
22
+ from ragen.env.sudoku.env import SudokuEnv
23
+ from ragen.env.sudoku.config import SudokuEnvConfig
24
+
25
+
26
+ class SudokuWrapper(gym.Env):
27
+ """
28
+ Adapter to use ragen SudokuEnv with Gymnasium vector API.
29
+ Improvements: Returns a Dict observation with 'action_mask' to prevent
30
+ the agent from modifying cells that are already filled.
31
+ """
32
+ metadata = {"render_modes": ["rgb_array", "human", "ansi"]}
33
+
34
+ def __init__(self, env: SudokuEnv, grid_size: int):
35
+ super().__init__()
36
+ self._env = env
37
+ self._size = grid_size
38
+ # 0 denotes empty, 1..grid_size denote values
39
+ self._val_dim = self._size + 1
40
+
41
+ # Actions: (row, col, num) -> Flattened
42
+ self._act_n = self._size * self._size * self._size
43
+ self.action_space = gym.spaces.Discrete(self._act_n)
44
+
45
+ # Observation: Dict with mask
46
+ self.observation_space = gym.spaces.Dict({
47
+ "observation": gym.spaces.Box(low=0.0, high=1.0, shape=(self._size * self._size * self._val_dim,), dtype=np.float32),
48
+ "action_mask": gym.spaces.Box(low=0.0, high=1.0, shape=(self._act_n,), dtype=np.float32)
49
+ })
50
+
51
+ def _encode_obs(self, text_obs: str) -> Dict[str, np.ndarray]:
52
+ # Parse the 'simple' grid format
53
+ vals: List[int] = []
54
+ for line in text_obs.splitlines():
55
+ ls = line.strip()
56
+ if len(ls) == 0: continue
57
+ if set(ls) <= {'-'}: continue
58
+ tokens = [t for t in ls.split() if t != '|']
59
+ if len(tokens) == 0: continue
60
+ for t in tokens:
61
+ if t == '.': vals.append(0)
62
+ else:
63
+ try: v = int(t)
64
+ except ValueError: v = 0
65
+ vals.append(v)
66
+
67
+ target = self._size * self._size
68
+ if len(vals) < target: vals.extend([0] * (target - len(vals)))
69
+ if len(vals) > target: vals = vals[:target]
70
+
71
+ # One-hot encode grid
72
+ grid = np.zeros((target, self._val_dim), dtype=np.float32)
73
+ # Initialize mask (1.0 = valid, 0.0 = invalid)
74
+ mask = np.ones(self._act_n, dtype=np.float32)
75
+
76
+ for i, v in enumerate(vals):
77
+ v_clamped = int(v)
78
+ if v_clamped < 0 or v_clamped > self._size:
79
+ v_clamped = 0
80
+ grid[i, v_clamped] = 1.0
81
+
82
+ # If a cell is NOT empty (v_clamped != 0), mask all actions for this cell.
83
+ # Agent should not overwrite existing numbers.
84
+ if v_clamped != 0:
85
+ start_idx = i * self._size
86
+ end_idx = start_idx + self._size
87
+ mask[start_idx:end_idx] = 0.0
88
+
89
+ return {
90
+ "observation": grid.reshape(-1),
91
+ "action_mask": mask
92
+ }
93
+
94
+ @staticmethod
95
+ def _decode_action(action_id: int, grid_size: int) -> Tuple[int, int, int]:
96
+ g = grid_size
97
+ row = action_id // (g * g)
98
+ rem = action_id % (g * g)
99
+ col = rem // g
100
+ num = (rem % g) + 1
101
+ return row, col, num
102
+
103
+ def reset(self, *, seed: int | None = None, options: Dict[str, Any] | None = None):
104
+ text_obs = self._env.reset(seed=seed)
105
+ obs = self._encode_obs(text_obs)
106
+ return obs, {}
107
+
108
+ def step(self, action: int):
109
+ row, col, num = self._decode_action(int(action), self._size)
110
+ act_str = f"{row+1},{col+1},{num}"
111
+ text_obs, reward, done, info = self._env.step(act_str)
112
+ obs = self._encode_obs(text_obs)
113
+ terminated = bool(done)
114
+ truncated = False
115
+ return obs, float(reward), terminated, truncated, info or {}
116
+
117
+ def render(self):
118
+ return self._env.render()
119
+
120
+ def close(self):
121
+ self._env.close()
122
+
123
+
124
+ @dataclass
125
+ class Args:
126
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
127
+ seed: int = 1
128
+ torch_deterministic: bool = True
129
+ cuda: bool = True
130
+ track: bool = True
131
+ wandb_project_name: str = "cleanRL"
132
+ wandb_entity: str | None = None
133
+ capture_video: bool = False
134
+
135
+ # Algorithm
136
+ env_id: str = "Sudoku"
137
+ total_timesteps: int = 2000_000
138
+ learning_rate: float = 3e-4
139
+ num_envs: int = 8
140
+ num_steps: int = 128
141
+ anneal_lr: bool = True
142
+ gamma: float = 0.99
143
+ gae_lambda: float = 0.95
144
+ num_minibatches: int = 4
145
+ update_epochs: int = 4
146
+ norm_adv: bool = True
147
+ clip_coef: float = 0.2
148
+ clip_vloss: bool = True
149
+ ent_coef: float = 0.01
150
+ vf_coef: float = 0.5
151
+ max_grad_norm: float = 0.5
152
+ target_kl: float | None = None
153
+
154
+ # Sudoku specific
155
+ grid_size: int = 4
156
+ difficulty: str = "easy"
157
+
158
+ # runtime filled
159
+ batch_size: int = 0
160
+ minibatch_size: int = 0
161
+ num_iterations: int = 0
162
+
163
+ # eval
164
+ eval_splits: int = 40
165
+ eval_episodes: int = 10000
166
+
167
+
168
+ def make_env(idx, run_name, seed, grid_size, difficulty, capture_video=False):
169
+ def thunk():
170
+ config = SudokuEnvConfig(
171
+ grid_size=grid_size,
172
+ difficulty=difficulty,
173
+ render_mode='text',
174
+ render_format='simple',
175
+ )
176
+ env = SudokuEnv(config)
177
+ env = SudokuWrapper(env, grid_size)
178
+ # Use env's own max_steps default if available, otherwise a sane cap
179
+ # Keeping your request for strict step limit logic, although wrapper enforces logic
180
+ max_steps = 81
181
+ # max_steps = int(grid_size * grid_size * 6)
182
+ env = gym.wrappers.TimeLimit(env, max_episode_steps=max_steps)
183
+ env = gym.wrappers.RecordEpisodeStatistics(env)
184
+ if capture_video and idx == 0:
185
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
186
+ return env
187
+ return thunk
188
+
189
+
190
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
191
+ torch.nn.init.orthogonal_(layer.weight, std)
192
+ torch.nn.init.constant_(layer.bias, bias_const)
193
+ return layer
194
+
195
+
196
+ class Agent(nn.Module):
197
+ def __init__(self, envs):
198
+ super().__init__()
199
+ # Accessing the shape from the Dict space
200
+ obs_shape = int(np.array(envs.single_observation_space['observation'].shape).prod())
201
+ hidden = 256 # Increased hidden size slightly for better capacity
202
+
203
+ self.critic = nn.Sequential(
204
+ layer_init(nn.Linear(obs_shape, hidden)),
205
+ nn.Tanh(),
206
+ layer_init(nn.Linear(hidden, hidden)),
207
+ nn.Tanh(),
208
+ layer_init(nn.Linear(hidden, 1), std=1.0),
209
+ )
210
+ self.actor = nn.Sequential(
211
+ layer_init(nn.Linear(obs_shape, hidden)),
212
+ nn.Tanh(),
213
+ layer_init(nn.Linear(hidden, hidden)),
214
+ nn.Tanh(),
215
+ layer_init(nn.Linear(hidden, envs.single_action_space.n), std=0.01),
216
+ )
217
+
218
+ def get_value(self, x):
219
+ return self.critic(x)
220
+
221
+ def get_action_and_value(self, x, action=None, action_mask=None):
222
+ logits = self.actor(x)
223
+
224
+ # Apply Action Masking
225
+ if action_mask is not None:
226
+ # Set logits of invalid actions to a very large negative number
227
+ logits = logits + (action_mask - 1.0) * 1e8
228
+
229
+ probs = Categorical(logits=logits)
230
+ if action is None:
231
+ action = probs.sample()
232
+ return action, probs.log_prob(action), probs.entropy(), self.critic(x)
233
+
234
+
235
+ if __name__ == "__main__":
236
+ args = tyro.cli(Args)
237
+ args.batch_size = int(args.num_envs * args.num_steps)
238
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
239
+ args.num_iterations = args.total_timesteps // args.batch_size
240
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
241
+
242
+ if args.track:
243
+ import wandb
244
+ wandb.init(
245
+ project=args.wandb_project_name,
246
+ entity=args.wandb_entity,
247
+ config=vars(args),
248
+ name=run_name,
249
+ monitor_gym=True,
250
+ save_code=True,
251
+ )
252
+ try:
253
+ wandb.define_metric("global_step")
254
+ for prefix in ["train/*", "rollout/*", "eval/*", "losses/*", "charts/*", "perf/*"]:
255
+ wandb.define_metric(prefix, step_metric="global_step")
256
+ except Exception:
257
+ pass
258
+
259
+ # seeding
260
+ random.seed(args.seed)
261
+ np.random.seed(args.seed)
262
+ torch.manual_seed(args.seed)
263
+ torch.backends.cudnn.deterministic = args.torch_deterministic
264
+
265
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
266
+
267
+ # envs
268
+ envs = gym.vector.SyncVectorEnv([
269
+ make_env(i, run_name, args.seed, args.grid_size, args.difficulty, args.capture_video)
270
+ for i in range(args.num_envs)
271
+ ])
272
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete)
273
+
274
+ agent = Agent(envs).to(device)
275
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
276
+
277
+ # storage
278
+ # Note: obs storage now only stores the flattened grid part
279
+ obs_shape = envs.single_observation_space['observation'].shape
280
+ mask_shape = envs.single_observation_space['action_mask'].shape
281
+
282
+ obs = torch.zeros((args.num_steps, args.num_envs) + obs_shape).to(device)
283
+ masks = torch.zeros((args.num_steps, args.num_envs) + mask_shape).to(device) # Storage for masks
284
+
285
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
286
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
287
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
288
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
289
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
290
+
291
+ # start
292
+ global_step = 0
293
+ start_time = time.time()
294
+
295
+ # envs.reset() returns a Dict of stacked arrays
296
+ next_obs_dict, _ = envs.reset(seed=args.seed)
297
+ next_obs = torch.Tensor(next_obs_dict['observation']).to(device)
298
+ next_mask = torch.Tensor(next_obs_dict['action_mask']).to(device)
299
+ next_done = torch.zeros(args.num_envs).to(device)
300
+
301
+ episode_returns = []
302
+ episode_steps = []
303
+ episode_successes = []
304
+
305
+ # Eval helper
306
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes, step_tag):
307
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
308
+ out_dir.mkdir(parents=True, exist_ok=True)
309
+ out_path = out_dir / "trajectories.jsonl"
310
+ env = make_env_fn()
311
+ collected = 0
312
+ summary_returns = []
313
+ summary_success = []
314
+ with out_path.open("w") as f:
315
+ while collected < n_episodes:
316
+ obs_dict, _ = env.reset(seed=args.seed + collected)
317
+ # Handle single env dict unpacking
318
+ state = obs_dict['observation']
319
+ mask = obs_dict['action_mask']
320
+
321
+ traj_states = [state.tolist()]
322
+ traj_actions = []
323
+ traj_rewards = []
324
+ traj_dones = []
325
+ traj_success = []
326
+ done = False
327
+ step_count = 0
328
+ max_eval_steps = getattr(env, '_max_episode_steps', None) or int(args.grid_size * args.grid_size * 6)
329
+
330
+ # Eval loop
331
+ current_obs = torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0)
332
+ current_mask = torch.tensor(mask, dtype=torch.float32, device=device).unsqueeze(0)
333
+
334
+ while not done:
335
+ with torch.no_grad():
336
+ # Pass mask to actor during eval
337
+ action, _, _, _ = agent_model.get_action_and_value(current_obs, action_mask=current_mask)
338
+ action_item = int(action.item())
339
+
340
+ next_obs_dict, reward, terminated, truncated, info = env.step(action_item)
341
+
342
+ traj_actions.append(action_item)
343
+ traj_rewards.append(float(reward))
344
+ step_count += 1
345
+ d = bool(terminated) or bool(truncated) or (step_count >= max_eval_steps)
346
+ traj_dones.append(d)
347
+ traj_success.append(bool(info.get('success', False)))
348
+
349
+ state = next_obs_dict['observation']
350
+ mask = next_obs_dict['action_mask']
351
+ current_obs = torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0)
352
+ current_mask = torch.tensor(mask, dtype=torch.float32, device=device).unsqueeze(0)
353
+
354
+ traj_states.append(state.tolist())
355
+ done = d
356
+
357
+ ep_ret = float(sum(traj_rewards))
358
+ ep_succ = bool(any(traj_success))
359
+ record = {
360
+ "states": traj_states,
361
+ "actions": traj_actions,
362
+ "rewards": traj_rewards,
363
+ "dones": traj_dones,
364
+ "success": traj_success,
365
+ "episode_return": ep_ret,
366
+ "episode_success": ep_succ,
367
+ }
368
+ f.write(json.dumps(record) + "\n")
369
+ collected += 1
370
+ summary_returns.append(ep_ret)
371
+ summary_success.append(1.0 if ep_succ else 0.0)
372
+ env.close()
373
+ try:
374
+ metrics = {
375
+ "global_step": int(step_tag),
376
+ "episodes": int(n_episodes),
377
+ "success_rate": float(np.mean(summary_success)) if len(summary_success) else 0.0,
378
+ "avg_return": float(np.mean(summary_returns)) if len(summary_returns) else 0.0,
379
+ "std_return": float(np.std(summary_returns)) if len(summary_returns) else 0.0,
380
+ }
381
+ with (out_dir / "metrics.json").open("w") as mf:
382
+ json.dump(metrics, mf)
383
+ except Exception as e:
384
+ print(f"Warning: failed to write eval metrics: {e}")
385
+
386
+ eval_every_iters = max(1, args.num_iterations // args.eval_splits)
387
+
388
+ # training loop
389
+ for iteration in range(1, args.num_iterations + 1):
390
+ if args.anneal_lr:
391
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
392
+ optimizer.param_groups[0]["lr"] = frac * args.learning_rate
393
+
394
+ for step in range(0, args.num_steps):
395
+ global_step += args.num_envs
396
+ obs[step] = next_obs
397
+ masks[step] = next_mask # Store mask
398
+ dones[step] = next_done
399
+
400
+ with torch.no_grad():
401
+ # PASS MASK HERE
402
+ action, logprob, _, value = agent.get_action_and_value(next_obs, action_mask=next_mask)
403
+ values[step] = value.flatten()
404
+ actions[step] = action
405
+ logprobs[step] = logprob
406
+
407
+ next_obs_dict, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
408
+ next_done = np.logical_or(terminations, truncations)
409
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
410
+
411
+ # Unpack dict again
412
+ next_obs = torch.Tensor(next_obs_dict['observation']).to(device)
413
+ next_mask = torch.Tensor(next_obs_dict['action_mask']).to(device)
414
+ next_done = torch.Tensor(next_done).to(device)
415
+
416
+ try:
417
+ mask = None
418
+ if isinstance(infos, dict):
419
+ if "_episode" in infos:
420
+ mask = np.asarray(infos["_episode"]).astype(bool)
421
+ elif "episode" in infos and isinstance(infos["episode"], dict) and "_l" in infos["episode"]:
422
+ mask = np.asarray(infos["episode"]["_l"]).astype(bool)
423
+ if mask is not None and np.any(mask):
424
+ r_arr = np.asarray(infos.get("episode", {}).get("r", np.zeros_like(mask, dtype=float)))
425
+ l_arr = np.asarray(infos.get("episode", {}).get("l", np.zeros_like(mask, dtype=int)))
426
+ succ_arr = np.asarray(infos.get("success", np.zeros_like(mask, dtype=bool))).astype(float)
427
+ for i in np.where(mask)[0]:
428
+ episode_returns.append(float(r_arr[i]))
429
+ episode_steps.append(global_step)
430
+ episode_successes.append(float(succ_arr[i]))
431
+ if args.track:
432
+ try:
433
+ import wandb
434
+ log_dict = {
435
+ "global_step": int(global_step),
436
+ "rollout/ep_rew_mean": float(np.mean(r_arr[mask])) if np.any(mask) else None,
437
+ "rollout/ep_len_mean": float(np.mean(l_arr[mask])) if np.any(mask) else None,
438
+ "rollout/success_rate": float(np.mean(succ_arr[mask])) if np.any(mask) else None,
439
+ }
440
+ if np.any(mask):
441
+ last_idx = np.where(mask)[0][-1]
442
+ log_dict.update({
443
+ "train/episodic_return": float(r_arr[last_idx]),
444
+ "train/episodic_length": int(l_arr[last_idx]),
445
+ "train/success": float(succ_arr[last_idx]),
446
+ "train/success_rate_100": float(np.mean(episode_successes[-100:])) if len(episode_successes) >= 100 else None,
447
+ })
448
+ wandb.log(log_dict, step=global_step)
449
+ except Exception:
450
+ pass
451
+ except Exception:
452
+ pass
453
+
454
+ # GAE
455
+ with torch.no_grad():
456
+ next_value = agent.get_value(next_obs).reshape(1, -1)
457
+ advantages = torch.zeros_like(rewards).to(device)
458
+ lastgaelam = 0
459
+ for t in reversed(range(args.num_steps)):
460
+ if t == args.num_steps - 1:
461
+ nextnonterminal = 1.0 - next_done
462
+ nextvalues = next_value
463
+ else:
464
+ nextnonterminal = 1.0 - dones[t + 1]
465
+ nextvalues = values[t + 1]
466
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
467
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
468
+ returns = advantages + values
469
+
470
+ # flatten batch
471
+ b_obs = obs.reshape((-1,) + obs_shape)
472
+ b_masks = masks.reshape((-1,) + mask_shape) # Flatten masks
473
+ b_logprobs = logprobs.reshape(-1)
474
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
475
+ b_advantages = advantages.reshape(-1)
476
+ b_returns = returns.reshape(-1)
477
+ b_values = values.reshape(-1)
478
+
479
+ # update
480
+ b_inds = np.arange(args.batch_size)
481
+ for epoch in range(args.update_epochs):
482
+ np.random.shuffle(b_inds)
483
+ for start in range(0, args.batch_size, args.minibatch_size):
484
+ end = start + args.minibatch_size
485
+ mb_inds = b_inds[start:end]
486
+
487
+ # PASS MASK HERE
488
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(
489
+ b_obs[mb_inds],
490
+ action=b_actions.long()[mb_inds],
491
+ action_mask=b_masks[mb_inds]
492
+ )
493
+
494
+ logratio = newlogprob - b_logprobs[mb_inds]
495
+ ratio = logratio.exp()
496
+
497
+ with torch.no_grad():
498
+ old_approx_kl = (-logratio).mean()
499
+ approx_kl = ((ratio - 1) - logratio).mean()
500
+
501
+ mb_advantages = b_advantages[mb_inds]
502
+ if args.norm_adv:
503
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
504
+
505
+ pg_loss1 = -mb_advantages * ratio
506
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
507
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
508
+
509
+ newvalue = newvalue.view(-1)
510
+ if args.clip_vloss:
511
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
512
+ v_clipped = b_values[mb_inds] + torch.clamp(
513
+ newvalue - b_values[mb_inds], -args.clip_coef, args.clip_coef,
514
+ )
515
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
516
+ v_loss = 0.5 * torch.max(v_loss_unclipped, v_loss_clipped).mean()
517
+ else:
518
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
519
+
520
+ entropy_loss = entropy.mean()
521
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
522
+
523
+ optimizer.zero_grad()
524
+ loss.backward()
525
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
526
+ optimizer.step()
527
+
528
+ if args.target_kl is not None and approx_kl > args.target_kl:
529
+ break
530
+
531
+ # logging
532
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
533
+ var_y = np.var(y_true)
534
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
535
+
536
+ sps = int(global_step / (time.time() - start_time))
537
+ progress = 100 * iteration / args.num_iterations
538
+ print(f"[{progress:5.1f}%] Iter {iteration:4d}/{args.num_iterations} | "
539
+ f"SPS: {sps:5d} | "
540
+ f"Reward: {rewards.mean().item():6.3f} | "
541
+ f"Val: {values.mean().item():6.3f} | "
542
+ f"VLoss: {v_loss.item():.4f} | "
543
+ f"PLoss: {pg_loss.item():.4f} | "
544
+ f"Ent: {entropy_loss.item():.4f}")
545
+ if args.track:
546
+ try:
547
+ import wandb
548
+ wandb.log({
549
+ "global_step": int(global_step),
550
+ "train/value_loss": float(v_loss.item()),
551
+ "train/policy_loss": float(pg_loss.item()),
552
+ "train/entropy": float(entropy_loss.item()),
553
+ "train/old_approx_kl": float(old_approx_kl.item()),
554
+ "train/approx_kl": float(approx_kl.item()),
555
+ "losses/explained_variance": float(explained_var),
556
+ "charts/avg_reward": float(rewards.mean().item()),
557
+ "charts/avg_value": float(values.mean().item()),
558
+ "perf/SPS": int(sps),
559
+ "train/learning_rate": float(optimizer.param_groups[0]["lr"]),
560
+ }, step=global_step)
561
+ except Exception:
562
+ pass
563
+
564
+ if iteration % eval_every_iters == 0:
565
+ try:
566
+ eval_thunk = make_env(0, run_name, args.seed + 9999, args.grid_size, args.difficulty, False)
567
+ collect_eval_trajectories(agent, eval_thunk, n_episodes=args.eval_episodes, step_tag=global_step)
568
+ if args.track:
569
+ try:
570
+ import json as _json
571
+ from pathlib import Path as _Path
572
+ mpath = _Path(f"runs/{run_name}/trajectories/step_{global_step}/metrics.json")
573
+ if mpath.exists():
574
+ with mpath.open("r") as mf:
575
+ metrics = _json.load(mf)
576
+ wandb.log({
577
+ "eval/success_rate": metrics.get("success_rate"),
578
+ "eval/avg_return": metrics.get("avg_return"),
579
+ "eval/std_return": metrics.get("std_return"),
580
+ "eval/episodes": metrics.get("episodes"),
581
+ }, step=global_step)
582
+ except Exception:
583
+ pass
584
+ print(f"Collected {args.eval_episodes} eval trajectories at global_step {global_step}")
585
+ except Exception as e:
586
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
587
+
588
+ envs.close()
cleanrl/cleanrl/ppo_sudoku_strongactionmask.py ADDED
@@ -0,0 +1,616 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PPO with Action Masking for RAGEN Sudoku (4x4, max_step=20)
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
+
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
+ # 假设 ragen 库在两级目录之上,请根据实际情况调整
20
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../'))
21
+
22
+ from ragen.env.sudoku.env import SudokuEnv
23
+ from ragen.env.sudoku.config import SudokuEnvConfig
24
+
25
+
26
+ class SudokuWrapper(gym.Env):
27
+ """
28
+ Adapter to use ragen SudokuEnv with Gymnasium vector API.
29
+ Improvements: Returns a Dict observation with 'action_mask' to prevent
30
+ the agent from modifying cells that are already filled.
31
+ """
32
+ metadata = {"render_modes": ["rgb_array", "human", "ansi"]}
33
+
34
+ def __init__(self, env: SudokuEnv, grid_size: int):
35
+ super().__init__()
36
+ self._env = env
37
+ self._size = grid_size
38
+ # 0 denotes empty, 1..grid_size denote values
39
+ self._val_dim = self._size + 1
40
+
41
+ # Actions: (row, col, num) -> Flattened
42
+ self._act_n = self._size * self._size * self._size
43
+ self.action_space = gym.spaces.Discrete(self._act_n)
44
+
45
+ # Observation: Dict with mask
46
+ self.observation_space = gym.spaces.Dict({
47
+ "observation": gym.spaces.Box(low=0.0, high=1.0, shape=(self._size * self._size * self._val_dim,), dtype=np.float32),
48
+ "action_mask": gym.spaces.Box(low=0.0, high=1.0, shape=(self._act_n,), dtype=np.float32)
49
+ })
50
+
51
+ def _encode_obs(self, text_obs: str) -> Dict[str, np.ndarray]:
52
+ # Parse the 'simple' grid format
53
+ vals: List[int] = []
54
+ for line in text_obs.splitlines():
55
+ ls = line.strip()
56
+ if len(ls) == 0: continue
57
+ if set(ls) <= {'-'}: continue
58
+ tokens = [t for t in ls.split() if t != '|']
59
+ if len(tokens) == 0: continue
60
+ for t in tokens:
61
+ if t == '.': vals.append(0)
62
+ else:
63
+ try: v = int(t)
64
+ except ValueError: v = 0
65
+ vals.append(v)
66
+
67
+ target = self._size * self._size
68
+ if len(vals) < target: vals.extend([0] * (target - len(vals)))
69
+ if len(vals) > target: vals = vals[:target]
70
+
71
+ # One-hot encode grid
72
+ grid = np.zeros((target, self._val_dim), dtype=np.float32)
73
+ # Initialize mask (1.0 = valid, 0.0 = invalid)
74
+ mask = np.zeros(self._act_n, dtype=np.float32)
75
+
76
+ for i, v in enumerate(vals):
77
+ v_clamped = int(v)
78
+ if v_clamped < 0 or v_clamped > self._size:
79
+ v_clamped = 0
80
+ grid[i, v_clamped] = 1.0
81
+
82
+ # If a cell is NOT empty (v_clamped != 0), mask all actions for this cell.
83
+ # Agent should not overwrite existing numbers.
84
+ if v_clamped != 0:
85
+ start_idx = i * self._size
86
+ end_idx = start_idx + self._size
87
+ mask[start_idx:end_idx] = 0.0
88
+
89
+ # Build current grid for validity checks
90
+ cur = np.array(vals, dtype=np.int64).reshape(self._size, self._size)
91
+ box = int(np.sqrt(self._size))
92
+
93
+ # Set mask=1 only for Sudoku-rule-valid placements on empty cells
94
+ for i, v in enumerate(vals):
95
+ if int(v) == 0:
96
+ r = i // self._size
97
+ c = i % self._size
98
+ row_vals = set(cur[r, :].tolist())
99
+ col_vals = set(cur[:, c].tolist())
100
+ br = (r // box) * box
101
+ bc = (c // box) * box
102
+ box_vals = set(cur[br:br+box, bc:bc+box].reshape(-1).tolist())
103
+ start_idx = i * self._size
104
+ for num in range(1, self._size + 1):
105
+ if (num not in row_vals) and (num not in col_vals) and (num not in box_vals):
106
+ mask[start_idx + (num - 1)] = 1.0
107
+
108
+ # Safe fallback: if no valid actions found, allow all actions on empty cells; if still none, allow all
109
+ if mask.sum() == 0:
110
+ for i, v in enumerate(vals):
111
+ if int(v) == 0:
112
+ start_idx = i * self._size
113
+ end_idx = start_idx + self._size
114
+ mask[start_idx:end_idx] = 1.0
115
+ if mask.sum() == 0:
116
+ mask[:] = 1.0
117
+
118
+ return {
119
+ "observation": grid.reshape(-1),
120
+ "action_mask": mask
121
+ }
122
+
123
+ @staticmethod
124
+ def _decode_action(action_id: int, grid_size: int) -> Tuple[int, int, int]:
125
+ g = grid_size
126
+ row = action_id // (g * g)
127
+ rem = action_id % (g * g)
128
+ col = rem // g
129
+ num = (rem % g) + 1
130
+ return row, col, num
131
+
132
+ def reset(self, *, seed: int | None = None, options: Dict[str, Any] | None = None):
133
+ text_obs = self._env.reset(seed=seed)
134
+ obs = self._encode_obs(text_obs)
135
+ return obs, {}
136
+
137
+ def step(self, action: int):
138
+ row, col, num = self._decode_action(int(action), self._size)
139
+ act_str = f"{row+1},{col+1},{num}"
140
+ text_obs, reward, done, info = self._env.step(act_str)
141
+ obs = self._encode_obs(text_obs)
142
+ terminated = bool(done)
143
+ truncated = False
144
+ return obs, float(reward), terminated, truncated, info or {}
145
+
146
+ def render(self):
147
+ return self._env.render()
148
+
149
+ def close(self):
150
+ self._env.close()
151
+
152
+
153
+ @dataclass
154
+ class Args:
155
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
156
+ seed: int = 1
157
+ torch_deterministic: bool = True
158
+ cuda: bool = True
159
+ track: bool = True
160
+ wandb_project_name: str = "cleanRL"
161
+ wandb_entity: str | None = None
162
+ capture_video: bool = False
163
+
164
+ # Algorithm
165
+ env_id: str = "Sudoku"
166
+ total_timesteps: int = 2000_000
167
+ learning_rate: float = 3e-4
168
+ num_envs: int = 8
169
+ num_steps: int = 128
170
+ anneal_lr: bool = True
171
+ gamma: float = 0.99
172
+ gae_lambda: float = 0.95
173
+ num_minibatches: int = 4
174
+ update_epochs: int = 4
175
+ norm_adv: bool = True
176
+ clip_coef: float = 0.2
177
+ clip_vloss: bool = True
178
+ ent_coef: float = 0.01
179
+ vf_coef: float = 0.5
180
+ max_grad_norm: float = 0.5
181
+ target_kl: float | None = None
182
+
183
+ # Sudoku specific
184
+ grid_size: int = 9
185
+ difficulty: str = "easy"
186
+
187
+ # runtime filled
188
+ batch_size: int = 0
189
+ minibatch_size: int = 0
190
+ num_iterations: int = 0
191
+
192
+ # eval
193
+ eval_splits: int = 2
194
+ eval_episodes: int = 4000
195
+
196
+
197
+ def make_env(idx, run_name, seed, grid_size, difficulty, capture_video=False):
198
+ def thunk():
199
+ config = SudokuEnvConfig(
200
+ grid_size=grid_size,
201
+ difficulty=difficulty,
202
+ render_mode='text',
203
+ render_format='simple',
204
+ )
205
+ env = SudokuEnv(config)
206
+ env = SudokuWrapper(env, grid_size)
207
+ # Use env's own max_steps default if available, otherwise a sane cap
208
+ # Keeping your request for strict step limit logic, although wrapper enforces logic
209
+ max_steps = 81
210
+ env = gym.wrappers.TimeLimit(env, max_episode_steps=max_steps)
211
+ env = gym.wrappers.RecordEpisodeStatistics(env)
212
+ if capture_video and idx == 0:
213
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
214
+ return env
215
+ return thunk
216
+
217
+
218
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
219
+ torch.nn.init.orthogonal_(layer.weight, std)
220
+ torch.nn.init.constant_(layer.bias, bias_const)
221
+ return layer
222
+
223
+
224
+ class Agent(nn.Module):
225
+ def __init__(self, envs):
226
+ super().__init__()
227
+ # Accessing the shape from the Dict space
228
+ obs_shape = int(np.array(envs.single_observation_space['observation'].shape).prod())
229
+ hidden = 256 # Increased hidden size slightly for better capacity
230
+
231
+ self.critic = nn.Sequential(
232
+ layer_init(nn.Linear(obs_shape, hidden)),
233
+ nn.Tanh(),
234
+ layer_init(nn.Linear(hidden, hidden)),
235
+ nn.Tanh(),
236
+ layer_init(nn.Linear(hidden, 1), std=1.0),
237
+ )
238
+ self.actor = nn.Sequential(
239
+ layer_init(nn.Linear(obs_shape, hidden)),
240
+ nn.Tanh(),
241
+ layer_init(nn.Linear(hidden, hidden)),
242
+ nn.Tanh(),
243
+ layer_init(nn.Linear(hidden, envs.single_action_space.n), std=0.01),
244
+ )
245
+
246
+ def get_value(self, x):
247
+ return self.critic(x)
248
+
249
+ def get_action_and_value(self, x, action=None, action_mask=None):
250
+ logits = self.actor(x)
251
+
252
+ # Apply Action Masking
253
+ if action_mask is not None:
254
+ # Set logits of invalid actions to a very large negative number
255
+ logits = logits + (action_mask - 1.0) * 1e8
256
+
257
+ probs = Categorical(logits=logits)
258
+ if action is None:
259
+ action = probs.sample()
260
+ return action, probs.log_prob(action), probs.entropy(), self.critic(x)
261
+
262
+
263
+ if __name__ == "__main__":
264
+ args = tyro.cli(Args)
265
+ args.batch_size = int(args.num_envs * args.num_steps)
266
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
267
+ args.num_iterations = args.total_timesteps // args.batch_size
268
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
269
+
270
+ if args.track:
271
+ import wandb
272
+ wandb.init(
273
+ project=args.wandb_project_name,
274
+ entity=args.wandb_entity,
275
+ config=vars(args),
276
+ name=run_name,
277
+ monitor_gym=True,
278
+ save_code=True,
279
+ )
280
+ try:
281
+ wandb.define_metric("global_step")
282
+ for prefix in ["train/*", "rollout/*", "eval/*", "losses/*", "charts/*", "perf/*"]:
283
+ wandb.define_metric(prefix, step_metric="global_step")
284
+ except Exception:
285
+ pass
286
+
287
+ # seeding
288
+ random.seed(args.seed)
289
+ np.random.seed(args.seed)
290
+ torch.manual_seed(args.seed)
291
+ torch.backends.cudnn.deterministic = args.torch_deterministic
292
+
293
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
294
+
295
+ # envs
296
+ envs = gym.vector.SyncVectorEnv([
297
+ make_env(i, run_name, args.seed, args.grid_size, args.difficulty, args.capture_video)
298
+ for i in range(args.num_envs)
299
+ ])
300
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete)
301
+
302
+ agent = Agent(envs).to(device)
303
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
304
+
305
+ # storage
306
+ # Note: obs storage now only stores the flattened grid part
307
+ obs_shape = envs.single_observation_space['observation'].shape
308
+ mask_shape = envs.single_observation_space['action_mask'].shape
309
+
310
+ obs = torch.zeros((args.num_steps, args.num_envs) + obs_shape).to(device)
311
+ masks = torch.zeros((args.num_steps, args.num_envs) + mask_shape).to(device) # Storage for masks
312
+
313
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
314
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
315
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
316
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
317
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
318
+
319
+ # start
320
+ global_step = 0
321
+ start_time = time.time()
322
+
323
+ # envs.reset() returns a Dict of stacked arrays
324
+ next_obs_dict, _ = envs.reset(seed=args.seed)
325
+ next_obs = torch.Tensor(next_obs_dict['observation']).to(device)
326
+ next_mask = torch.Tensor(next_obs_dict['action_mask']).to(device)
327
+ next_done = torch.zeros(args.num_envs).to(device)
328
+
329
+ episode_returns = []
330
+ episode_steps = []
331
+ episode_successes = []
332
+
333
+ # Eval helper
334
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes, step_tag):
335
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
336
+ out_dir.mkdir(parents=True, exist_ok=True)
337
+ out_path = out_dir / "trajectories.jsonl"
338
+ env = make_env_fn()
339
+ collected = 0
340
+ summary_returns = []
341
+ summary_success = []
342
+ with out_path.open("w") as f:
343
+ while collected < n_episodes:
344
+ obs_dict, _ = env.reset(seed=args.seed + collected)
345
+ # Handle single env dict unpacking
346
+ state = obs_dict['observation']
347
+ mask = obs_dict['action_mask']
348
+
349
+ traj_states = [state.tolist()]
350
+ traj_actions = []
351
+ traj_rewards = []
352
+ traj_dones = []
353
+ traj_success = []
354
+ done = False
355
+ step_count = 0
356
+ max_eval_steps = getattr(env, '_max_episode_steps', None) or int(args.grid_size * args.grid_size * 6)
357
+
358
+ # Eval loop
359
+ current_obs = torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0)
360
+ current_mask = torch.tensor(mask, dtype=torch.float32, device=device).unsqueeze(0)
361
+
362
+ while not done:
363
+ with torch.no_grad():
364
+ # Pass mask to actor during eval
365
+ action, _, _, _ = agent_model.get_action_and_value(current_obs, action_mask=current_mask)
366
+ action_item = int(action.item())
367
+
368
+ next_obs_dict, reward, terminated, truncated, info = env.step(action_item)
369
+
370
+ traj_actions.append(action_item)
371
+ traj_rewards.append(float(reward))
372
+ step_count += 1
373
+ d = bool(terminated) or bool(truncated) or (step_count >= max_eval_steps)
374
+ traj_dones.append(d)
375
+ traj_success.append(bool(info.get('success', False)))
376
+
377
+ state = next_obs_dict['observation']
378
+ mask = next_obs_dict['action_mask']
379
+ current_obs = torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0)
380
+ current_mask = torch.tensor(mask, dtype=torch.float32, device=device).unsqueeze(0)
381
+
382
+ traj_states.append(state.tolist())
383
+ done = d
384
+
385
+ ep_ret = float(sum(traj_rewards))
386
+ ep_succ = bool(any(traj_success))
387
+ record = {
388
+ "states": traj_states,
389
+ "actions": traj_actions,
390
+ "rewards": traj_rewards,
391
+ "dones": traj_dones,
392
+ "success": traj_success,
393
+ "episode_return": ep_ret,
394
+ "episode_success": ep_succ,
395
+ }
396
+ f.write(json.dumps(record) + "\n")
397
+ collected += 1
398
+ summary_returns.append(ep_ret)
399
+ summary_success.append(1.0 if ep_succ else 0.0)
400
+ env.close()
401
+ try:
402
+ metrics = {
403
+ "global_step": int(step_tag),
404
+ "episodes": int(n_episodes),
405
+ "success_rate": float(np.mean(summary_success)) if len(summary_success) else 0.0,
406
+ "avg_return": float(np.mean(summary_returns)) if len(summary_returns) else 0.0,
407
+ "std_return": float(np.std(summary_returns)) if len(summary_returns) else 0.0,
408
+ }
409
+ with (out_dir / "metrics.json").open("w") as mf:
410
+ json.dump(metrics, mf)
411
+ except Exception as e:
412
+ print(f"Warning: failed to write eval metrics: {e}")
413
+
414
+ eval_every_iters = max(1, args.num_iterations // args.eval_splits)
415
+
416
+ # training loop
417
+ for iteration in range(1, args.num_iterations + 1):
418
+ if args.anneal_lr:
419
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
420
+ optimizer.param_groups[0]["lr"] = frac * args.learning_rate
421
+
422
+ for step in range(0, args.num_steps):
423
+ global_step += args.num_envs
424
+ obs[step] = next_obs
425
+ masks[step] = next_mask # Store mask
426
+ dones[step] = next_done
427
+
428
+ with torch.no_grad():
429
+ # PASS MASK HERE
430
+ action, logprob, _, value = agent.get_action_and_value(next_obs, action_mask=next_mask)
431
+ values[step] = value.flatten()
432
+ actions[step] = action
433
+ logprobs[step] = logprob
434
+
435
+ next_obs_dict, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
436
+ next_done = np.logical_or(terminations, truncations)
437
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
438
+
439
+ # Unpack dict again
440
+ next_obs = torch.Tensor(next_obs_dict['observation']).to(device)
441
+ next_mask = torch.Tensor(next_obs_dict['action_mask']).to(device)
442
+ next_done = torch.Tensor(next_done).to(device)
443
+
444
+ try:
445
+ mask = None
446
+ if isinstance(infos, dict):
447
+ if "_episode" in infos:
448
+ mask = np.asarray(infos["_episode"]).astype(bool)
449
+ elif "episode" in infos and isinstance(infos["episode"], dict) and "_l" in infos["episode"]:
450
+ mask = np.asarray(infos["episode"]["_l"]).astype(bool)
451
+ if mask is not None and np.any(mask):
452
+ r_arr = np.asarray(infos.get("episode", {}).get("r", np.zeros_like(mask, dtype=float)))
453
+ l_arr = np.asarray(infos.get("episode", {}).get("l", np.zeros_like(mask, dtype=int)))
454
+ succ_arr = np.asarray(infos.get("success", np.zeros_like(mask, dtype=bool))).astype(float)
455
+ for i in np.where(mask)[0]:
456
+ episode_returns.append(float(r_arr[i]))
457
+ episode_steps.append(global_step)
458
+ episode_successes.append(float(succ_arr[i]))
459
+ if args.track:
460
+ try:
461
+ import wandb
462
+ log_dict = {
463
+ "global_step": int(global_step),
464
+ "rollout/ep_rew_mean": float(np.mean(r_arr[mask])) if np.any(mask) else None,
465
+ "rollout/ep_len_mean": float(np.mean(l_arr[mask])) if np.any(mask) else None,
466
+ "rollout/success_rate": float(np.mean(succ_arr[mask])) if np.any(mask) else None,
467
+ }
468
+ if np.any(mask):
469
+ last_idx = np.where(mask)[0][-1]
470
+ log_dict.update({
471
+ "train/episodic_return": float(r_arr[last_idx]),
472
+ "train/episodic_length": int(l_arr[last_idx]),
473
+ "train/success": float(succ_arr[last_idx]),
474
+ "train/success_rate_100": float(np.mean(episode_successes[-100:])) if len(episode_successes) >= 100 else None,
475
+ })
476
+ wandb.log(log_dict, step=global_step)
477
+ except Exception:
478
+ pass
479
+ except Exception:
480
+ pass
481
+
482
+ # GAE
483
+ with torch.no_grad():
484
+ next_value = agent.get_value(next_obs).reshape(1, -1)
485
+ advantages = torch.zeros_like(rewards).to(device)
486
+ lastgaelam = 0
487
+ for t in reversed(range(args.num_steps)):
488
+ if t == args.num_steps - 1:
489
+ nextnonterminal = 1.0 - next_done
490
+ nextvalues = next_value
491
+ else:
492
+ nextnonterminal = 1.0 - dones[t + 1]
493
+ nextvalues = values[t + 1]
494
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
495
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
496
+ returns = advantages + values
497
+
498
+ # flatten batch
499
+ b_obs = obs.reshape((-1,) + obs_shape)
500
+ b_masks = masks.reshape((-1,) + mask_shape) # Flatten masks
501
+ b_logprobs = logprobs.reshape(-1)
502
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
503
+ b_advantages = advantages.reshape(-1)
504
+ b_returns = returns.reshape(-1)
505
+ b_values = values.reshape(-1)
506
+
507
+ # update
508
+ b_inds = np.arange(args.batch_size)
509
+ for epoch in range(args.update_epochs):
510
+ np.random.shuffle(b_inds)
511
+ for start in range(0, args.batch_size, args.minibatch_size):
512
+ end = start + args.minibatch_size
513
+ mb_inds = b_inds[start:end]
514
+
515
+ # PASS MASK HERE
516
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(
517
+ b_obs[mb_inds],
518
+ action=b_actions.long()[mb_inds],
519
+ action_mask=b_masks[mb_inds]
520
+ )
521
+
522
+ logratio = newlogprob - b_logprobs[mb_inds]
523
+ ratio = logratio.exp()
524
+
525
+ with torch.no_grad():
526
+ old_approx_kl = (-logratio).mean()
527
+ approx_kl = ((ratio - 1) - logratio).mean()
528
+
529
+ mb_advantages = b_advantages[mb_inds]
530
+ if args.norm_adv:
531
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
532
+
533
+ pg_loss1 = -mb_advantages * ratio
534
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
535
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
536
+
537
+ newvalue = newvalue.view(-1)
538
+ if args.clip_vloss:
539
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
540
+ v_clipped = b_values[mb_inds] + torch.clamp(
541
+ newvalue - b_values[mb_inds], -args.clip_coef, args.clip_coef,
542
+ )
543
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
544
+ v_loss = 0.5 * torch.max(v_loss_unclipped, v_loss_clipped).mean()
545
+ else:
546
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
547
+
548
+ entropy_loss = entropy.mean()
549
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
550
+
551
+ optimizer.zero_grad()
552
+ loss.backward()
553
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
554
+ optimizer.step()
555
+
556
+ if args.target_kl is not None and approx_kl > args.target_kl:
557
+ break
558
+
559
+ # logging
560
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
561
+ var_y = np.var(y_true)
562
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
563
+
564
+ sps = int(global_step / (time.time() - start_time))
565
+ progress = 100 * iteration / args.num_iterations
566
+ print(f"[{progress:5.1f}%] Iter {iteration:4d}/{args.num_iterations} | "
567
+ f"SPS: {sps:5d} | "
568
+ f"Reward: {rewards.mean().item():6.3f} | "
569
+ f"Val: {values.mean().item():6.3f} | "
570
+ f"VLoss: {v_loss.item():.4f} | "
571
+ f"PLoss: {pg_loss.item():.4f} | "
572
+ f"Ent: {entropy_loss.item():.4f}")
573
+ if args.track:
574
+ try:
575
+ import wandb
576
+ wandb.log({
577
+ "global_step": int(global_step),
578
+ "train/value_loss": float(v_loss.item()),
579
+ "train/policy_loss": float(pg_loss.item()),
580
+ "train/entropy": float(entropy_loss.item()),
581
+ "train/old_approx_kl": float(old_approx_kl.item()),
582
+ "train/approx_kl": float(approx_kl.item()),
583
+ "losses/explained_variance": float(explained_var),
584
+ "charts/avg_reward": float(rewards.mean().item()),
585
+ "charts/avg_value": float(values.mean().item()),
586
+ "perf/SPS": int(sps),
587
+ "train/learning_rate": float(optimizer.param_groups[0]["lr"]),
588
+ }, step=global_step)
589
+ except Exception:
590
+ pass
591
+
592
+ if iteration % eval_every_iters == 0:
593
+ try:
594
+ eval_thunk = make_env(0, run_name, args.seed + 9999, args.grid_size, args.difficulty, False)
595
+ collect_eval_trajectories(agent, eval_thunk, n_episodes=args.eval_episodes, step_tag=global_step)
596
+ if args.track:
597
+ try:
598
+ import json as _json
599
+ from pathlib import Path as _Path
600
+ mpath = _Path(f"runs/{run_name}/trajectories/step_{global_step}/metrics.json")
601
+ if mpath.exists():
602
+ with mpath.open("r") as mf:
603
+ metrics = _json.load(mf)
604
+ wandb.log({
605
+ "eval/success_rate": metrics.get("success_rate"),
606
+ "eval/avg_return": metrics.get("avg_return"),
607
+ "eval/std_return": metrics.get("std_return"),
608
+ "eval/episodes": metrics.get("episodes"),
609
+ }, step=global_step)
610
+ except Exception:
611
+ pass
612
+ print(f"Collected {args.eval_episodes} eval trajectories at global_step {global_step}")
613
+ except Exception as e:
614
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
615
+
616
+ envs.close()
cleanrl/cleanrl/ppo_trxl/pom_env.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gymnasium as gym
2
+ import numpy as np
3
+ import pygame
4
+ from gymnasium import spaces
5
+
6
+ gym.register(
7
+ id="ProofofMemory-v0",
8
+ entry_point="pom_env:PoMEnv",
9
+ max_episode_steps=16,
10
+ )
11
+
12
+
13
+ class PoMEnv(gym.Env):
14
+ """
15
+ Proof of Concept Memory Environment
16
+
17
+ This environment is intended to assess whether the policy's memory is working.
18
+ The environment is based on a one dimensional grid where the agent can move left or right.
19
+ At both ends, a goal is spawned that is either punishing or rewarding.
20
+ During the very first two steps, the agent gets to know which goal leads to a positive or negative reward.
21
+ Afterwards, this information is hidden in the agent's observation.
22
+ The last value of the agent's observation is its current position inside the environment.
23
+ Optionally and to increase the difficulty of the task, the agent's position can be frozen until the goal information is hidden.
24
+ To further challenge the agent, the step_size can be decreased.
25
+ """
26
+
27
+ metadata = {"render_modes": ["human", "rgb_array", "debug_rgb_array"], "render_fps": 4}
28
+
29
+ def __init__(self, render_mode="human"):
30
+ self._freeze = True
31
+ self._step_size = 0.2
32
+ self._min_steps = int(1.0 / self._step_size) + 1
33
+ self._time_penalty = 0.1
34
+ self._num_show_steps = 2
35
+ self.render_mode = render_mode
36
+ glob = False
37
+
38
+ self.action_space = spaces.Discrete(2)
39
+ self.observation_space = spaces.Box(low=-1.0, high=1.0, shape=(3,), dtype=np.float32)
40
+
41
+ # Create an array with possible positions
42
+ num_steps = int(0.4 / self._step_size)
43
+ lower = min(-2.0 * self._step_size, -num_steps * self._step_size) if not glob else -1 + self._step_size
44
+ upper = max(3.0 * self._step_size, self._step_size, (num_steps + 1) * self._step_size) if not glob else 1
45
+ self.possible_positions = np.arange(lower, upper, self._step_size).clip(-1 + self._step_size, 1 - self._step_size)
46
+ self.possible_positions = list(map(lambda x: round(x, 2), self.possible_positions)) # fix floating point errors
47
+
48
+ # Pygame-related attributes for rendering
49
+ self.window = None
50
+ self.clock = None
51
+ self.width = 400
52
+ self.height = 80
53
+ self.cell_width = self.width / (2 * int(1 / self._step_size) + 1)
54
+
55
+ def step(self, action):
56
+ reward = 0.0
57
+ done = False
58
+
59
+ if self._num_show_steps > self._step_count:
60
+ self._position += self._step_size * (1 - self._freeze) if action == 1 else -self._step_size * (1 - self._freeze)
61
+ self._position = np.round(self._position, 2)
62
+
63
+ obs = np.asarray([self._goals[0], self._position, self._goals[1]], dtype=np.float32)
64
+
65
+ if self._freeze:
66
+ self._step_count += 1
67
+ return obs, reward, done, False, {}
68
+
69
+ else:
70
+ self._position += self._step_size if action == 1 else -self._step_size
71
+ self._position = np.round(self._position, 2)
72
+ obs = np.asarray([0.0, self._position, 0.0], dtype=np.float32) # mask out goal information
73
+
74
+ # Determine reward and termination
75
+ if self._position == -1.0:
76
+ if self._goals[0] == 1.0:
77
+ reward += 1.0 + self._min_steps * self._time_penalty
78
+ else:
79
+ reward -= 1.0 + self._min_steps * self._time_penalty
80
+ done = True
81
+ elif self._position == 1.0:
82
+ if self._goals[1] == 1.0:
83
+ reward += 1.0 + self._min_steps * self._time_penalty
84
+ else:
85
+ reward -= 1.0 + self._min_steps * self._time_penalty
86
+ done = True
87
+ else:
88
+ reward -= self._time_penalty
89
+ self.rewards.append(reward)
90
+
91
+ if done:
92
+ info = {"reward": sum(self.rewards), "length": len(self.rewards)}
93
+ else:
94
+ info = {}
95
+
96
+ self._step_count += 1
97
+
98
+ return obs, reward, done, False, info
99
+
100
+ def reset(self, *, seed=None, options=None):
101
+ super().reset(seed=seed)
102
+ self.rewards = []
103
+ self._position = np.random.choice(self.possible_positions)
104
+ self._step_count = 0
105
+ goals = np.asarray([-1.0, 1.0])
106
+ self._goals = goals[np.random.permutation(2)]
107
+ obs = np.asarray([self._goals[0], self._position, self._goals[1]], dtype=np.float32)
108
+ return obs, {}
109
+
110
+ def render(self):
111
+ if self.render_mode not in self.metadata["render_modes"]:
112
+ return
113
+
114
+ # Initialize Pygame
115
+ if not pygame.get_init():
116
+ pygame.init()
117
+ if self.window is None and self.render_mode == "human":
118
+ pygame.display.init()
119
+ self.window = pygame.display.set_mode((self.width, self.height))
120
+ pygame.display.set_caption("Proof of Memory Environment")
121
+ if self.clock is None and self.render_mode == "human":
122
+ self.clock = pygame.time.Clock()
123
+
124
+ # Create surface
125
+ canvas = pygame.Surface((self.width, self.height))
126
+ canvas.fill((255, 255, 255)) # Fill the background with white
127
+
128
+ # Draw grid
129
+ num_cells = 2 * int(1 / self._step_size) + 1
130
+ for i in range(num_cells):
131
+ x = i * self.cell_width
132
+ pygame.draw.rect(canvas, (200, 200, 200), pygame.Rect(x, 0, self.cell_width, self.height), 1)
133
+
134
+ # Draw agent
135
+ agent_pos = int((self._position + 1) / self._step_size)
136
+ agent_x = agent_pos * self.cell_width + self.cell_width / 2
137
+ pygame.draw.circle(canvas, (0, 0, 255), (agent_x, self.height / 2), 15)
138
+
139
+ # Draw goals
140
+ show_goals = self._num_show_steps > self._step_count
141
+ if show_goals:
142
+ left_goal_color = (0, 255, 0) if self._goals[0] > 0 else (255, 0, 0)
143
+ pygame.draw.rect(canvas, left_goal_color, pygame.Rect(0, 0, self.cell_width, self.height))
144
+ right_goal_color = (0, 255, 0) if self._goals[1] > 0 else (255, 0, 0)
145
+ pygame.draw.rect(
146
+ canvas, right_goal_color, pygame.Rect(self.width - self.cell_width, 0, self.cell_width, self.height)
147
+ )
148
+ else:
149
+ pygame.draw.rect(canvas, (200, 200, 200), pygame.Rect(0, 0, self.cell_width, self.height))
150
+ pygame.draw.rect(
151
+ canvas, (200, 200, 200), pygame.Rect(self.width - self.cell_width, 0, self.cell_width, self.height)
152
+ )
153
+
154
+ # Render text information
155
+ font = pygame.font.SysFont(None, 24)
156
+ text = font.render(f"Goals are shown: {show_goals}", True, (0, 0, 0))
157
+ canvas.blit(text, (10, 10))
158
+
159
+ if self.render_mode == "human":
160
+ self.window.blit(canvas, (0, 0))
161
+ pygame.display.flip()
162
+ self.clock.tick(self.metadata["render_fps"])
163
+ elif self.render_mode in ["rgb_array", "debug_rgb_array"]:
164
+ return np.transpose(np.array(pygame.surfarray.pixels3d(canvas)), axes=(1, 0, 2))
165
+
166
+ def close(self):
167
+ if self.window is not None:
168
+ pygame.display.quit()
169
+ pygame.quit()
170
+ self.window = None
171
+ self.clock = None
172
+
173
+
174
+ if __name__ == "__main__":
175
+ env = PoMEnv(render_mode="human")
176
+ o, _ = env.reset()
177
+ img = env.render()
178
+ done = False
179
+ rewards = []
180
+ const_action = 1
181
+ while not done:
182
+ o, r, done, _, _ = env.step(const_action)
183
+ rewards.append(r)
184
+ img = env.render()
185
+ print(f"Total reward: {sum(rewards)}, Steps: {len(rewards)}")
186
+ env.close()
cleanrl/cleanrl/ppo_trxl/ppo_trxl.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import time
4
+ from collections import deque
5
+ from dataclasses import dataclass
6
+
7
+ import gymnasium as gym
8
+ import memory_gym # noqa
9
+ import numpy as np
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.optim as optim
13
+ import tyro
14
+ from einops import rearrange
15
+ from minigrid.wrappers import ImgObsWrapper, RGBImgPartialObsWrapper
16
+ from pom_env import PoMEnv # noqa
17
+ from torch.distributions import Categorical
18
+ from torch.utils.tensorboard import SummaryWriter
19
+
20
+
21
+ @dataclass
22
+ class Args:
23
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
24
+ """the name of this experiment"""
25
+ seed: int = 1
26
+ """seed of the experiment"""
27
+ torch_deterministic: bool = True
28
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
29
+ cuda: bool = True
30
+ """if toggled, cuda will be enabled by default"""
31
+ track: bool = False
32
+ """if toggled, this experiment will be tracked with Weights and Biases"""
33
+ wandb_project_name: str = "cleanRL"
34
+ """the wandb's project name"""
35
+ wandb_entity: str = None
36
+ """the entity (team) of wandb's project"""
37
+ capture_video: bool = False
38
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
39
+ save_model: bool = False
40
+ """whether to save model into the `runs/{run_name}` folder"""
41
+
42
+ # Algorithm specific arguments
43
+ env_id: str = "MortarMayhem-Grid-v0"
44
+ """the id of the environment"""
45
+ total_timesteps: int = 200000000
46
+ """total timesteps of the experiments"""
47
+ init_lr: float = 2.75e-4
48
+ """the initial learning rate of the optimizer"""
49
+ final_lr: float = 1.0e-5
50
+ """the final learning rate of the optimizer after linearly annealing"""
51
+ num_envs: int = 32
52
+ """the number of parallel game environments"""
53
+ num_steps: int = 512
54
+ """the number of steps to run in each environment per policy rollout"""
55
+ anneal_steps: int = 32 * 512 * 10000
56
+ """the number of steps to linearly anneal the learning rate and entropy coefficient from initial to final"""
57
+ gamma: float = 0.995
58
+ """the discount factor gamma"""
59
+ gae_lambda: float = 0.95
60
+ """the lambda for the general advantage estimation"""
61
+ num_minibatches: int = 8
62
+ """the number of mini-batches"""
63
+ update_epochs: int = 3
64
+ """the K epochs to update the policy"""
65
+ norm_adv: bool = False
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
+ init_ent_coef: float = 0.0001
72
+ """initial coefficient of the entropy bonus"""
73
+ final_ent_coef: float = 0.000001
74
+ """final coefficient of the entropy bonus after linearly annealing"""
75
+ vf_coef: float = 0.5
76
+ """coefficient of the value function"""
77
+ max_grad_norm: float = 0.25
78
+ """the maximum norm for the gradient clipping"""
79
+ target_kl: float = None
80
+ """the target KL divergence threshold"""
81
+
82
+ # Transformer-XL specific arguments
83
+ trxl_num_layers: int = 3
84
+ """the number of transformer layers"""
85
+ trxl_num_heads: int = 4
86
+ """the number of heads used in multi-head attention"""
87
+ trxl_dim: int = 384
88
+ """the dimension of the transformer"""
89
+ trxl_memory_length: int = 119
90
+ """the length of TrXL's sliding memory window"""
91
+ trxl_positional_encoding: str = "absolute"
92
+ """the positional encoding type of the transformer, choices: "", "absolute", "learned" """
93
+ reconstruction_coef: float = 0.0
94
+ """the coefficient of the observation reconstruction loss, if set to 0.0 the reconstruction loss is not used"""
95
+
96
+ # To be filled on runtime
97
+ batch_size: int = 0
98
+ """the batch size (computed in runtime)"""
99
+ minibatch_size: int = 0
100
+ """the mini-batch size (computed in runtime)"""
101
+ num_iterations: int = 0
102
+ """the number of iterations (computed in runtime)"""
103
+
104
+
105
+ def make_env(env_id, idx, capture_video, run_name, render_mode="debug_rgb_array"):
106
+ if "MiniGrid" in env_id:
107
+ if render_mode == "debug_rgb_array":
108
+ render_mode = "rgb_array"
109
+
110
+ def thunk():
111
+ if "MiniGrid" in env_id:
112
+ env = gym.make(env_id, agent_view_size=3, tile_size=28, render_mode=render_mode)
113
+ env = ImgObsWrapper(RGBImgPartialObsWrapper(env, tile_size=28))
114
+ env = gym.wrappers.TimeLimit(env, 96)
115
+ else:
116
+ env = gym.make(env_id, render_mode=render_mode)
117
+ if capture_video and idx == 0:
118
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
119
+ return gym.wrappers.RecordEpisodeStatistics(env)
120
+
121
+ return thunk
122
+
123
+
124
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
125
+ torch.nn.init.orthogonal_(layer.weight, std)
126
+ # torch.nn.init.constant_(layer.bias, bias_const)
127
+ return layer
128
+
129
+
130
+ def batched_index_select(input, dim, index):
131
+ for ii in range(1, len(input.shape)):
132
+ if ii != dim:
133
+ index = index.unsqueeze(ii)
134
+ expanse = list(input.shape)
135
+ expanse[0] = -1
136
+ expanse[dim] = -1
137
+ index = index.expand(expanse)
138
+ return torch.gather(input, dim, index)
139
+
140
+
141
+ class PositionalEncoding(nn.Module):
142
+ def __init__(self, dim, min_timescale=2.0, max_timescale=1e4):
143
+ super().__init__()
144
+ freqs = torch.arange(0, dim, min_timescale)
145
+ inv_freqs = max_timescale ** (-freqs / dim)
146
+ self.register_buffer("inv_freqs", inv_freqs)
147
+
148
+ def forward(self, seq_len):
149
+ seq = torch.arange(seq_len - 1, -1, -1.0)
150
+ sinusoidal_inp = rearrange(seq, "n -> n ()") * rearrange(self.inv_freqs, "d -> () d")
151
+ pos_emb = torch.cat((sinusoidal_inp.sin(), sinusoidal_inp.cos()), dim=-1)
152
+ return pos_emb
153
+
154
+
155
+ class MultiHeadAttention(nn.Module):
156
+ """Multi Head Attention without dropout inspired by https://github.com/aladdinpersson/Machine-Learning-Collection"""
157
+
158
+ def __init__(self, embed_dim, num_heads):
159
+ super().__init__()
160
+ self.embed_dim = embed_dim
161
+ self.num_heads = num_heads
162
+ self.head_size = embed_dim // num_heads
163
+
164
+ assert self.head_size * num_heads == embed_dim, "Embedding dimension needs to be divisible by the number of heads"
165
+
166
+ self.values = nn.Linear(self.head_size, self.head_size, bias=False)
167
+ self.keys = nn.Linear(self.head_size, self.head_size, bias=False)
168
+ self.queries = nn.Linear(self.head_size, self.head_size, bias=False)
169
+ self.fc_out = nn.Linear(self.num_heads * self.head_size, embed_dim)
170
+
171
+ def forward(self, values, keys, query, mask):
172
+ N = query.shape[0]
173
+ value_len, key_len, query_len = values.shape[1], keys.shape[1], query.shape[1]
174
+
175
+ values = values.reshape(N, value_len, self.num_heads, self.head_size)
176
+ keys = keys.reshape(N, key_len, self.num_heads, self.head_size)
177
+ query = query.reshape(N, query_len, self.num_heads, self.head_size)
178
+
179
+ values = self.values(values) # (N, value_len, heads, head_dim)
180
+ keys = self.keys(keys) # (N, key_len, heads, head_dim)
181
+ queries = self.queries(query) # (N, query_len, heads, heads_dim)
182
+
183
+ # Dot-product
184
+ energy = torch.einsum("nqhd,nkhd->nhqk", [queries, keys])
185
+
186
+ # Mask padded indices so their attention weights become 0
187
+ if mask is not None:
188
+ energy = energy.masked_fill(mask.unsqueeze(1).unsqueeze(1) == 0, float("-1e20")) # -inf causes NaN
189
+
190
+ # Normalize energy values and apply softmax to retrieve the attention scores
191
+ attention = torch.softmax(
192
+ energy / (self.embed_dim ** (1 / 2)), dim=3
193
+ ) # attention shape: (N, heads, query_len, key_len)
194
+
195
+ # Scale values by attention weights
196
+ out = torch.einsum("nhql,nlhd->nqhd", [attention, values]).reshape(N, query_len, self.num_heads * self.head_size)
197
+
198
+ return self.fc_out(out), attention
199
+
200
+
201
+ class TransformerLayer(nn.Module):
202
+ def __init__(self, dim, num_heads):
203
+ super().__init__()
204
+ self.attention = MultiHeadAttention(dim, num_heads)
205
+ self.layer_norm_q = nn.LayerNorm(dim)
206
+ self.norm_kv = nn.LayerNorm(dim)
207
+ self.layer_norm_attn = nn.LayerNorm(dim)
208
+ self.fc_projection = nn.Sequential(nn.Linear(dim, dim), nn.ReLU())
209
+
210
+ def forward(self, value, key, query, mask):
211
+ # Pre-layer normalization (post-layer normalization is usually less effective)
212
+ query_ = self.layer_norm_q(query)
213
+ value = self.norm_kv(value)
214
+ key = value # K = V -> self-attention
215
+ attention, attention_weights = self.attention(value, key, query_, mask) # MHA
216
+ x = attention + query # Skip connection
217
+ x_ = self.layer_norm_attn(x) # Pre-layer normalization
218
+ forward = self.fc_projection(x_) # Forward projection
219
+ out = forward + x # Skip connection
220
+ return out, attention_weights
221
+
222
+
223
+ class Transformer(nn.Module):
224
+ def __init__(self, num_layers, dim, num_heads, max_episode_steps, positional_encoding):
225
+ super().__init__()
226
+ self.max_episode_steps = max_episode_steps
227
+ self.positional_encoding = positional_encoding
228
+ if positional_encoding == "absolute":
229
+ self.pos_embedding = PositionalEncoding(dim)
230
+ elif positional_encoding == "learned":
231
+ self.pos_embedding = nn.Parameter(torch.randn(max_episode_steps, dim))
232
+ self.transformer_layers = nn.ModuleList([TransformerLayer(dim, num_heads) for _ in range(num_layers)])
233
+
234
+ def forward(self, x, memories, mask, memory_indices):
235
+ # Add positional encoding to every transformer layer input
236
+ if self.positional_encoding == "absolute":
237
+ pos_embedding = self.pos_embedding(self.max_episode_steps)[memory_indices]
238
+ memories = memories + pos_embedding.unsqueeze(2)
239
+ elif self.positional_encoding == "learned":
240
+ memories = memories + self.pos_embedding[memory_indices].unsqueeze(2)
241
+
242
+ # Forward transformer layers and return new memories (i.e. hidden states)
243
+ out_memories = []
244
+ for i, layer in enumerate(self.transformer_layers):
245
+ out_memories.append(x.detach())
246
+ x, attention_weights = layer(
247
+ memories[:, :, i], memories[:, :, i], x.unsqueeze(1), mask
248
+ ) # args: value, key, query, mask
249
+ x = x.squeeze()
250
+ if len(x.shape) == 1:
251
+ x = x.unsqueeze(0)
252
+ return x, torch.stack(out_memories, dim=1)
253
+
254
+
255
+ class Agent(nn.Module):
256
+ def __init__(self, args, observation_space, action_space_shape, max_episode_steps):
257
+ super().__init__()
258
+ self.obs_shape = observation_space.shape
259
+ self.max_episode_steps = max_episode_steps
260
+
261
+ if len(self.obs_shape) > 1:
262
+ self.encoder = nn.Sequential(
263
+ layer_init(nn.Conv2d(3, 32, 8, stride=4)),
264
+ nn.ReLU(),
265
+ layer_init(nn.Conv2d(32, 64, 4, stride=2)),
266
+ nn.ReLU(),
267
+ layer_init(nn.Conv2d(64, 64, 3, stride=1)),
268
+ nn.ReLU(),
269
+ nn.Flatten(),
270
+ layer_init(nn.Linear(64 * 7 * 7, args.trxl_dim)),
271
+ nn.ReLU(),
272
+ )
273
+ else:
274
+ self.encoder = layer_init(nn.Linear(observation_space.shape[0], args.trxl_dim))
275
+
276
+ self.transformer = Transformer(
277
+ args.trxl_num_layers, args.trxl_dim, args.trxl_num_heads, self.max_episode_steps, args.trxl_positional_encoding
278
+ )
279
+
280
+ self.hidden_post_trxl = nn.Sequential(
281
+ layer_init(nn.Linear(args.trxl_dim, args.trxl_dim)),
282
+ nn.ReLU(),
283
+ )
284
+
285
+ self.actor_branches = nn.ModuleList(
286
+ [
287
+ layer_init(nn.Linear(args.trxl_dim, out_features=num_actions), np.sqrt(0.01))
288
+ for num_actions in action_space_shape
289
+ ]
290
+ )
291
+ self.critic = layer_init(nn.Linear(args.trxl_dim, 1), 1)
292
+
293
+ if args.reconstruction_coef > 0.0:
294
+ self.transposed_cnn = nn.Sequential(
295
+ layer_init(nn.Linear(args.trxl_dim, 64 * 7 * 7)),
296
+ nn.ReLU(),
297
+ nn.Unflatten(1, (64, 7, 7)),
298
+ layer_init(nn.ConvTranspose2d(64, 64, 3, stride=1)),
299
+ nn.ReLU(),
300
+ layer_init(nn.ConvTranspose2d(64, 32, 4, stride=2)),
301
+ nn.ReLU(),
302
+ layer_init(nn.ConvTranspose2d(32, 3, 8, stride=4)),
303
+ nn.Sigmoid(),
304
+ )
305
+
306
+ def get_value(self, x, memory, memory_mask, memory_indices):
307
+ if len(self.obs_shape) > 1:
308
+ x = self.encoder(x.permute((0, 3, 1, 2)) / 255.0)
309
+ else:
310
+ x = self.encoder(x)
311
+ x, _ = self.transformer(x, memory, memory_mask, memory_indices)
312
+ x = self.hidden_post_trxl(x)
313
+ return self.critic(x).flatten()
314
+
315
+ def get_action_and_value(self, x, memory, memory_mask, memory_indices, action=None):
316
+ if len(self.obs_shape) > 1:
317
+ x = self.encoder(x.permute((0, 3, 1, 2)) / 255.0)
318
+ else:
319
+ x = self.encoder(x)
320
+ x, memory = self.transformer(x, memory, memory_mask, memory_indices)
321
+ x = self.hidden_post_trxl(x)
322
+ self.x = x
323
+ probs = [Categorical(logits=branch(x)) for branch in self.actor_branches]
324
+ if action is None:
325
+ action = torch.stack([dist.sample() for dist in probs], dim=1)
326
+ log_probs = []
327
+ for i, dist in enumerate(probs):
328
+ log_probs.append(dist.log_prob(action[:, i]))
329
+ entropies = torch.stack([dist.entropy() for dist in probs], dim=1).sum(1).reshape(-1)
330
+ return action, torch.stack(log_probs, dim=1), entropies, self.critic(x).flatten(), memory
331
+
332
+ def reconstruct_observation(self):
333
+ x = self.transposed_cnn(self.x)
334
+ return x.permute((0, 2, 3, 1))
335
+
336
+
337
+ if __name__ == "__main__":
338
+ args = tyro.cli(Args)
339
+ args.batch_size = int(args.num_envs * args.num_steps)
340
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
341
+ args.num_iterations = args.total_timesteps // args.batch_size
342
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
343
+
344
+ if args.track:
345
+ import wandb
346
+
347
+ wandb.init(
348
+ project=args.wandb_project_name,
349
+ entity=args.wandb_entity,
350
+ sync_tensorboard=True,
351
+ config=vars(args),
352
+ name=run_name,
353
+ monitor_gym=True,
354
+ save_code=True,
355
+ )
356
+ writer = SummaryWriter(f"runs/{run_name}")
357
+ writer.add_text(
358
+ "hyperparameters",
359
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
360
+ )
361
+
362
+ # TRY NOT TO MODIFY: seeding
363
+ random.seed(args.seed)
364
+ np.random.seed(args.seed)
365
+ torch.manual_seed(args.seed)
366
+ torch.backends.cudnn.deterministic = args.torch_deterministic
367
+
368
+ # Determine the device to be used for training and set the default tensor type
369
+ if args.cuda:
370
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
371
+ torch.set_default_device(device)
372
+ else:
373
+ device = torch.device("cpu")
374
+
375
+ # Environment setup
376
+ envs = gym.vector.SyncVectorEnv(
377
+ [make_env(args.env_id, i, args.capture_video, run_name) for i in range(args.num_envs)],
378
+ )
379
+ observation_space = envs.single_observation_space
380
+ action_space_shape = (
381
+ (envs.single_action_space.n,)
382
+ if isinstance(envs.single_action_space, gym.spaces.Discrete)
383
+ else tuple(envs.single_action_space.nvec)
384
+ )
385
+ env_ids = range(args.num_envs)
386
+ env_current_episode_step = torch.zeros((args.num_envs,), dtype=torch.long)
387
+ # Determine maximum episode steps
388
+ max_episode_steps = envs.envs[0].spec.max_episode_steps
389
+ if not max_episode_steps:
390
+ envs.envs[0].reset() # Memory Gym envs need to be reset before accessing max_episode_steps
391
+ max_episode_steps = envs.envs[0].max_episode_steps
392
+ if max_episode_steps <= 0:
393
+ max_episode_steps = 1024 # Memory Gym envs have max_episode_steps set to -1
394
+ # Set transformer memory length to max episode steps if greater than max episode steps
395
+ args.trxl_memory_length = min(args.trxl_memory_length, max_episode_steps)
396
+
397
+ agent = Agent(args, observation_space, action_space_shape, max_episode_steps).to(device)
398
+ optimizer = optim.AdamW(agent.parameters(), lr=args.init_lr)
399
+ bce_loss = nn.BCELoss() # Binary cross entropy loss for observation reconstruction
400
+
401
+ # ALGO Logic: Storage setup
402
+ rewards = torch.zeros((args.num_steps, args.num_envs))
403
+ actions = torch.zeros((args.num_steps, args.num_envs, len(action_space_shape)), dtype=torch.long)
404
+ dones = torch.zeros((args.num_steps, args.num_envs))
405
+ obs = torch.zeros((args.num_steps, args.num_envs) + observation_space.shape)
406
+ log_probs = torch.zeros((args.num_steps, args.num_envs, len(action_space_shape)))
407
+ values = torch.zeros((args.num_steps, args.num_envs))
408
+ # The length of stored-memories is equal to the number of sampled episodes during training data sampling
409
+ # (num_episodes, max_episode_length, num_layers, embed_dim)
410
+ stored_memories = []
411
+ # Memory mask used during attention
412
+ stored_memory_masks = torch.zeros((args.num_steps, args.num_envs, args.trxl_memory_length), dtype=torch.bool)
413
+ # Index to select the correct episode memory from stored_memories
414
+ stored_memory_index = torch.zeros((args.num_steps, args.num_envs), dtype=torch.long)
415
+ # Indices to slice the episode memories into windows
416
+ stored_memory_indices = torch.zeros((args.num_steps, args.num_envs, args.trxl_memory_length), dtype=torch.long)
417
+
418
+ # TRY NOT TO MODIFY: start the game
419
+ global_step = 0
420
+ start_time = time.time()
421
+ episode_infos = deque(maxlen=100) # Store episode results for monitoring statistics
422
+ next_obs, _ = envs.reset(seed=args.seed)
423
+ next_obs = torch.Tensor(next_obs).to(device)
424
+ next_done = torch.zeros(args.num_envs)
425
+ # Setup placeholders for each environments's current episodic memory
426
+ next_memory = torch.zeros((args.num_envs, max_episode_steps, args.trxl_num_layers, args.trxl_dim), dtype=torch.float32)
427
+ # Generate episodic memory mask used in attention
428
+ memory_mask = torch.tril(torch.ones((args.trxl_memory_length, args.trxl_memory_length)), diagonal=-1)
429
+ """ e.g. memory mask tensor looks like this if memory_length = 6
430
+ 0, 0, 0, 0, 0, 0
431
+ 1, 0, 0, 0, 0, 0
432
+ 1, 1, 0, 0, 0, 0
433
+ 1, 1, 1, 0, 0, 0
434
+ 1, 1, 1, 1, 0, 0
435
+ 1, 1, 1, 1, 1, 0
436
+ """
437
+ # Setup memory window indices to support a sliding window over the episodic memory
438
+ repetitions = torch.repeat_interleave(
439
+ torch.arange(0, args.trxl_memory_length).unsqueeze(0), args.trxl_memory_length - 1, dim=0
440
+ ).long()
441
+ memory_indices = torch.stack(
442
+ [torch.arange(i, i + args.trxl_memory_length) for i in range(max_episode_steps - args.trxl_memory_length + 1)]
443
+ ).long()
444
+ memory_indices = torch.cat((repetitions, memory_indices))
445
+ """ e.g. the memory window indices tensor looks like this if memory_length = 4 and max_episode_length = 7:
446
+ 0, 1, 2, 3
447
+ 0, 1, 2, 3
448
+ 0, 1, 2, 3
449
+ 0, 1, 2, 3
450
+ 1, 2, 3, 4
451
+ 2, 3, 4, 5
452
+ 3, 4, 5, 6
453
+ """
454
+
455
+ for iteration in range(1, args.num_iterations + 1):
456
+ sampled_episode_infos = []
457
+
458
+ # Annealing the learning rate and entropy coefficient if instructed to do so
459
+ do_anneal = args.anneal_steps > 0 and global_step < args.anneal_steps
460
+ frac = 1 - global_step / args.anneal_steps if do_anneal else 0
461
+ lr = (args.init_lr - args.final_lr) * frac + args.final_lr
462
+ for param_group in optimizer.param_groups:
463
+ param_group["lr"] = lr
464
+ ent_coef = (args.init_ent_coef - args.final_ent_coef) * frac + args.final_ent_coef
465
+
466
+ # Init episodic memory buffer using each environments' current episodic memory
467
+ stored_memories = [next_memory[e] for e in range(args.num_envs)]
468
+ for e in range(args.num_envs):
469
+ stored_memory_index[:, e] = e
470
+
471
+ for step in range(args.num_steps):
472
+ global_step += args.num_envs
473
+
474
+ # ALGO LOGIC: action logic
475
+ with torch.no_grad():
476
+ obs[step] = next_obs
477
+ dones[step] = next_done
478
+ stored_memory_masks[step] = memory_mask[torch.clip(env_current_episode_step, 0, args.trxl_memory_length - 1)]
479
+ stored_memory_indices[step] = memory_indices[env_current_episode_step]
480
+ # Retrieve the memory window from the entire episodic memory
481
+ memory_window = batched_index_select(next_memory, 1, stored_memory_indices[step])
482
+ action, logprob, _, value, new_memory = agent.get_action_and_value(
483
+ next_obs, memory_window, stored_memory_masks[step], stored_memory_indices[step]
484
+ )
485
+ next_memory[env_ids, env_current_episode_step] = new_memory
486
+ # Store the action, log_prob, and value in the buffer
487
+ actions[step], log_probs[step], values[step] = action, logprob, value
488
+
489
+ # TRY NOT TO MODIFY: execute the game and log data.
490
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
491
+ next_done = np.logical_or(terminations, truncations)
492
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
493
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
494
+
495
+ # Reset and process episodic memory if done
496
+ for id, done in enumerate(next_done):
497
+ if done:
498
+ # Reset the environment's current timestep
499
+ env_current_episode_step[id] = 0
500
+ # Break the reference to the environment's episodic memory
501
+ mem_index = stored_memory_index[step, id]
502
+ stored_memories[mem_index] = stored_memories[mem_index].clone()
503
+ # Reset episodic memory
504
+ next_memory[id] = torch.zeros(
505
+ (max_episode_steps, args.trxl_num_layers, args.trxl_dim), dtype=torch.float32
506
+ )
507
+ if step < args.num_steps - 1:
508
+ # Store memory inside the buffer
509
+ stored_memories.append(next_memory[id])
510
+ # Store the reference of to the current episodic memory inside the buffer
511
+ stored_memory_index[step + 1 :, id] = len(stored_memories) - 1
512
+ else:
513
+ # Increment environment timestep if not done
514
+ env_current_episode_step[id] += 1
515
+
516
+ if "final_info" in infos:
517
+ for info in infos["final_info"]:
518
+ if info and "episode" in info:
519
+ sampled_episode_infos.append(info["episode"])
520
+
521
+ # Bootstrap value if not done
522
+ with torch.no_grad():
523
+ start = torch.clip(env_current_episode_step - args.trxl_memory_length, 0)
524
+ end = torch.clip(env_current_episode_step, args.trxl_memory_length)
525
+ indices = torch.stack([torch.arange(start[b], end[b]) for b in range(args.num_envs)]).long()
526
+ memory_window = batched_index_select(next_memory, 1, indices) # Retrieve the memory window from the entire episode
527
+ next_value = agent.get_value(
528
+ next_obs,
529
+ memory_window,
530
+ memory_mask[torch.clip(env_current_episode_step, 0, args.trxl_memory_length - 1)],
531
+ stored_memory_indices[-1],
532
+ )
533
+ advantages = torch.zeros_like(rewards).to(device)
534
+ lastgaelam = 0
535
+ for t in reversed(range(args.num_steps)):
536
+ if t == args.num_steps - 1:
537
+ nextnonterminal = 1.0 - next_done
538
+ nextvalues = next_value
539
+ else:
540
+ nextnonterminal = 1.0 - dones[t + 1]
541
+ nextvalues = values[t + 1]
542
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
543
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
544
+ returns = advantages + values
545
+
546
+ # Flatten the batch
547
+ b_obs = obs.reshape(-1, *obs.shape[2:])
548
+ b_logprobs = log_probs.reshape(-1, *log_probs.shape[2:])
549
+ b_actions = actions.reshape(-1, *actions.shape[2:])
550
+ b_advantages = advantages.reshape(-1)
551
+ b_returns = returns.reshape(-1)
552
+ b_values = values.reshape(-1)
553
+ b_memory_index = stored_memory_index.reshape(-1)
554
+ b_memory_indices = stored_memory_indices.reshape(-1, *stored_memory_indices.shape[2:])
555
+ b_memory_mask = stored_memory_masks.reshape(-1, *stored_memory_masks.shape[2:])
556
+ stored_memories = torch.stack(stored_memories, dim=0)
557
+
558
+ # Remove unnecessary padding from TrXL memory, if applicable
559
+ actual_max_episode_steps = (stored_memory_indices * stored_memory_masks).max().item() + 1
560
+ if actual_max_episode_steps < args.trxl_memory_length:
561
+ b_memory_indices = b_memory_indices[:, :actual_max_episode_steps]
562
+ b_memory_mask = b_memory_mask[:, :actual_max_episode_steps]
563
+ stored_memories = stored_memories[:, :actual_max_episode_steps]
564
+
565
+ # Optimizing the policy and value network
566
+ clipfracs = []
567
+ for epoch in range(args.update_epochs):
568
+ b_inds = torch.randperm(args.batch_size)
569
+ for start in range(0, args.batch_size, args.minibatch_size):
570
+ end = start + args.minibatch_size
571
+ mb_inds = b_inds[start:end]
572
+ mb_memories = stored_memories[b_memory_index[mb_inds]]
573
+ mb_memory_windows = batched_index_select(mb_memories, 1, b_memory_indices[mb_inds])
574
+
575
+ _, newlogprob, entropy, newvalue, _ = agent.get_action_and_value(
576
+ b_obs[mb_inds], mb_memory_windows, b_memory_mask[mb_inds], b_memory_indices[mb_inds], b_actions[mb_inds]
577
+ )
578
+
579
+ # Policy loss
580
+ mb_advantages = b_advantages[mb_inds]
581
+ if args.norm_adv:
582
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
583
+ mb_advantages = mb_advantages.unsqueeze(1).repeat(
584
+ 1, len(action_space_shape)
585
+ ) # Repeat is necessary for multi-discrete action spaces
586
+ logratio = newlogprob - b_logprobs[mb_inds]
587
+ ratio = torch.exp(logratio)
588
+ pgloss1 = -mb_advantages * ratio
589
+ pgloss2 = -mb_advantages * torch.clamp(ratio, 1.0 - args.clip_coef, 1.0 + args.clip_coef)
590
+ pg_loss = torch.max(pgloss1, pgloss2).mean()
591
+
592
+ # Value loss
593
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
594
+ if args.clip_vloss:
595
+ v_loss_clipped = b_values[mb_inds] + (newvalue - b_values[mb_inds]).clamp(
596
+ min=-args.clip_coef, max=args.clip_coef
597
+ )
598
+ v_loss = torch.max(v_loss_unclipped, (v_loss_clipped - b_returns[mb_inds]) ** 2).mean()
599
+ else:
600
+ v_loss = v_loss_unclipped.mean()
601
+
602
+ # Entropy loss
603
+ entropy_loss = entropy.mean()
604
+
605
+ # Combined losses
606
+ loss = pg_loss - ent_coef * entropy_loss + v_loss * args.vf_coef
607
+
608
+ # Add reconstruction loss if used
609
+ r_loss = torch.tensor(0.0)
610
+ if args.reconstruction_coef > 0.0:
611
+ r_loss = bce_loss(agent.reconstruct_observation(), b_obs[mb_inds] / 255.0)
612
+ loss += args.reconstruction_coef * r_loss
613
+
614
+ optimizer.zero_grad()
615
+ loss.backward()
616
+ torch.nn.utils.clip_grad_norm_(agent.parameters(), max_norm=args.max_grad_norm)
617
+ optimizer.step()
618
+
619
+ with torch.no_grad():
620
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
621
+ old_approx_kl = (-logratio).mean()
622
+ approx_kl = ((ratio - 1) - logratio).mean()
623
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
624
+
625
+ if args.target_kl is not None and approx_kl > args.target_kl:
626
+ break
627
+
628
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
629
+ var_y = np.var(y_true)
630
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
631
+
632
+ # Log and monitor training statistics
633
+ episode_infos.extend(sampled_episode_infos)
634
+ episode_result = {}
635
+ if len(episode_infos) > 0:
636
+ for key in episode_infos[0].keys():
637
+ episode_result[key + "_mean"] = np.mean([info[key] for info in episode_infos])
638
+
639
+ print(
640
+ "{:9} SPS={:4} return={:.2f} length={:.1f} pi_loss={:.3f} v_loss={:.3f} entropy={:.3f} r_loss={:.3f} value={:.3f} adv={:.3f}".format(
641
+ iteration,
642
+ int(global_step / (time.time() - start_time)),
643
+ episode_result["r_mean"],
644
+ episode_result["l_mean"],
645
+ pg_loss.item(),
646
+ v_loss.item(),
647
+ entropy_loss.item(),
648
+ r_loss.item(),
649
+ torch.mean(values),
650
+ torch.mean(advantages),
651
+ )
652
+ )
653
+
654
+ if episode_result:
655
+ for key in episode_result:
656
+ writer.add_scalar("episode/" + key, episode_result[key], global_step)
657
+ writer.add_scalar("episode/value_mean", torch.mean(values), global_step)
658
+ writer.add_scalar("episode/advantage_mean", torch.mean(advantages), global_step)
659
+ writer.add_scalar("charts/learning_rate", lr, global_step)
660
+ writer.add_scalar("charts/entropy_coefficient", ent_coef, global_step)
661
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
662
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
663
+ writer.add_scalar("losses/loss", loss.item(), global_step)
664
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
665
+ writer.add_scalar("losses/reconstruction_loss", r_loss.item(), global_step)
666
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
667
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
668
+ writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step)
669
+ writer.add_scalar("losses/explained_variance", explained_var, global_step)
670
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
671
+
672
+ if args.save_model:
673
+ model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
674
+ model_data = {
675
+ "model_weights": agent.state_dict(),
676
+ "args": vars(args),
677
+ }
678
+ torch.save(model_data, model_path)
679
+ print(f"model saved to {model_path}")
680
+
681
+ writer.close()
682
+ envs.close()
cleanrl/cleanrl/ppo_trxl/pyproject.toml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "ppo-trxl"
3
+ version = "1.0.1"
4
+ description = ""
5
+ authors = [{ name = "Marco Pleines", email = "marco.pleines@tu-dortmund.de" }]
6
+ requires-python = "~=3.10"
7
+ license = "MIT"
8
+ dependencies = [
9
+ "memory-gym>=1.0.2,<2",
10
+ "einops>=0.7.0,<0.8",
11
+ "minigrid>=2.3.1,<3",
12
+ "reprint>=0.6.0,<0.7",
13
+ "opencv-python>=4.9.0.80,<5",
14
+ "torch>=2.0.0,<3",
15
+ "torchaudio>=2.0.0,<3",
16
+ "wandb>=0.16.6,<0.17",
17
+ "tyro>=0.8.3,<0.9",
18
+ "tensorboard>=2.16.2,<3",
19
+ ]
20
+
21
+ [tool.uv]
22
+
23
+ [[tool.uv.index]]
24
+ name = "pytorch"
25
+ url = "https://download.pytorch.org/whl/cu118"
26
+ explicit = true
27
+
28
+ [tool.uv.sources]
29
+ torch = { index = "pytorch" }
30
+ torchaudio = { index = "pytorch" }
31
+
32
+ [build-system]
33
+ requires = ["hatchling"]
34
+ build-backend = "hatchling.build"
cleanrl/cleanrl/ppo_ultrahorizon.py ADDED
@@ -0,0 +1,490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PPO implementation for Ultrahorizon Grid Environment
2
+ # Adapted from ppo_atari.py for text-based grid environment
3
+ import os
4
+ import random
5
+ import time
6
+ from dataclasses import dataclass
7
+ import sys
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.optim as optim
17
+ import tyro
18
+ from torch.distributions.categorical import Categorical
19
+ from torch.utils.tensorboard import SummaryWriter
20
+ from tqdm import tqdm
21
+ from ultrahorizon_gym_wrapper import make_ultrahorizon_env, Difficulty
22
+ import json
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 = True
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 = "Ultrahorizon-v0"
46
+ """the id of the environment"""
47
+ difficulty: str = "EASY"
48
+ """difficulty level: EASY, MEDIUM, or HARD"""
49
+ total_timesteps: int = 10000000
50
+ """total timesteps of the experiments"""
51
+ learning_rate: float = 2.5e-4
52
+ """the learning rate of the optimizer"""
53
+ num_envs: int = 4
54
+ """the number of parallel game environments"""
55
+ num_steps: int = 512
56
+ """the number of steps to run in each environment per policy rollout"""
57
+ anneal_lr: bool = True
58
+ """Toggle learning rate annealing for policy and value networks"""
59
+ gamma: float = 0.99
60
+ """the discount factor gamma"""
61
+ gae_lambda: float = 0.95
62
+ """the lambda for the general advantage estimation"""
63
+ num_minibatches: int = 4
64
+ """the number of mini-batches"""
65
+ update_epochs: int = 4
66
+ """the K epochs to update the policy"""
67
+ norm_adv: bool = True
68
+ """Toggles advantages normalization"""
69
+ clip_coef: float = 0.2
70
+ """the surrogate clipping coefficient"""
71
+ clip_vloss: bool = True
72
+ """Toggles whether or not to use a clipped loss for the value function, as per the paper."""
73
+ ent_coef: float = 0.01
74
+ """coefficient of the entropy"""
75
+ vf_coef: float = 0.5
76
+ """coefficient of the value function"""
77
+ max_grad_norm: float = 0.5
78
+ """the maximum norm for the gradient clipping"""
79
+ target_kl: float = None
80
+ """the target KL divergence threshold"""
81
+
82
+ # to be filled in runtime
83
+ batch_size: int = 0
84
+ """the batch size (computed in runtime)"""
85
+ minibatch_size: int = 0
86
+ """the mini-batch size (computed in runtime)"""
87
+ num_iterations: int = 0
88
+ """the number of iterations (computed in runtime)"""
89
+
90
+
91
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
92
+ torch.nn.init.orthogonal_(layer.weight, std)
93
+ torch.nn.init.constant_(layer.bias, bias_const)
94
+ return layer
95
+
96
+
97
+ class Agent(nn.Module):
98
+ """
99
+ Neural network agent for Ultrahorizon environment.
100
+ Uses MLP instead of CNN since observations are feature vectors, not images.
101
+ """
102
+ def __init__(self, envs):
103
+ super().__init__()
104
+ # Get observation space dimension
105
+ obs_dim = np.array(envs.single_observation_space.shape).prod()
106
+
107
+ # MLP network for processing feature vectors
108
+ self.network = nn.Sequential(
109
+ layer_init(nn.Linear(obs_dim, 256)),
110
+ nn.ReLU(),
111
+ layer_init(nn.Linear(256, 256)),
112
+ nn.ReLU(),
113
+ layer_init(nn.Linear(256, 128)),
114
+ nn.ReLU(),
115
+ )
116
+ self.actor = layer_init(nn.Linear(128, envs.single_action_space.n), std=0.01)
117
+ self.critic = layer_init(nn.Linear(128, 1), std=1)
118
+
119
+ def get_value(self, x):
120
+ return self.critic(self.network(x))
121
+
122
+ def get_action_and_value(self, x, action=None):
123
+ hidden = self.network(x)
124
+ logits = self.actor(hidden)
125
+ probs = Categorical(logits=logits)
126
+ if action is None:
127
+ action = probs.sample()
128
+ return action, probs.log_prob(action), probs.entropy(), self.critic(hidden)
129
+
130
+
131
+ def test_policy(agent, difficulty, device, num_episodes=10, seed=None):
132
+ """
133
+ Test the current policy and collect trajectories and rewards.
134
+
135
+ Args:
136
+ agent: The trained agent
137
+ difficulty: Difficulty level for the environment
138
+ device: torch device
139
+ num_episodes: Number of episodes to test
140
+ seed: Random seed for testing
141
+
142
+ Returns:
143
+ dict: Dictionary containing test results including trajectories and rewards
144
+ """
145
+ # Create a single test environment
146
+ test_env = make_ultrahorizon_env(difficulty=difficulty, free=True)()
147
+
148
+ test_results = {
149
+ 'episode_returns': [],
150
+ 'episode_lengths': [],
151
+ 'final_scores': [],
152
+ 'trajectories': [] # Store trajectories for each episode
153
+ }
154
+
155
+ agent.eval() # Set agent to evaluation mode
156
+
157
+ for episode in range(num_episodes):
158
+ obs, _ = test_env.reset(seed=seed + episode if seed is not None else None)
159
+ done = False
160
+ episode_return = 0
161
+ episode_length = 0
162
+ trajectory = {
163
+ 'observations': [],
164
+ 'actions': [],
165
+ 'rewards': [],
166
+ 'dones': []
167
+ }
168
+
169
+ while not done:
170
+ # Store observation
171
+ trajectory['observations'].append(obs.tolist())
172
+
173
+ # Get action from policy
174
+ with torch.no_grad():
175
+ obs_tensor = torch.Tensor(obs).unsqueeze(0).to(device)
176
+ action, _, _, _ = agent.get_action_and_value(obs_tensor)
177
+ action = action.cpu().numpy()[0]
178
+
179
+ # Take action in environment
180
+ next_obs, reward, terminated, truncated, info = test_env.step(action)
181
+ done = terminated or truncated
182
+
183
+ # Store trajectory data
184
+ trajectory['actions'].append(int(action))
185
+ trajectory['rewards'].append(float(reward))
186
+ trajectory['dones'].append(done)
187
+
188
+ episode_return += reward
189
+ episode_length += 1
190
+ obs = next_obs
191
+
192
+ # Store episode results
193
+ test_results['episode_returns'].append(float(episode_return))
194
+ test_results['episode_lengths'].append(episode_length)
195
+ test_results['final_scores'].append(float(info.get('final_score', 0.0)))
196
+ test_results['trajectories'].append(trajectory)
197
+
198
+ agent.train() # Set agent back to training mode
199
+ test_env.close()
200
+
201
+ # Calculate statistics
202
+ test_results['mean_return'] = np.mean(test_results['episode_returns'])
203
+ test_results['std_return'] = np.std(test_results['episode_returns'])
204
+ test_results['mean_length'] = np.mean(test_results['episode_lengths'])
205
+ test_results['mean_final_score'] = np.mean(test_results['final_scores'])
206
+ test_results['std_final_score'] = np.std(test_results['final_scores'])
207
+
208
+ return test_results
209
+
210
+
211
+ if __name__ == "__main__":
212
+ args = tyro.cli(Args)
213
+ args.batch_size = int(args.num_envs * args.num_steps)
214
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
215
+ args.num_iterations = args.total_timesteps // args.batch_size
216
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}_{args.difficulty.upper()}__{int(time.time())}"
217
+
218
+ if args.track:
219
+ import wandb
220
+
221
+ wandb.init(
222
+ project=args.wandb_project_name,
223
+ entity=args.wandb_entity,
224
+ sync_tensorboard=True,
225
+ config=vars(args),
226
+ name=run_name,
227
+ monitor_gym=True,
228
+ save_code=True,
229
+ )
230
+ writer = SummaryWriter(f"runs/{run_name}")
231
+ writer.add_text(
232
+ "hyperparameters",
233
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
234
+ )
235
+
236
+ # TRY NOT TO MODIFY: seeding
237
+ random.seed(args.seed)
238
+ np.random.seed(args.seed)
239
+ torch.manual_seed(args.seed)
240
+ torch.backends.cudnn.deterministic = args.torch_deterministic
241
+
242
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
243
+
244
+ # env setup - convert difficulty string to enum
245
+ difficulty_map = {
246
+ "EASY": Difficulty.EASY,
247
+ "MEDIUM": Difficulty.MEDIUM,
248
+ "HARD": Difficulty.HARD
249
+ }
250
+
251
+ difficulty = difficulty_map.get(args.difficulty.upper(), Difficulty.EASY)
252
+
253
+ envs = gym.vector.SyncVectorEnv(
254
+ [make_ultrahorizon_env(difficulty=difficulty, free=True) for i in range(args.num_envs)],
255
+ )
256
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
257
+
258
+ agent = Agent(envs).to(device)
259
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
260
+
261
+ # ALGO Logic: Storage setup
262
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
263
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
264
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
265
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
266
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
267
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
268
+
269
+ # TRY NOT TO MODIFY: start the game
270
+ global_step = 0
271
+ start_time = time.time()
272
+ next_obs, _ = envs.reset(seed=args.seed)
273
+ next_obs = torch.Tensor(next_obs).to(device)
274
+ next_done = torch.zeros(args.num_envs).to(device)
275
+
276
+ # Setup for testing at 10% intervals
277
+ test_interval = args.num_iterations // 10
278
+ test_results_history = [] # Store all test results
279
+ test_save_dir = f"runs/{run_name}/test_results"
280
+ os.makedirs(test_save_dir, exist_ok=True)
281
+
282
+ for iteration in tqdm(range(1, args.num_iterations + 1)):
283
+ # Annealing the rate if instructed to do so.
284
+ if args.anneal_lr:
285
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
286
+ lrnow = frac * args.learning_rate
287
+ optimizer.param_groups[0]["lr"] = lrnow
288
+
289
+ for step in range(0, args.num_steps):
290
+ global_step += args.num_envs
291
+ obs[step] = next_obs
292
+ dones[step] = next_done
293
+
294
+ # ALGO LOGIC: action logic
295
+ with torch.no_grad():
296
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
297
+ values[step] = value.flatten()
298
+ actions[step] = action
299
+ logprobs[step] = logprob
300
+
301
+ # TRY NOT TO MODIFY: execute the game and log data.
302
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
303
+ next_done = np.logical_or(terminations, truncations)
304
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
305
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
306
+
307
+ # Handle terminal observations correctly
308
+ # When an episode ends, next_obs is the initial state of the new episode
309
+ # We need to use the final observation from the terminated episode for bootstrapping
310
+ if "final_observation" in infos:
311
+ for idx, final_obs in enumerate(infos["final_observation"]):
312
+ if final_obs is not None:
313
+ # Replace the reset observation with the actual final observation
314
+ next_obs[idx] = torch.Tensor(final_obs).to(device)
315
+
316
+ # import pdb;pdb.set_trace()
317
+ if "final_info" in infos:
318
+ for info in infos["final_info"]:
319
+ if info and "episode" in info:
320
+ episode_return = info['episode']['r']
321
+ episode_length = info['episode']['l']
322
+ final_score = info.get('final_score', 0.0) # Get cumulative score from environment
323
+ # import pdb;pdb.set_trace()
324
+ # print(f"global_step={global_step}, episodic_return={episode_return}, episodic_length={episode_length},final_score={final_score}")
325
+ writer.add_scalar("charts/episodic_return", episode_return, global_step)
326
+ writer.add_scalar("charts/episodic_length", episode_length, global_step)
327
+ writer.add_scalar("charts/final_score", final_score, global_step)
328
+
329
+ # import pdb;pdb.set_trace()
330
+ # bootstrap value if not done
331
+ with torch.no_grad():
332
+ next_value = agent.get_value(next_obs).reshape(1, -1)
333
+ advantages = torch.zeros_like(rewards).to(device)
334
+ lastgaelam = 0
335
+ for t in reversed(range(args.num_steps)):
336
+ if t == args.num_steps - 1:
337
+ nextnonterminal = 1.0 - next_done
338
+ nextvalues = next_value
339
+ else:
340
+ nextnonterminal = 1.0 - dones[t + 1]
341
+ nextvalues = values[t + 1]
342
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
343
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
344
+ returns = advantages + values
345
+
346
+ # flatten the batch
347
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
348
+ b_logprobs = logprobs.reshape(-1)
349
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
350
+ b_advantages = advantages.reshape(-1)
351
+ b_returns = returns.reshape(-1)
352
+ b_values = values.reshape(-1)
353
+
354
+ # Optimizing the policy and value network
355
+ b_inds = np.arange(args.batch_size)
356
+ clipfracs = []
357
+ for epoch in range(args.update_epochs):
358
+ np.random.shuffle(b_inds)
359
+ for start in range(0, args.batch_size, args.minibatch_size):
360
+ end = start + args.minibatch_size
361
+ mb_inds = b_inds[start:end]
362
+
363
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
364
+ logratio = newlogprob - b_logprobs[mb_inds]
365
+ ratio = logratio.exp()
366
+
367
+ with torch.no_grad():
368
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
369
+ old_approx_kl = (-logratio).mean()
370
+ approx_kl = ((ratio - 1) - logratio).mean()
371
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
372
+
373
+ mb_advantages = b_advantages[mb_inds]
374
+ if args.norm_adv:
375
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
376
+
377
+ # Policy loss
378
+ pg_loss1 = -mb_advantages * ratio
379
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
380
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
381
+
382
+ # Value loss
383
+ newvalue = newvalue.view(-1)
384
+ if args.clip_vloss:
385
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
386
+ v_clipped = b_values[mb_inds] + torch.clamp(
387
+ newvalue - b_values[mb_inds],
388
+ -args.clip_coef,
389
+ args.clip_coef,
390
+ )
391
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
392
+ v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped)
393
+ v_loss = 0.5 * v_loss_max.mean()
394
+ else:
395
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
396
+
397
+ entropy_loss = entropy.mean()
398
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
399
+
400
+ optimizer.zero_grad()
401
+ loss.backward()
402
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
403
+ optimizer.step()
404
+
405
+ if args.target_kl is not None and approx_kl > args.target_kl:
406
+ break
407
+
408
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
409
+ var_y = np.var(y_true)
410
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
411
+
412
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
413
+ writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step)
414
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
415
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
416
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
417
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
418
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
419
+ writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step)
420
+ writer.add_scalar("losses/explained_variance", explained_var, global_step)
421
+
422
+ # Additional useful metrics
423
+ writer.add_scalar("charts/avg_reward", rewards.mean().item(), global_step)
424
+ writer.add_scalar("charts/avg_value", values.mean().item(), global_step)
425
+ writer.add_scalar("charts/max_reward", rewards.max().item(), global_step)
426
+ writer.add_scalar("charts/min_reward", rewards.min().item(), global_step)
427
+
428
+ # Console output with key metrics
429
+ sps = int(global_step / (time.time() - start_time))
430
+ print(f"Iter {iteration}/{args.num_iterations} | SPS: {sps} | "
431
+ f"Avg Reward: {rewards.mean().item():.3f} | "
432
+ f"Value Loss: {v_loss.item():.4f} | "
433
+ f"Policy Loss: {pg_loss.item():.4f} | "
434
+ f"Entropy: {entropy_loss.item():.4f}")
435
+ print(f"global_step={global_step}, episodic_return={episode_return}, episodic_length={episode_length},final_score={final_score}")
436
+ writer.add_scalar("charts/SPS", sps, global_step)
437
+
438
+ # Test policy at 10% intervals
439
+ if iteration % test_interval == 0 or iteration == args.num_iterations:
440
+ print(f"\n{'='*60}")
441
+ print(f"Testing policy at iteration {iteration}/{args.num_iterations} ({100*iteration//args.num_iterations}%)")
442
+ print(f"{'='*60}")
443
+
444
+ test_results = test_policy(
445
+ agent=agent,
446
+ difficulty=difficulty,
447
+ device=device,
448
+ num_episodes=10,
449
+ seed=args.seed
450
+ )
451
+
452
+ # Log test results to tensorboard
453
+ writer.add_scalar("test/mean_return", test_results['mean_return'], global_step)
454
+ writer.add_scalar("test/std_return", test_results['std_return'], global_step)
455
+ writer.add_scalar("test/mean_length", test_results['mean_length'], global_step)
456
+ writer.add_scalar("test/mean_final_score", test_results['mean_final_score'], global_step)
457
+ writer.add_scalar("test/std_final_score", test_results['std_final_score'], global_step)
458
+
459
+ # Print test results
460
+ print(f"Test Results (10 episodes):")
461
+ print(f" Mean Return: {test_results['mean_return']:.2f} ± {test_results['std_return']:.2f}")
462
+ print(f" Mean Length: {test_results['mean_length']:.2f}")
463
+ print(f" Mean Final Score: {test_results['mean_final_score']:.2f} ± {test_results['std_final_score']:.2f}")
464
+ print(f"{'='*60}\n")
465
+
466
+ # Save test results to file
467
+ test_results_with_metadata = {
468
+ 'iteration': iteration,
469
+ 'global_step': global_step,
470
+ 'training_progress': iteration / args.num_iterations,
471
+ 'test_results': test_results
472
+ }
473
+ test_results_history.append(test_results_with_metadata)
474
+
475
+ # Save individual test result
476
+ test_file = f"{test_save_dir}/test_iter_{iteration}.json"
477
+ with open(test_file, 'w') as f:
478
+ json.dump(test_results_with_metadata, f, indent=2)
479
+ print(f"Saved test results to {test_file}")
480
+
481
+ envs.close()
482
+ writer.close()
483
+ torch.save(agent.state_dict(), f"runs/{run_name}/agent_{global_step}.pt")
484
+ print(f"Saved model at global_step={global_step}")
485
+
486
+ # Save all test results history
487
+ test_history_file = f"{test_save_dir}/test_history.json"
488
+ with open(test_history_file, 'w') as f:
489
+ json.dump(test_results_history, f, indent=2)
490
+ print(f"Saved complete test history to {test_history_file}")
cleanrl/cleanrl/pqn.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/pqn/#pqnpy
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.nn.functional as F
12
+ import torch.optim as optim
13
+ import tyro
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 for each environment per update"""
47
+ num_minibatches: int = 4
48
+ """the number of mini-batches"""
49
+ update_epochs: int = 4
50
+ """the K epochs to update the policy"""
51
+ anneal_lr: bool = True
52
+ """Toggle learning rate annealing"""
53
+ gamma: float = 0.99
54
+ """the discount factor gamma"""
55
+ start_e: float = 1
56
+ """the starting epsilon for exploration"""
57
+ end_e: float = 0.05
58
+ """the ending epsilon for exploration"""
59
+ exploration_fraction: float = 0.5
60
+ """the fraction of `total_timesteps` it takes from start_e to end_e"""
61
+ max_grad_norm: float = 10.0
62
+ """the maximum norm for the gradient clipping"""
63
+ q_lambda: float = 0.65
64
+ """the lambda for Q(lambda)"""
65
+
66
+
67
+ def make_env(env_id, seed, idx, capture_video, run_name):
68
+ def thunk():
69
+ if capture_video and idx == 0:
70
+ env = gym.make(env_id, render_mode="rgb_array")
71
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
72
+ else:
73
+ env = gym.make(env_id)
74
+ env = gym.wrappers.RecordEpisodeStatistics(env)
75
+ env.action_space.seed(seed)
76
+
77
+ return env
78
+
79
+ return thunk
80
+
81
+
82
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
83
+ torch.nn.init.orthogonal_(layer.weight, std)
84
+ torch.nn.init.constant_(layer.bias, bias_const)
85
+ return layer
86
+
87
+
88
+ # ALGO LOGIC: initialize agent here:
89
+ class QNetwork(nn.Module):
90
+ def __init__(self, env):
91
+ super().__init__()
92
+
93
+ self.network = nn.Sequential(
94
+ layer_init(nn.Linear(np.array(env.single_observation_space.shape).prod(), 120)),
95
+ nn.LayerNorm(120),
96
+ nn.ReLU(),
97
+ layer_init(nn.Linear(120, 84)),
98
+ nn.LayerNorm(84),
99
+ nn.ReLU(),
100
+ layer_init(nn.Linear(84, env.single_action_space.n)),
101
+ )
102
+
103
+ def forward(self, x):
104
+ return self.network(x)
105
+
106
+
107
+ def linear_schedule(start_e: float, end_e: float, duration: int, t: int):
108
+ slope = (end_e - start_e) / duration
109
+ return max(slope * t + start_e, end_e)
110
+
111
+
112
+ if __name__ == "__main__":
113
+ args = tyro.cli(Args)
114
+ args.batch_size = int(args.num_envs * args.num_steps)
115
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
116
+ args.num_iterations = args.total_timesteps // args.batch_size
117
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
118
+ if args.track:
119
+ import wandb
120
+
121
+ wandb.init(
122
+ project=args.wandb_project_name,
123
+ entity=args.wandb_entity,
124
+ sync_tensorboard=True,
125
+ config=vars(args),
126
+ name=run_name,
127
+ monitor_gym=True,
128
+ save_code=True,
129
+ )
130
+ writer = SummaryWriter(f"runs/{run_name}")
131
+ writer.add_text(
132
+ "hyperparameters",
133
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
134
+ )
135
+
136
+ # TRY NOT TO MODIFY: seeding
137
+ random.seed(args.seed)
138
+ np.random.seed(args.seed)
139
+ torch.manual_seed(args.seed)
140
+ torch.backends.cudnn.deterministic = args.torch_deterministic
141
+
142
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
143
+
144
+ # env setup
145
+ envs = gym.vector.SyncVectorEnv(
146
+ [make_env(args.env_id, args.seed + i, i, args.capture_video, run_name) for i in range(args.num_envs)]
147
+ )
148
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
149
+
150
+ # agent setup
151
+ q_network = QNetwork(envs).to(device)
152
+ optimizer = optim.RAdam(q_network.parameters(), lr=args.learning_rate)
153
+
154
+ # storage setup
155
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
156
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).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
+ # TRY NOT TO MODIFY: start the game
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
+ for iteration in range(1, args.num_iterations + 1):
169
+ # Annealing the rate if instructed to do so.
170
+ if args.anneal_lr:
171
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
172
+ lrnow = frac * args.learning_rate
173
+ optimizer.param_groups[0]["lr"] = lrnow
174
+
175
+ for step in range(0, args.num_steps):
176
+ global_step += args.num_envs
177
+ obs[step] = next_obs
178
+ dones[step] = next_done
179
+
180
+ epsilon = linear_schedule(args.start_e, args.end_e, args.exploration_fraction * args.total_timesteps, global_step)
181
+ random_actions = torch.randint(0, envs.single_action_space.n, (args.num_envs,)).to(device)
182
+ with torch.no_grad():
183
+ q_values = q_network(next_obs)
184
+ max_actions = torch.argmax(q_values, dim=1)
185
+ values[step] = q_values[torch.arange(args.num_envs), max_actions].flatten()
186
+
187
+ explore = torch.rand((args.num_envs,)).to(device) < epsilon
188
+ action = torch.where(explore, random_actions, max_actions)
189
+ actions[step] = action
190
+
191
+ # TRY NOT TO MODIFY: execute the game and log data.
192
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
193
+ next_done = np.logical_or(terminations, truncations)
194
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
195
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
196
+
197
+ if "final_info" in infos:
198
+ for info in infos["final_info"]:
199
+ if info and "episode" in info:
200
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
201
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
202
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
203
+
204
+ # Compute Q(lambda) targets
205
+ with torch.no_grad():
206
+ returns = torch.zeros_like(rewards).to(device)
207
+ for t in reversed(range(args.num_steps)):
208
+ if t == args.num_steps - 1:
209
+ next_value, _ = torch.max(q_network(next_obs), dim=-1)
210
+ nextnonterminal = 1.0 - next_done
211
+ returns[t] = rewards[t] + args.gamma * next_value * nextnonterminal
212
+ else:
213
+ nextnonterminal = 1.0 - dones[t + 1]
214
+ next_value = values[t + 1]
215
+ returns[t] = (
216
+ rewards[t]
217
+ + args.gamma * (args.q_lambda * returns[t + 1] + (1 - args.q_lambda) * next_value) * nextnonterminal
218
+ )
219
+
220
+ # flatten the batch
221
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
222
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
223
+ b_returns = returns.reshape(-1)
224
+
225
+ # Optimizing the Q-network
226
+ b_inds = np.arange(args.batch_size)
227
+ for epoch in range(args.update_epochs):
228
+ np.random.shuffle(b_inds)
229
+ for start in range(0, args.batch_size, args.minibatch_size):
230
+ end = start + args.minibatch_size
231
+ mb_inds = b_inds[start:end]
232
+
233
+ old_val = q_network(b_obs[mb_inds]).gather(1, b_actions[mb_inds].unsqueeze(-1).long()).squeeze()
234
+ loss = F.mse_loss(b_returns[mb_inds], old_val)
235
+
236
+ # optimize the model
237
+ optimizer.zero_grad()
238
+ loss.backward()
239
+ nn.utils.clip_grad_norm_(q_network.parameters(), args.max_grad_norm)
240
+ optimizer.step()
241
+
242
+ writer.add_scalar("losses/td_loss", loss, global_step)
243
+ writer.add_scalar("losses/q_values", old_val.mean().item(), global_step)
244
+ print("SPS:", int(global_step / (time.time() - start_time)))
245
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
246
+
247
+ envs.close()
248
+ writer.close()
cleanrl/cleanrl/pqn_atari_envpool_lstm.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/pqn/#pqn_atari_envpool_lstmpy
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.nn.functional as F
14
+ import torch.optim as optim
15
+ import tyro
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
+ num_minibatches: int = 4
54
+ """the number of mini-batches"""
55
+ update_epochs: int = 4
56
+ """the K epochs to update the policy"""
57
+ max_grad_norm: float = 0.5
58
+ """the maximum norm for the gradient clipping"""
59
+ start_e: float = 1
60
+ """the starting epsilon for exploration"""
61
+ end_e: float = 0.01
62
+ """the ending epsilon for exploration"""
63
+ exploration_fraction: float = 0.10
64
+ """the fraction of `total_timesteps` it takes from start_e to end_e"""
65
+ q_lambda: float = 0.65
66
+ """the lambda for the Q-Learning algorithm"""
67
+
68
+ # to be filled in runtime
69
+ batch_size: int = 0
70
+ """the batch size (computed in runtime)"""
71
+ minibatch_size: int = 0
72
+ """the mini-batch size (computed in runtime)"""
73
+ num_iterations: int = 0
74
+ """the number of iterations (computed in runtime)"""
75
+
76
+
77
+ class RecordEpisodeStatistics(gym.Wrapper):
78
+ def __init__(self, env, deque_size=100):
79
+ super().__init__(env)
80
+ self.num_envs = getattr(env, "num_envs", 1)
81
+ self.episode_returns = None
82
+ self.episode_lengths = None
83
+
84
+ def reset(self, **kwargs):
85
+ observations = super().reset(**kwargs)
86
+ self.episode_returns = np.zeros(self.num_envs, dtype=np.float32)
87
+ self.episode_lengths = np.zeros(self.num_envs, dtype=np.int32)
88
+ self.lives = np.zeros(self.num_envs, dtype=np.int32)
89
+ self.returned_episode_returns = np.zeros(self.num_envs, dtype=np.float32)
90
+ self.returned_episode_lengths = np.zeros(self.num_envs, dtype=np.int32)
91
+ return observations
92
+
93
+ def step(self, action):
94
+ observations, rewards, dones, infos = super().step(action)
95
+ self.episode_returns += infos["reward"]
96
+ self.episode_lengths += 1
97
+ self.returned_episode_returns[:] = self.episode_returns
98
+ self.returned_episode_lengths[:] = self.episode_lengths
99
+ self.episode_returns *= 1 - infos["terminated"]
100
+ self.episode_lengths *= 1 - infos["terminated"]
101
+ infos["r"] = self.returned_episode_returns
102
+ infos["l"] = self.returned_episode_lengths
103
+ return (
104
+ observations,
105
+ rewards,
106
+ dones,
107
+ infos,
108
+ )
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 QNetwork(nn.Module):
118
+ def __init__(self, env):
119
+ super().__init__()
120
+ self.network = nn.Sequential(
121
+ layer_init(nn.Conv2d(1, 32, 8, stride=4)),
122
+ nn.LayerNorm([32, 20, 20]),
123
+ nn.ReLU(),
124
+ layer_init(nn.Conv2d(32, 64, 4, stride=2)),
125
+ nn.LayerNorm([64, 9, 9]),
126
+ nn.ReLU(),
127
+ layer_init(nn.Conv2d(64, 64, 3, stride=1)),
128
+ nn.LayerNorm([64, 7, 7]),
129
+ nn.ReLU(),
130
+ nn.Flatten(),
131
+ layer_init(nn.Linear(3136, 512)),
132
+ nn.LayerNorm(512),
133
+ nn.ReLU(),
134
+ )
135
+ self.lstm = nn.LSTM(512, 128)
136
+ for name, param in self.lstm.named_parameters():
137
+ if "bias" in name:
138
+ nn.init.constant_(param, 0)
139
+ elif "weight" in name:
140
+ nn.init.orthogonal_(param, 1.0)
141
+ self.q_func = layer_init(nn.Linear(128, env.single_action_space.n))
142
+
143
+ def get_states(self, x, lstm_state, done):
144
+ hidden = self.network(x / 255.0)
145
+
146
+ # LSTM logic
147
+ batch_size = lstm_state[0].shape[1]
148
+ hidden = hidden.reshape((-1, batch_size, self.lstm.input_size))
149
+ done = done.reshape((-1, batch_size))
150
+ new_hidden = []
151
+ for h, d in zip(hidden, done):
152
+ h, lstm_state = self.lstm(
153
+ h.unsqueeze(0),
154
+ (
155
+ (1.0 - d).view(1, -1, 1) * lstm_state[0],
156
+ (1.0 - d).view(1, -1, 1) * lstm_state[1],
157
+ ),
158
+ )
159
+ new_hidden += [h]
160
+ new_hidden = torch.flatten(torch.cat(new_hidden), 0, 1)
161
+ return new_hidden, lstm_state
162
+
163
+ def forward(self, x, lstm_state, done):
164
+ hidden, lstm_state = self.get_states(x, lstm_state, done)
165
+ return self.q_func(hidden), lstm_state
166
+
167
+
168
+ def linear_schedule(start_e: float, end_e: float, duration: int, t: int):
169
+ slope = (end_e - start_e) / duration
170
+ return max(slope * t + start_e, end_e)
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 = envpool.make(
207
+ args.env_id,
208
+ env_type="gym",
209
+ num_envs=args.num_envs,
210
+ episodic_life=True,
211
+ reward_clip=True,
212
+ seed=args.seed,
213
+ stack_num=1,
214
+ )
215
+ envs.num_envs = args.num_envs
216
+ envs.single_action_space = envs.action_space
217
+ envs.single_observation_space = envs.observation_space
218
+ envs = RecordEpisodeStatistics(envs)
219
+ assert isinstance(envs.action_space, gym.spaces.Discrete), "only discrete action space is supported"
220
+
221
+ q_network = QNetwork(envs).to(device)
222
+ optimizer = optim.RAdam(q_network.parameters(), lr=args.learning_rate)
223
+
224
+ # ALGO Logic: Storage setup
225
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
226
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
227
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
228
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
229
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
230
+ avg_returns = deque(maxlen=20)
231
+
232
+ # TRY NOT TO MODIFY: start the game
233
+ global_step = 0
234
+ start_time = time.time()
235
+ next_obs = torch.Tensor(envs.reset()).to(device)
236
+ next_done = torch.zeros(args.num_envs).to(device)
237
+
238
+ next_lstm_state = (
239
+ torch.zeros(q_network.lstm.num_layers, args.num_envs, q_network.lstm.hidden_size).to(device),
240
+ torch.zeros(q_network.lstm.num_layers, args.num_envs, q_network.lstm.hidden_size).to(device),
241
+ ) # hidden and cell states (see https://youtu.be/8HyCNIVRbSU)
242
+
243
+ for iteration in range(1, args.num_iterations + 1):
244
+ initial_lstm_state = (next_lstm_state[0].clone(), next_lstm_state[1].clone())
245
+
246
+ # Annealing the rate if instructed to do so.
247
+ if args.anneal_lr:
248
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
249
+ lrnow = frac * args.learning_rate
250
+ optimizer.param_groups[0]["lr"] = lrnow
251
+
252
+ for step in range(0, args.num_steps):
253
+ global_step += args.num_envs
254
+ obs[step] = next_obs
255
+ dones[step] = next_done
256
+
257
+ epsilon = linear_schedule(args.start_e, args.end_e, args.exploration_fraction * args.total_timesteps, global_step)
258
+
259
+ random_actions = torch.randint(0, envs.single_action_space.n, (args.num_envs,)).to(device)
260
+ with torch.no_grad():
261
+ q_values, next_lstm_state = q_network(next_obs, next_lstm_state, next_done)
262
+ max_actions = torch.argmax(q_values, dim=1)
263
+ values[step] = q_values[torch.arange(args.num_envs), max_actions].flatten()
264
+
265
+ explore = torch.rand((args.num_envs,)).to(device) < epsilon
266
+ action = torch.where(explore, random_actions, max_actions)
267
+ actions[step] = action
268
+
269
+ # TRY NOT TO MODIFY: execute the game and log data.
270
+ next_obs, reward, next_done, info = envs.step(action.cpu().numpy())
271
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
272
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
273
+
274
+ for idx, d in enumerate(next_done):
275
+ if d and info["lives"][idx] == 0:
276
+ print(f"global_step={global_step}, episodic_return={info['r'][idx]}")
277
+ avg_returns.append(info["r"][idx])
278
+ writer.add_scalar("charts/avg_episodic_return", np.average(avg_returns), global_step)
279
+ writer.add_scalar("charts/episodic_return", info["r"][idx], global_step)
280
+ writer.add_scalar("charts/episodic_length", info["l"][idx], global_step)
281
+
282
+ # Compute Q(lambda) targets
283
+ with torch.no_grad():
284
+ returns = torch.zeros_like(rewards).to(device)
285
+ for t in reversed(range(args.num_steps)):
286
+ if t == args.num_steps - 1:
287
+ next_value, _ = torch.max(q_network(next_obs, next_lstm_state, next_done)[0], dim=-1)
288
+ nextnonterminal = 1.0 - next_done
289
+ returns[t] = rewards[t] + args.gamma * next_value * nextnonterminal
290
+ else:
291
+ nextnonterminal = 1.0 - dones[t + 1]
292
+ next_value = values[t + 1]
293
+ returns[t] = (
294
+ rewards[t]
295
+ + args.gamma * (args.q_lambda * returns[t + 1] + (1 - args.q_lambda) * next_value) * nextnonterminal
296
+ )
297
+
298
+ # flatten the batch
299
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
300
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
301
+ b_returns = returns.reshape(-1)
302
+ b_dones = dones.reshape(-1)
303
+
304
+ assert args.num_envs % args.num_minibatches == 0
305
+ envsperbatch = args.num_envs // args.num_minibatches
306
+ envinds = np.arange(args.num_envs)
307
+ flatinds = np.arange(args.batch_size).reshape(args.num_steps, args.num_envs)
308
+
309
+ # Optimizing the Q-network
310
+ b_inds = np.arange(args.batch_size)
311
+ for epoch in range(args.update_epochs):
312
+ np.random.shuffle(envinds)
313
+ for start in range(0, args.num_envs, envsperbatch):
314
+ end = start + envsperbatch
315
+ mbenvinds = envinds[start:end]
316
+ mb_inds = flatinds[:, mbenvinds].ravel() # be really careful about the index
317
+
318
+ old_val, _ = q_network(
319
+ b_obs[mb_inds],
320
+ (initial_lstm_state[0][:, mbenvinds], initial_lstm_state[1][:, mbenvinds]),
321
+ b_dones[mb_inds],
322
+ )
323
+ old_val = old_val.gather(1, b_actions[mb_inds].unsqueeze(-1).long()).squeeze()
324
+
325
+ loss = F.mse_loss(b_returns[mb_inds], old_val)
326
+
327
+ # optimize the model
328
+ optimizer.zero_grad()
329
+ loss.backward()
330
+ nn.utils.clip_grad_norm_(q_network.parameters(), args.max_grad_norm)
331
+ optimizer.step()
332
+
333
+ writer.add_scalar("losses/td_loss", loss, global_step)
334
+ writer.add_scalar("losses/q_values", old_val.mean().item(), global_step)
335
+ print("SPS:", int(global_step / (time.time() - start_time)))
336
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
337
+
338
+ envs.close()
339
+ writer.close()
cleanrl/cleanrl/qdagger_dqn_atari_impalacnn.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/qdagger/#qdagger_dqn_atari_jax_impalacnnpy
2
+ import os
3
+ import random
4
+ import time
5
+ from collections import deque
6
+ from dataclasses import dataclass
7
+
8
+ import gymnasium as gym
9
+ import numpy as np
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ import torch.optim as optim
14
+ import tyro
15
+ from huggingface_hub import hf_hub_download
16
+ from rich.progress import track
17
+ from torch.utils.tensorboard import SummaryWriter
18
+
19
+ from cleanrl.dqn_atari import QNetwork as TeacherModel
20
+ from cleanrl_utils.atari_wrappers import (
21
+ ClipRewardEnv,
22
+ EpisodicLifeEnv,
23
+ FireResetEnv,
24
+ MaxAndSkipEnv,
25
+ NoopResetEnv,
26
+ )
27
+ from cleanrl_utils.buffers import ReplayBuffer
28
+ from cleanrl_utils.evals.dqn_eval import evaluate
29
+
30
+
31
+ @dataclass
32
+ class Args:
33
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
34
+ """the name of this experiment"""
35
+ seed: int = 1
36
+ """seed of the experiment"""
37
+ torch_deterministic: bool = True
38
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
39
+ cuda: bool = True
40
+ """if toggled, cuda will be enabled by default"""
41
+ track: bool = False
42
+ """if toggled, this experiment will be tracked with Weights and Biases"""
43
+ wandb_project_name: str = "cleanRL"
44
+ """the wandb's project name"""
45
+ wandb_entity: str = None
46
+ """the entity (team) of wandb's project"""
47
+ capture_video: bool = False
48
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
49
+ save_model: bool = False
50
+ """whether to save model into the `runs/{run_name}` folder"""
51
+ upload_model: bool = False
52
+ """whether to upload the saved model to huggingface"""
53
+ hf_entity: str = ""
54
+ """the user or org name of the model repository from the Hugging Face Hub"""
55
+
56
+ # Algorithm specific arguments
57
+ env_id: str = "BreakoutNoFrameskip-v4"
58
+ """the id of the environment"""
59
+ total_timesteps: int = 10000000
60
+ """total timesteps of the experiments"""
61
+ learning_rate: float = 1e-4
62
+ """the learning rate of the optimizer"""
63
+ num_envs: int = 1
64
+ """the number of parallel game environments"""
65
+ buffer_size: int = 1000000
66
+ """the replay memory buffer size"""
67
+ gamma: float = 0.99
68
+ """the discount factor gamma"""
69
+ tau: float = 1.0
70
+ """the target network update rate"""
71
+ target_network_frequency: int = 1000
72
+ """the timesteps it takes to update the target network"""
73
+ batch_size: int = 32
74
+ """the batch size of sample from the reply memory"""
75
+ start_e: float = 1.0
76
+ """the starting epsilon for exploration"""
77
+ end_e: float = 0.01
78
+ """the ending epsilon for exploration"""
79
+ exploration_fraction: float = 0.10
80
+ """the fraction of `total-timesteps` it takes from start-e to go end-e"""
81
+ learning_starts: int = 80000
82
+ """timestep to start learning"""
83
+ train_frequency: int = 4
84
+ """the frequency of training"""
85
+
86
+ # QDagger specific arguments
87
+ teacher_policy_hf_repo: str = None
88
+ """the huggingface repo of the teacher policy"""
89
+ teacher_model_exp_name: str = "dqn_atari"
90
+ """the experiment name of the teacher model"""
91
+ teacher_eval_episodes: int = 10
92
+ """the number of episodes to run the teacher policy evaluate"""
93
+ teacher_steps: int = 500000
94
+ """the number of steps to run the teacher policy to generate the replay buffer"""
95
+ offline_steps: int = 500000
96
+ """the number of steps to run the student policy with the teacher's replay buffer"""
97
+ temperature: float = 1.0
98
+ """the temperature parameter for qdagger"""
99
+
100
+
101
+ def make_env(env_id, seed, idx, capture_video, run_name):
102
+ def thunk():
103
+ if capture_video and idx == 0:
104
+ env = gym.make(env_id, render_mode="rgb_array")
105
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
106
+ else:
107
+ env = gym.make(env_id)
108
+ env = gym.wrappers.RecordEpisodeStatistics(env)
109
+ env = NoopResetEnv(env, noop_max=30)
110
+ env = MaxAndSkipEnv(env, skip=4)
111
+ env = EpisodicLifeEnv(env)
112
+ if "FIRE" in env.unwrapped.get_action_meanings():
113
+ env = FireResetEnv(env)
114
+ env = ClipRewardEnv(env)
115
+ env = gym.wrappers.ResizeObservation(env, (84, 84))
116
+ env = gym.wrappers.GrayScaleObservation(env)
117
+ env = gym.wrappers.FrameStack(env, 4)
118
+ env.action_space.seed(seed)
119
+
120
+ return env
121
+
122
+ return thunk
123
+
124
+
125
+ # taken from https://github.com/AIcrowd/neurips2020-procgen-starter-kit/blob/142d09586d2272a17f44481a115c4bd817cf6a94/models/impala_cnn_torch.py
126
+ class ResidualBlock(nn.Module):
127
+ def __init__(self, channels):
128
+ super().__init__()
129
+ self.conv0 = nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=3, padding=1)
130
+ self.conv1 = nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=3, padding=1)
131
+
132
+ def forward(self, x):
133
+ inputs = x
134
+ x = nn.functional.relu(x)
135
+ x = self.conv0(x)
136
+ x = nn.functional.relu(x)
137
+ x = self.conv1(x)
138
+ return x + inputs
139
+
140
+
141
+ class ConvSequence(nn.Module):
142
+ def __init__(self, input_shape, out_channels):
143
+ super().__init__()
144
+ self._input_shape = input_shape
145
+ self._out_channels = out_channels
146
+ self.conv = nn.Conv2d(in_channels=self._input_shape[0], out_channels=self._out_channels, kernel_size=3, padding=1)
147
+ self.res_block0 = ResidualBlock(self._out_channels)
148
+ self.res_block1 = ResidualBlock(self._out_channels)
149
+
150
+ def forward(self, x):
151
+ x = self.conv(x)
152
+ x = nn.functional.max_pool2d(x, kernel_size=3, stride=2, padding=1)
153
+ x = self.res_block0(x)
154
+ x = self.res_block1(x)
155
+ assert x.shape[1:] == self.get_output_shape()
156
+ return x
157
+
158
+ def get_output_shape(self):
159
+ _c, h, w = self._input_shape
160
+ return (self._out_channels, (h + 1) // 2, (w + 1) // 2)
161
+
162
+
163
+ # ALGO LOGIC: initialize agent here:
164
+ class QNetwork(nn.Module):
165
+ def __init__(self, env):
166
+ super().__init__()
167
+ c, h, w = envs.single_observation_space.shape
168
+ shape = (c, h, w)
169
+ conv_seqs = []
170
+ for out_channels in [16, 32, 32]:
171
+ conv_seq = ConvSequence(shape, out_channels)
172
+ shape = conv_seq.get_output_shape()
173
+ conv_seqs.append(conv_seq)
174
+ conv_seqs += [
175
+ nn.Flatten(),
176
+ nn.ReLU(),
177
+ nn.Linear(in_features=shape[0] * shape[1] * shape[2], out_features=256),
178
+ nn.ReLU(),
179
+ nn.Linear(in_features=256, out_features=env.single_action_space.n),
180
+ ]
181
+ self.network = nn.Sequential(*conv_seqs)
182
+
183
+ def forward(self, x):
184
+ return self.network(x / 255.0)
185
+
186
+
187
+ def linear_schedule(start_e: float, end_e: float, duration: int, t: int):
188
+ slope = (end_e - start_e) / duration
189
+ return max(slope * t + start_e, end_e)
190
+
191
+
192
+ def kl_divergence_with_logits(target_logits, prediction_logits):
193
+ """Implementation of on-policy distillation loss."""
194
+ out = -F.softmax(target_logits, dim=-1) * (F.log_softmax(prediction_logits, dim=-1) - F.log_softmax(target_logits, dim=-1))
195
+ return torch.sum(out)
196
+
197
+
198
+ if __name__ == "__main__":
199
+ args = tyro.cli(Args)
200
+ assert args.num_envs == 1, "vectorized envs are not supported at the moment"
201
+ if args.teacher_policy_hf_repo is None:
202
+ args.teacher_policy_hf_repo = f"cleanrl/{args.env_id}-{args.teacher_model_exp_name}-seed1"
203
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
204
+ if args.track:
205
+ import wandb
206
+
207
+ wandb.init(
208
+ project=args.wandb_project_name,
209
+ entity=args.wandb_entity,
210
+ sync_tensorboard=True,
211
+ config=vars(args),
212
+ name=run_name,
213
+ monitor_gym=True,
214
+ save_code=True,
215
+ )
216
+ writer = SummaryWriter(f"runs/{run_name}")
217
+ writer.add_text(
218
+ "hyperparameters",
219
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
220
+ )
221
+
222
+ # TRY NOT TO MODIFY: seeding
223
+ random.seed(args.seed)
224
+ np.random.seed(args.seed)
225
+ torch.manual_seed(args.seed)
226
+ torch.backends.cudnn.deterministic = args.torch_deterministic
227
+
228
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
229
+
230
+ # env setup
231
+ envs = gym.vector.SyncVectorEnv(
232
+ [make_env(args.env_id, args.seed + i, i, args.capture_video, run_name) for i in range(args.num_envs)]
233
+ )
234
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
235
+
236
+ q_network = QNetwork(envs).to(device)
237
+ optimizer = optim.Adam(q_network.parameters(), lr=args.learning_rate)
238
+ target_network = QNetwork(envs).to(device)
239
+ target_network.load_state_dict(q_network.state_dict())
240
+
241
+ # QDAGGER LOGIC:
242
+ teacher_model_path = hf_hub_download(
243
+ repo_id=args.teacher_policy_hf_repo, filename=f"{args.teacher_model_exp_name}.cleanrl_model"
244
+ )
245
+ teacher_model = TeacherModel(envs).to(device)
246
+ teacher_model.load_state_dict(torch.load(teacher_model_path, map_location=device))
247
+ teacher_model.eval()
248
+
249
+ # evaluate the teacher model
250
+ teacher_episodic_returns = evaluate(
251
+ teacher_model_path,
252
+ make_env,
253
+ args.env_id,
254
+ eval_episodes=args.teacher_eval_episodes,
255
+ run_name=f"{run_name}-teacher-eval",
256
+ Model=TeacherModel,
257
+ epsilon=args.end_e,
258
+ capture_video=False,
259
+ )
260
+ writer.add_scalar("charts/teacher/avg_episodic_return", np.mean(teacher_episodic_returns), 0)
261
+
262
+ # collect teacher data for args.teacher_steps
263
+ # we assume we don't have access to the teacher's replay buffer
264
+ # see Fig. A.19 in Agarwal et al. 2022 for more detail
265
+ teacher_rb = ReplayBuffer(
266
+ args.buffer_size,
267
+ envs.single_observation_space,
268
+ envs.single_action_space,
269
+ device,
270
+ optimize_memory_usage=True,
271
+ handle_timeout_termination=False,
272
+ )
273
+
274
+ obs, _ = envs.reset(seed=args.seed)
275
+ for global_step in track(range(args.teacher_steps), description="filling teacher's replay buffer"):
276
+ epsilon = linear_schedule(args.start_e, args.end_e, args.teacher_steps, global_step)
277
+ if random.random() < epsilon:
278
+ actions = np.array([envs.single_action_space.sample() for _ in range(envs.num_envs)])
279
+ else:
280
+ q_values = teacher_model(torch.Tensor(obs).to(device))
281
+ actions = torch.argmax(q_values, dim=1).cpu().numpy()
282
+ next_obs, rewards, terminations, truncations, infos = envs.step(actions)
283
+ real_next_obs = next_obs.copy()
284
+ for idx, trunc in enumerate(truncations):
285
+ if trunc:
286
+ real_next_obs[idx] = infos["final_observation"][idx]
287
+ teacher_rb.add(obs, real_next_obs, actions, rewards, terminations, infos)
288
+ obs = next_obs
289
+
290
+ # offline training phase: train the student model using the qdagger loss
291
+ for global_step in track(range(args.offline_steps), description="offline student training"):
292
+ data = teacher_rb.sample(args.batch_size)
293
+ # perform a gradient-descent step
294
+ with torch.no_grad():
295
+ target_max, _ = target_network(data.next_observations).max(dim=1)
296
+ td_target = data.rewards.flatten() + args.gamma * target_max * (1 - data.dones.flatten())
297
+ teacher_q_values = teacher_model(data.observations) / args.temperature
298
+
299
+ student_q_values = q_network(data.observations)
300
+ old_val = student_q_values.gather(1, data.actions).squeeze()
301
+ q_loss = F.mse_loss(td_target, old_val)
302
+
303
+ student_q_values = student_q_values / args.temperature
304
+ distill_loss = torch.mean(kl_divergence_with_logits(teacher_q_values, student_q_values))
305
+
306
+ loss = q_loss + 1.0 * distill_loss
307
+
308
+ optimizer.zero_grad()
309
+ loss.backward()
310
+ optimizer.step()
311
+
312
+ # update the target network
313
+ if global_step % args.target_network_frequency == 0:
314
+ for target_network_param, q_network_param in zip(target_network.parameters(), q_network.parameters()):
315
+ target_network_param.data.copy_(args.tau * q_network_param.data + (1.0 - args.tau) * target_network_param.data)
316
+
317
+ if global_step % 100 == 0:
318
+ writer.add_scalar("charts/offline/loss", loss, global_step)
319
+ writer.add_scalar("charts/offline/q_loss", q_loss, global_step)
320
+ writer.add_scalar("charts/offline/distill_loss", distill_loss, global_step)
321
+
322
+ if global_step % 100000 == 0:
323
+ # evaluate the student model
324
+ model_path = f"runs/{run_name}/{args.exp_name}-offline-{global_step}.cleanrl_model"
325
+ torch.save(q_network.state_dict(), model_path)
326
+ print(f"model saved to {model_path}")
327
+
328
+ episodic_returns = evaluate(
329
+ model_path,
330
+ make_env,
331
+ args.env_id,
332
+ eval_episodes=10,
333
+ run_name=f"{run_name}-eval",
334
+ Model=QNetwork,
335
+ device=device,
336
+ epsilon=args.end_e,
337
+ )
338
+ print(episodic_returns)
339
+ writer.add_scalar("charts/offline/avg_episodic_return", np.mean(episodic_returns), global_step)
340
+
341
+ rb = ReplayBuffer(
342
+ args.buffer_size,
343
+ envs.single_observation_space,
344
+ envs.single_action_space,
345
+ device,
346
+ optimize_memory_usage=True,
347
+ handle_timeout_termination=False,
348
+ )
349
+ start_time = time.time()
350
+
351
+ # TRY NOT TO MODIFY: start the game
352
+ envs = gym.vector.SyncVectorEnv(
353
+ [make_env(args.env_id, args.seed + i, i, args.capture_video, run_name) for i in range(args.num_envs)]
354
+ )
355
+ obs, _ = envs.reset(seed=args.seed)
356
+ episodic_returns = deque(maxlen=10)
357
+ # online training phase
358
+ for global_step in track(range(args.total_timesteps), description="online student training"):
359
+ global_step += args.offline_steps
360
+ # ALGO LOGIC: put action logic here
361
+ epsilon = linear_schedule(args.start_e, args.end_e, args.exploration_fraction * args.total_timesteps, global_step)
362
+ if random.random() < epsilon:
363
+ actions = np.array([envs.single_action_space.sample() for _ in range(envs.num_envs)])
364
+ else:
365
+ q_values = q_network(torch.Tensor(obs).to(device))
366
+ actions = torch.argmax(q_values, dim=1).cpu().numpy()
367
+
368
+ # TRY NOT TO MODIFY: execute the game and log data.
369
+ next_obs, rewards, terminations, truncations, infos = envs.step(actions)
370
+
371
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
372
+ if "final_info" in infos:
373
+ for info in infos["final_info"]:
374
+ # Skip the envs that are not done
375
+ if "episode" not in info:
376
+ continue
377
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
378
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
379
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
380
+ writer.add_scalar("charts/epsilon", epsilon, global_step)
381
+ episodic_returns.append(info["episode"]["r"])
382
+ break
383
+
384
+ # TRY NOT TO MODIFY: save data to reply buffer; handle `final_observation`
385
+ real_next_obs = next_obs.copy()
386
+ for idx, trunc in enumerate(truncations):
387
+ if trunc:
388
+ real_next_obs[idx] = infos["final_observation"][idx]
389
+ rb.add(obs, real_next_obs, actions, rewards, terminations, infos)
390
+
391
+ # TRY NOT TO MODIFY: CRUCIAL step easy to overlook
392
+ obs = next_obs
393
+
394
+ # ALGO LOGIC: training.
395
+ if global_step > args.learning_starts:
396
+ if global_step % args.train_frequency == 0:
397
+ data = rb.sample(args.batch_size)
398
+ # perform a gradient-descent step
399
+ if len(episodic_returns) < 10:
400
+ distill_coeff = 1.0
401
+ else:
402
+ distill_coeff = max(1 - np.mean(episodic_returns) / np.mean(teacher_episodic_returns), 0)
403
+ with torch.no_grad():
404
+ target_max, _ = target_network(data.next_observations).max(dim=1)
405
+ td_target = data.rewards.flatten() + args.gamma * target_max * (1 - data.dones.flatten())
406
+ teacher_q_values = teacher_model(data.observations) / args.temperature
407
+
408
+ student_q_values = q_network(data.observations)
409
+ old_val = student_q_values.gather(1, data.actions).squeeze()
410
+ q_loss = F.mse_loss(td_target, old_val)
411
+
412
+ student_q_values = student_q_values / args.temperature
413
+ distill_loss = torch.mean(kl_divergence_with_logits(teacher_q_values, student_q_values))
414
+
415
+ loss = q_loss + distill_coeff * distill_loss
416
+
417
+ if global_step % 100 == 0:
418
+ writer.add_scalar("losses/loss", loss, global_step)
419
+ writer.add_scalar("losses/td_loss", q_loss, global_step)
420
+ writer.add_scalar("losses/distill_loss", distill_loss, global_step)
421
+ writer.add_scalar("losses/q_values", old_val.mean().item(), global_step)
422
+ writer.add_scalar("charts/distill_coeff", distill_coeff, global_step)
423
+ print("SPS:", int(global_step / (time.time() - start_time)))
424
+ print(distill_coeff)
425
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
426
+
427
+ # optimize the model
428
+ optimizer.zero_grad()
429
+ loss.backward()
430
+ optimizer.step()
431
+
432
+ # update the target network
433
+ if global_step % args.target_network_frequency == 0:
434
+ for target_network_param, q_network_param in zip(target_network.parameters(), q_network.parameters()):
435
+ target_network_param.data.copy_(
436
+ args.tau * q_network_param.data + (1.0 - args.tau) * target_network_param.data
437
+ )
438
+
439
+ if args.save_model:
440
+ model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
441
+ torch.save(q_network.state_dict(), model_path)
442
+ print(f"model saved to {model_path}")
443
+ from cleanrl_utils.evals.dqn_eval import evaluate
444
+
445
+ episodic_returns = evaluate(
446
+ model_path,
447
+ make_env,
448
+ args.env_id,
449
+ eval_episodes=10,
450
+ run_name=f"{run_name}-eval",
451
+ Model=QNetwork,
452
+ device=device,
453
+ epsilon=args.end_e,
454
+ )
455
+ for idx, episodic_return in enumerate(episodic_returns):
456
+ writer.add_scalar("eval/episodic_return", episodic_return, idx)
457
+
458
+ if args.upload_model:
459
+ from cleanrl_utils.huggingface import push_to_hub
460
+
461
+ repo_name = f"{args.env_id}-{args.exp_name}-seed{args.seed}"
462
+ repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
463
+ push_to_hub(args, episodic_returns, repo_id, "Qdagger", f"runs/{run_name}", f"videos/{run_name}-eval")
464
+
465
+ envs.close()
466
+ writer.close()
cleanrl/cleanrl/ragen_wrappers.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gymnasium-compatible wrappers for RAGEN environments to enable traditional RL training.
3
+ These wrappers convert text-based observations to numerical representations suitable for MLP networks.
4
+ """
5
+ import gymnasium as gym
6
+ import numpy as np
7
+ from typing import Any, Dict, Tuple
8
+
9
+
10
+ class BanditWrapper(gym.Wrapper):
11
+ """
12
+ Wrapper for RAGEN Bandit that uses only observable text.
13
+ Converts text observations to a fixed-size one-hot hash vector.
14
+ Does not alter episode semantics and does not inspect env internals.
15
+ """
16
+ def __init__(self, env, feature_dim_per_name: int = 16):
17
+ super().__init__(env)
18
+ # Two name slots (first/second), each hashed to one-hot of size K
19
+ self.k = feature_dim_per_name
20
+ self.observation_space = gym.spaces.Box(low=0, high=1, shape=(2 * self.k,), dtype=np.float32)
21
+ self.action_space = gym.spaces.Discrete(2)
22
+
23
+ def _parse_names(self, text_obs: str):
24
+ """Extract the two arm names from the prompt text purely via regex/string ops."""
25
+ # Heuristic: look for the segment after "named " and split by " and "
26
+ try:
27
+ anchor = "named "
28
+ if anchor in text_obs:
29
+ segment = text_obs.split(anchor, 1)[1]
30
+ # Cut at newline if present
31
+ segment = segment.split("\n", 1)[0]
32
+ # Now split by " and " to get two names; also strip punctuation
33
+ parts = segment.split(" and ")
34
+ if len(parts) >= 2:
35
+ name_a = parts[0].strip().strip(' .!?,')
36
+ name_b = parts[1].strip().strip(' .!?,')
37
+ return name_a, name_b
38
+ except Exception:
39
+ pass
40
+ # Fallback: no names found
41
+ return "", ""
42
+
43
+ def _names_to_vector(self, name_a: str, name_b: str) -> np.ndarray:
44
+ vec = np.zeros(2 * self.k, dtype=np.float32)
45
+ idx_a = (hash(name_a) % self.k)
46
+ idx_b = (hash(name_b) % self.k)
47
+ vec[idx_a] = 1.0
48
+ vec[self.k + idx_b] = 1.0
49
+ return vec
50
+
51
+ def reset(self, **kwargs):
52
+ seed = kwargs.get('seed', None)
53
+ mode = kwargs.get('mode', None)
54
+ text_obs = self.env.reset(seed=seed, mode=mode)
55
+ name_a, name_b = self._parse_names(text_obs)
56
+ return self._names_to_vector(name_a, name_b), {}
57
+
58
+ def step(self, action):
59
+ ragen_action = int(action) + 1
60
+ text_obs, reward, done, info = self.env.step(ragen_action)
61
+ name_a, name_b = self._parse_names(text_obs)
62
+ terminated = bool(done)
63
+ truncated = False
64
+ return self._names_to_vector(name_a, name_b), reward, terminated, truncated, info
65
+
66
+
67
+ class FrozenLakeWrapper(gym.Wrapper):
68
+ """
69
+ Wrapper for RAGEN FrozenLake environment.
70
+ Converts grid-based text observations to numerical state representation.
71
+ """
72
+ def __init__(self, env):
73
+ super().__init__(env)
74
+ # Bootstrap an observation to determine grid size from text only
75
+ bootstrap_text = self.env.reset()
76
+ flat, _ = self._parse_observation_and_meta(bootstrap_text)
77
+ self.observation_space = gym.spaces.Box(low=0, high=1, shape=(flat.shape[0],), dtype=np.float32)
78
+ self.action_space = gym.spaces.Discrete(4)
79
+ # Serve the bootstrapped obs on first reset without calling env.reset again
80
+ self._bootstrap_obs = flat
81
+ self._bootstrap_ready = True
82
+
83
+ def _parse_observation_and_meta(self, text_obs: str) -> Tuple[np.ndarray, Tuple[int, int]]:
84
+ """Parse text observation into numerical state (one-hot grid + player pos)."""
85
+ lines = text_obs.strip().split('\n')
86
+ grid = []
87
+ player_pos = None
88
+ rows = len(lines)
89
+ cols = max(len(line) for line in lines) if rows > 0 else 0
90
+ # Parse grid
91
+ for i, line in enumerate(lines):
92
+ row = []
93
+ for j, char in enumerate(line):
94
+ if char == 'P': # Player
95
+ row.append(0)
96
+ player_pos = (i, j)
97
+ elif char == '_': # Frozen
98
+ row.append(1)
99
+ elif char == 'O': # Hole
100
+ row.append(2)
101
+ elif char == 'G': # Goal
102
+ row.append(3)
103
+ elif char == 'X': # Player in hole
104
+ row.append(2)
105
+ player_pos = (i, j)
106
+ elif char == '√': # Player on goal
107
+ row.append(3)
108
+ player_pos = (i, j)
109
+ else:
110
+ row.append(1) # Default to frozen
111
+ grid.append(row)
112
+ # Pad ragged rows if needed
113
+ grid = np.array([r + [1] * (cols - len(r)) for r in grid], dtype=np.int32)
114
+ grid_size = (rows, cols)
115
+ # One-hot encode grid over 4 cell types
116
+ # One-hot encode grid
117
+ one_hot_grid = np.zeros((rows, cols, 4), dtype=np.float32)
118
+ for i in range(rows):
119
+ for j in range(cols):
120
+ cell_type = grid[i, j]
121
+ one_hot_grid[i, j, cell_type] = 1.0
122
+ # Flatten grid
123
+ flat_grid = one_hot_grid.flatten()
124
+ # Add normalized player position
125
+ if player_pos is None:
126
+ player_pos = (0, 0)
127
+ player_pos_norm = np.array([
128
+ 0.0 if rows <= 1 else player_pos[0] / max(1, rows - 1),
129
+ 0.0 if cols <= 1 else player_pos[1] / max(1, cols - 1),
130
+ ], dtype=np.float32)
131
+ flat = np.concatenate([flat_grid, player_pos_norm])
132
+ return flat, grid_size
133
+
134
+ def reset(self, **kwargs):
135
+ # Filter out 'options' parameter that gymnasium passes but RAGEN doesn't support
136
+ if self._bootstrap_ready:
137
+ # First call returns the bootstrapped observation to avoid double reset
138
+ self._bootstrap_ready = False
139
+ return self._bootstrap_obs.copy(), {}
140
+ seed = kwargs.get('seed', None)
141
+ mode = kwargs.get('mode', None)
142
+ text_obs = self.env.reset(seed=seed, mode=mode)
143
+ state, _ = self._parse_observation_and_meta(text_obs)
144
+ return state, {}
145
+
146
+ def step(self, action):
147
+ # Map action from 0,1,2,3 to 1,2,3,4 (RAGEN uses 1-indexed actions)
148
+ ragen_action = action + 1
149
+ text_obs, reward, done, info = self.env.step(ragen_action)
150
+ state, _ = self._parse_observation_and_meta(text_obs)
151
+
152
+ terminated = done
153
+ truncated = False
154
+
155
+ return state, reward, terminated, truncated, info
156
+
157
+
158
+ class SokobanWrapper(gym.Wrapper):
159
+ """
160
+ Wrapper for RAGEN Sokoban environment.
161
+ Converts grid-based text observations to numerical state representation.
162
+ Note: Does not inherit from gym.Wrapper due to old gym vs gymnasium compatibility.
163
+ """
164
+ def __init__(self, env):
165
+ super().__init__(env)
166
+ # Bootstrap an observation to determine room size from text only
167
+ bootstrap_text = self.env.reset()
168
+ flat, rows, cols = self._parse_observation_and_meta(bootstrap_text)
169
+ self.observation_space = gym.spaces.Box(low=0, high=1, shape=(flat.shape[0],), dtype=np.float32)
170
+ self.action_space = gym.spaces.Discrete(4)
171
+ self.metadata = getattr(env, 'metadata', {})
172
+ self._bootstrap_obs = flat
173
+ self._bootstrap_ready = True
174
+
175
+ def _parse_observation_and_meta(self, text_obs: str) -> Tuple[np.ndarray, int, int]:
176
+ """Parse text observation into numerical state and return dims."""
177
+ lines = text_obs.strip().split('\n')
178
+ grid = []
179
+ rows = len(lines)
180
+ cols = max(len(line) for line in lines) if rows > 0 else 0
181
+ # Mapping from characters to cell types
182
+ char_to_type = {
183
+ '#': 0, # wall
184
+ '_': 1, # empty
185
+ 'O': 2, # target
186
+ '√': 3, # box on target
187
+ 'X': 4, # box
188
+ 'P': 5, # player
189
+ 'S': 6, # player on target
190
+ }
191
+
192
+ for line in lines:
193
+ row = []
194
+ for char in line:
195
+ row.append(char_to_type.get(char, 1)) # Default to empty
196
+ grid.append(row)
197
+ # Pad ragged rows
198
+ grid = np.array([r + [1] * (cols - len(r)) for r in grid], dtype=np.int32)
199
+ # One-hot encode grid
200
+ one_hot_grid = np.zeros((rows, cols, 7), dtype=np.float32)
201
+ for i in range(rows):
202
+ for j in range(cols):
203
+ cell_type = grid[i, j]
204
+ one_hot_grid[i, j, cell_type] = 1.0
205
+ return one_hot_grid.flatten(), rows, cols
206
+
207
+ def reset(self, **kwargs):
208
+ if self._bootstrap_ready:
209
+ self._bootstrap_ready = False
210
+ return self._bootstrap_obs.copy(), {}
211
+ seed = kwargs.get('seed', None)
212
+ mode = kwargs.get('mode', None)
213
+ text_obs = self.env.reset(seed=seed, mode=mode)
214
+ state, _, _ = self._parse_observation_and_meta(text_obs)
215
+ return state, {}
216
+
217
+ def step(self, action):
218
+ # Map action from 0,1,2,3 to 1,2,3,4 (RAGEN uses 1-indexed actions)
219
+ ragen_action = action + 1
220
+ text_obs, reward, done, info = self.env.step(ragen_action)
221
+ state, _, _ = self._parse_observation_and_meta(text_obs)
222
+
223
+ terminated = done
224
+ truncated = False
225
+
226
+ return state, reward, terminated, truncated, info
227
+
228
+ def close(self):
229
+ if hasattr(self.env, 'close'):
230
+ self.env.close()
231
+
232
+ def render(self):
233
+ if hasattr(self.env, 'render'):
234
+ return self.env.render()
235
+ return None
cleanrl/cleanrl/sac_atari.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/sac/#sac_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.nn.functional as F
12
+ import torch.optim as optim
13
+ import tyro
14
+ from torch.distributions.categorical import Categorical
15
+ from torch.utils.tensorboard import SummaryWriter
16
+
17
+ from cleanrl_utils.atari_wrappers import (
18
+ ClipRewardEnv,
19
+ EpisodicLifeEnv,
20
+ FireResetEnv,
21
+ MaxAndSkipEnv,
22
+ NoopResetEnv,
23
+ )
24
+ from cleanrl_utils.buffers import ReplayBuffer
25
+
26
+
27
+ @dataclass
28
+ class Args:
29
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
30
+ """the name of this experiment"""
31
+ seed: int = 1
32
+ """seed of the experiment"""
33
+ torch_deterministic: bool = True
34
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
35
+ cuda: bool = True
36
+ """if toggled, cuda will be enabled by default"""
37
+ track: bool = False
38
+ """if toggled, this experiment will be tracked with Weights and Biases"""
39
+ wandb_project_name: str = "cleanRL"
40
+ """the wandb's project name"""
41
+ wandb_entity: str = None
42
+ """the entity (team) of wandb's project"""
43
+ capture_video: bool = False
44
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
45
+
46
+ # Algorithm specific arguments
47
+ env_id: str = "BeamRiderNoFrameskip-v4"
48
+ """the id of the environment"""
49
+ total_timesteps: int = 5000000
50
+ """total timesteps of the experiments"""
51
+ buffer_size: int = int(1e6)
52
+ """the replay memory buffer size""" # smaller than in original paper but evaluation is done only for 100k steps anyway
53
+ gamma: float = 0.99
54
+ """the discount factor gamma"""
55
+ tau: float = 1.0
56
+ """target smoothing coefficient (default: 1)"""
57
+ batch_size: int = 64
58
+ """the batch size of sample from the reply memory"""
59
+ learning_starts: int = 2e4
60
+ """timestep to start learning"""
61
+ policy_lr: float = 3e-4
62
+ """the learning rate of the policy network optimizer"""
63
+ q_lr: float = 3e-4
64
+ """the learning rate of the Q network network optimizer"""
65
+ update_frequency: int = 4
66
+ """the frequency of training updates"""
67
+ target_network_frequency: int = 8000
68
+ """the frequency of updates for the target networks"""
69
+ alpha: float = 0.2
70
+ """Entropy regularization coefficient."""
71
+ autotune: bool = True
72
+ """automatic tuning of the entropy coefficient"""
73
+ target_entropy_scale: float = 0.89
74
+ """coefficient for scaling the autotune entropy target"""
75
+
76
+
77
+ def make_env(env_id, seed, idx, capture_video, run_name):
78
+ def thunk():
79
+ if capture_video and idx == 0:
80
+ env = gym.make(env_id, render_mode="rgb_array")
81
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
82
+ else:
83
+ env = gym.make(env_id)
84
+ env = gym.wrappers.RecordEpisodeStatistics(env)
85
+
86
+ env = NoopResetEnv(env, noop_max=30)
87
+ env = MaxAndSkipEnv(env, skip=4)
88
+ env = EpisodicLifeEnv(env)
89
+ if "FIRE" in env.unwrapped.get_action_meanings():
90
+ env = FireResetEnv(env)
91
+ env = ClipRewardEnv(env)
92
+ env = gym.wrappers.ResizeObservation(env, (84, 84))
93
+ env = gym.wrappers.GrayScaleObservation(env)
94
+ env = gym.wrappers.FrameStack(env, 4)
95
+
96
+ env.action_space.seed(seed)
97
+ return env
98
+
99
+ return thunk
100
+
101
+
102
+ def layer_init(layer, bias_const=0.0):
103
+ nn.init.kaiming_normal_(layer.weight)
104
+ torch.nn.init.constant_(layer.bias, bias_const)
105
+ return layer
106
+
107
+
108
+ # ALGO LOGIC: initialize agent here:
109
+ # NOTE: Sharing a CNN encoder between Actor and Critics is not recommended for SAC without stopping actor gradients
110
+ # See the SAC+AE paper https://arxiv.org/abs/1910.01741 for more info
111
+ # TL;DR The actor's gradients mess up the representation when using a joint encoder
112
+ class SoftQNetwork(nn.Module):
113
+ def __init__(self, envs):
114
+ super().__init__()
115
+ obs_shape = envs.single_observation_space.shape
116
+ self.conv = nn.Sequential(
117
+ layer_init(nn.Conv2d(obs_shape[0], 32, kernel_size=8, stride=4)),
118
+ nn.ReLU(),
119
+ layer_init(nn.Conv2d(32, 64, kernel_size=4, stride=2)),
120
+ nn.ReLU(),
121
+ layer_init(nn.Conv2d(64, 64, kernel_size=3, stride=1)),
122
+ nn.Flatten(),
123
+ )
124
+
125
+ with torch.inference_mode():
126
+ output_dim = self.conv(torch.zeros(1, *obs_shape)).shape[1]
127
+
128
+ self.fc1 = layer_init(nn.Linear(output_dim, 512))
129
+ self.fc_q = layer_init(nn.Linear(512, envs.single_action_space.n))
130
+
131
+ def forward(self, x):
132
+ x = F.relu(self.conv(x / 255.0))
133
+ x = F.relu(self.fc1(x))
134
+ q_vals = self.fc_q(x)
135
+ return q_vals
136
+
137
+
138
+ class Actor(nn.Module):
139
+ def __init__(self, envs):
140
+ super().__init__()
141
+ obs_shape = envs.single_observation_space.shape
142
+ self.conv = nn.Sequential(
143
+ layer_init(nn.Conv2d(obs_shape[0], 32, kernel_size=8, stride=4)),
144
+ nn.ReLU(),
145
+ layer_init(nn.Conv2d(32, 64, kernel_size=4, stride=2)),
146
+ nn.ReLU(),
147
+ layer_init(nn.Conv2d(64, 64, kernel_size=3, stride=1)),
148
+ nn.Flatten(),
149
+ )
150
+
151
+ with torch.inference_mode():
152
+ output_dim = self.conv(torch.zeros(1, *obs_shape)).shape[1]
153
+
154
+ self.fc1 = layer_init(nn.Linear(output_dim, 512))
155
+ self.fc_logits = layer_init(nn.Linear(512, envs.single_action_space.n))
156
+
157
+ def forward(self, x):
158
+ x = F.relu(self.conv(x))
159
+ x = F.relu(self.fc1(x))
160
+ logits = self.fc_logits(x)
161
+
162
+ return logits
163
+
164
+ def get_action(self, x):
165
+ logits = self(x / 255.0)
166
+ policy_dist = Categorical(logits=logits)
167
+ action = policy_dist.sample()
168
+ # Action probabilities for calculating the adapted soft-Q loss
169
+ action_probs = policy_dist.probs
170
+ log_prob = F.log_softmax(logits, dim=1)
171
+ return action, log_prob, action_probs
172
+
173
+
174
+ if __name__ == "__main__":
175
+ args = tyro.cli(Args)
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
+ torch.manual_seed(args.seed)
199
+ torch.backends.cudnn.deterministic = args.torch_deterministic
200
+
201
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
202
+
203
+ # env setup
204
+ envs = gym.vector.SyncVectorEnv([make_env(args.env_id, args.seed, 0, args.capture_video, run_name)])
205
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
206
+
207
+ actor = Actor(envs).to(device)
208
+ qf1 = SoftQNetwork(envs).to(device)
209
+ qf2 = SoftQNetwork(envs).to(device)
210
+ qf1_target = SoftQNetwork(envs).to(device)
211
+ qf2_target = SoftQNetwork(envs).to(device)
212
+ qf1_target.load_state_dict(qf1.state_dict())
213
+ qf2_target.load_state_dict(qf2.state_dict())
214
+ # TRY NOT TO MODIFY: eps=1e-4 increases numerical stability
215
+ q_optimizer = optim.Adam(list(qf1.parameters()) + list(qf2.parameters()), lr=args.q_lr, eps=1e-4)
216
+ actor_optimizer = optim.Adam(list(actor.parameters()), lr=args.policy_lr, eps=1e-4)
217
+
218
+ # Automatic entropy tuning
219
+ if args.autotune:
220
+ target_entropy = -args.target_entropy_scale * torch.log(1 / torch.tensor(envs.single_action_space.n))
221
+ log_alpha = torch.zeros(1, requires_grad=True, device=device)
222
+ alpha = log_alpha.exp().item()
223
+ a_optimizer = optim.Adam([log_alpha], lr=args.q_lr, eps=1e-4)
224
+ else:
225
+ alpha = args.alpha
226
+
227
+ rb = ReplayBuffer(
228
+ args.buffer_size,
229
+ envs.single_observation_space,
230
+ envs.single_action_space,
231
+ device,
232
+ handle_timeout_termination=False,
233
+ )
234
+ start_time = time.time()
235
+
236
+ # TRY NOT TO MODIFY: start the game
237
+ obs, _ = envs.reset(seed=args.seed)
238
+ for global_step in range(args.total_timesteps):
239
+ # ALGO LOGIC: put action logic here
240
+ if global_step < args.learning_starts:
241
+ actions = np.array([envs.single_action_space.sample() for _ in range(envs.num_envs)])
242
+ else:
243
+ actions, _, _ = actor.get_action(torch.Tensor(obs).to(device))
244
+ actions = actions.detach().cpu().numpy()
245
+
246
+ # TRY NOT TO MODIFY: execute the game and log data.
247
+ next_obs, rewards, terminations, truncations, infos = envs.step(actions)
248
+
249
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
250
+ if "final_info" in infos:
251
+ for info in infos["final_info"]:
252
+ # Skip the envs that are not done
253
+ if "episode" not in info:
254
+ continue
255
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
256
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
257
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
258
+ break
259
+
260
+ # TRY NOT TO MODIFY: save data to reply buffer; handle `final_observation`
261
+ real_next_obs = next_obs.copy()
262
+ for idx, trunc in enumerate(truncations):
263
+ if trunc:
264
+ real_next_obs[idx] = infos["final_observation"][idx]
265
+ rb.add(obs, real_next_obs, actions, rewards, terminations, infos)
266
+
267
+ # TRY NOT TO MODIFY: CRUCIAL step easy to overlook
268
+ obs = next_obs
269
+
270
+ # ALGO LOGIC: training.
271
+ if global_step > args.learning_starts:
272
+ if global_step % args.update_frequency == 0:
273
+ data = rb.sample(args.batch_size)
274
+ # CRITIC training
275
+ with torch.no_grad():
276
+ _, next_state_log_pi, next_state_action_probs = actor.get_action(data.next_observations)
277
+ qf1_next_target = qf1_target(data.next_observations)
278
+ qf2_next_target = qf2_target(data.next_observations)
279
+ # we can use the action probabilities instead of MC sampling to estimate the expectation
280
+ min_qf_next_target = next_state_action_probs * (
281
+ torch.min(qf1_next_target, qf2_next_target) - alpha * next_state_log_pi
282
+ )
283
+ # adapt Q-target for discrete Q-function
284
+ min_qf_next_target = min_qf_next_target.sum(dim=1)
285
+ next_q_value = data.rewards.flatten() + (1 - data.dones.flatten()) * args.gamma * (min_qf_next_target)
286
+
287
+ # use Q-values only for the taken actions
288
+ qf1_values = qf1(data.observations)
289
+ qf2_values = qf2(data.observations)
290
+ qf1_a_values = qf1_values.gather(1, data.actions.long()).view(-1)
291
+ qf2_a_values = qf2_values.gather(1, data.actions.long()).view(-1)
292
+ qf1_loss = F.mse_loss(qf1_a_values, next_q_value)
293
+ qf2_loss = F.mse_loss(qf2_a_values, next_q_value)
294
+ qf_loss = qf1_loss + qf2_loss
295
+
296
+ q_optimizer.zero_grad()
297
+ qf_loss.backward()
298
+ q_optimizer.step()
299
+
300
+ # ACTOR training
301
+ _, log_pi, action_probs = actor.get_action(data.observations)
302
+ with torch.no_grad():
303
+ qf1_values = qf1(data.observations)
304
+ qf2_values = qf2(data.observations)
305
+ min_qf_values = torch.min(qf1_values, qf2_values)
306
+ # no need for reparameterization, the expectation can be calculated for discrete actions
307
+ actor_loss = (action_probs * ((alpha * log_pi) - min_qf_values)).mean()
308
+
309
+ actor_optimizer.zero_grad()
310
+ actor_loss.backward()
311
+ actor_optimizer.step()
312
+
313
+ if args.autotune:
314
+ # reuse action probabilities for temperature loss
315
+ alpha_loss = (action_probs.detach() * (-log_alpha.exp() * (log_pi + target_entropy).detach())).mean()
316
+
317
+ a_optimizer.zero_grad()
318
+ alpha_loss.backward()
319
+ a_optimizer.step()
320
+ alpha = log_alpha.exp().item()
321
+
322
+ # update the target networks
323
+ if global_step % args.target_network_frequency == 0:
324
+ for param, target_param in zip(qf1.parameters(), qf1_target.parameters()):
325
+ target_param.data.copy_(args.tau * param.data + (1 - args.tau) * target_param.data)
326
+ for param, target_param in zip(qf2.parameters(), qf2_target.parameters()):
327
+ target_param.data.copy_(args.tau * param.data + (1 - args.tau) * target_param.data)
328
+
329
+ if global_step % 100 == 0:
330
+ writer.add_scalar("losses/qf1_values", qf1_a_values.mean().item(), global_step)
331
+ writer.add_scalar("losses/qf2_values", qf2_a_values.mean().item(), global_step)
332
+ writer.add_scalar("losses/qf1_loss", qf1_loss.item(), global_step)
333
+ writer.add_scalar("losses/qf2_loss", qf2_loss.item(), global_step)
334
+ writer.add_scalar("losses/qf_loss", qf_loss.item() / 2.0, global_step)
335
+ writer.add_scalar("losses/actor_loss", actor_loss.item(), global_step)
336
+ writer.add_scalar("losses/alpha", alpha, global_step)
337
+ print("SPS:", int(global_step / (time.time() - start_time)))
338
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
339
+ if args.autotune:
340
+ writer.add_scalar("losses/alpha_loss", alpha_loss.item(), global_step)
341
+
342
+ envs.close()
343
+ writer.close()
cleanrl/cleanrl/scout_dqn/dqn_bandit_nochangeenv.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DQN 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 Deque, 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
+ from ragen.env.bandit.env import BanditEnv
22
+ from ragen.env.bandit.config import BanditEnvConfig
23
+ from ragen_wrappers import BanditWrapper
24
+
25
+
26
+ @dataclass
27
+ class Args:
28
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
29
+ seed: int = 1
30
+ torch_deterministic: bool = True
31
+ cuda: bool = True
32
+ track: bool = True
33
+ wandb_project_name: str = "Subagent"
34
+ wandb_entity: str | None = None
35
+ capture_video: bool = False
36
+
37
+ # Algorithm
38
+ env_id: str = "BanditDQN"
39
+ total_timesteps: int = 50_000
40
+ learning_rate: float = 1e-3
41
+ gamma: float = 0.0 # bandit is single-step
42
+ batch_size: int = 64
43
+ buffer_size: int = 10_000
44
+ target_network_frequency: int = 500
45
+ train_frequency: int = 1
46
+
47
+ # Epsilon-greedy
48
+ start_e: float = 1.0
49
+ end_e: float = 0.05
50
+ exploration_fraction: float = 0.2 # fraction of total timesteps over which to anneal epsilon
51
+
52
+ # Model size
53
+ hidden_size: int = 32
54
+ feature_dim_per_name: int = 16
55
+
56
+
57
+ def make_env(run_name: str, seed: int, feature_dim_per_name: int, capture_video: bool = False):
58
+ cfg = BanditEnvConfig()
59
+ env = BanditEnv(cfg)
60
+ env = BanditWrapper(env, feature_dim_per_name=feature_dim_per_name)
61
+ env = gym.wrappers.RecordEpisodeStatistics(env)
62
+ if capture_video:
63
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
64
+ return env
65
+
66
+
67
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
68
+ torch.nn.init.orthogonal_(layer.weight, std)
69
+ torch.nn.init.constant_(layer.bias, bias_const)
70
+ return layer
71
+
72
+
73
+ class QNetwork(nn.Module):
74
+ def __init__(self, obs_dim: int, act_dim: int, hidden: int):
75
+ super().__init__()
76
+ self.net = nn.Sequential(
77
+ layer_init(nn.Linear(obs_dim, hidden)),
78
+ nn.ReLU(),
79
+ layer_init(nn.Linear(hidden, hidden)),
80
+ nn.ReLU(),
81
+ layer_init(nn.Linear(hidden, act_dim), std=0.01),
82
+ )
83
+
84
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
85
+ return self.net(x)
86
+
87
+
88
+ class ReplayBuffer:
89
+ def __init__(self, capacity: int):
90
+ self.capacity = capacity
91
+ self.ptr = 0
92
+ self.full = False
93
+ self.obs_buf = None
94
+ self.next_obs_buf = None
95
+ self.act_buf = None
96
+ self.rew_buf = None
97
+ self.done_buf = None
98
+
99
+ def add(self, obs: np.ndarray, act: int, rew: float, done: bool, next_obs: np.ndarray):
100
+ if self.obs_buf is None:
101
+ obs_shape = obs.shape
102
+ self.obs_buf = np.zeros((self.capacity,) + obs_shape, dtype=np.float32)
103
+ self.next_obs_buf = np.zeros((self.capacity,) + obs_shape, dtype=np.float32)
104
+ self.act_buf = np.zeros((self.capacity,), dtype=np.int64)
105
+ self.rew_buf = np.zeros((self.capacity,), dtype=np.float32)
106
+ self.done_buf = np.zeros((self.capacity,), dtype=np.float32)
107
+ self.obs_buf[self.ptr] = obs
108
+ self.next_obs_buf[self.ptr] = next_obs
109
+ self.act_buf[self.ptr] = act
110
+ self.rew_buf[self.ptr] = rew
111
+ self.done_buf[self.ptr] = 1.0 if done else 0.0
112
+ self.ptr = (self.ptr + 1) % self.capacity
113
+ if self.ptr == 0:
114
+ self.full = True
115
+
116
+ def can_sample(self, batch_size: int) -> bool:
117
+ return (self.capacity if self.full else self.ptr) >= batch_size
118
+
119
+ def sample(self, batch_size: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
120
+ size = self.capacity if self.full else self.ptr
121
+ idxs = np.random.randint(0, size, size=batch_size)
122
+ return (
123
+ self.obs_buf[idxs],
124
+ self.act_buf[idxs],
125
+ self.rew_buf[idxs],
126
+ self.done_buf[idxs],
127
+ self.next_obs_buf[idxs],
128
+ )
129
+
130
+
131
+ if __name__ == "__main__":
132
+ args = tyro.cli(Args)
133
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
134
+
135
+ if args.track:
136
+ import wandb
137
+ wandb.init(
138
+ project=args.wandb_project_name,
139
+ entity=args.wandb_entity,
140
+ config=vars(args),
141
+ name=run_name,
142
+ monitor_gym=True,
143
+ save_code=True,
144
+ )
145
+ try:
146
+ wandb.define_metric("global_step")
147
+ for prefix in ["train/*", "rollout/*", "eval/*", "losses/*", "charts/*", "perf/*"]:
148
+ wandb.define_metric(prefix, step_metric="global_step")
149
+ except Exception:
150
+ pass
151
+
152
+ # seeding
153
+ random.seed(args.seed)
154
+ np.random.seed(args.seed)
155
+ torch.manual_seed(args.seed)
156
+ torch.backends.cudnn.deterministic = args.torch_deterministic
157
+
158
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
159
+
160
+ # env
161
+ env = make_env(run_name, args.seed, args.feature_dim_per_name, args.capture_video)
162
+ obs_shape = env.observation_space.shape
163
+ act_dim = env.action_space.n
164
+
165
+ # networks
166
+ policy_net = QNetwork(int(np.prod(obs_shape)), act_dim, args.hidden_size).to(device)
167
+ target_net = QNetwork(int(np.prod(obs_shape)), act_dim, args.hidden_size).to(device)
168
+ target_net.load_state_dict(policy_net.state_dict())
169
+ target_net.eval()
170
+
171
+ optimizer = optim.Adam(policy_net.parameters(), lr=args.learning_rate)
172
+ criterion = nn.SmoothL1Loss()
173
+
174
+ rb = ReplayBuffer(args.buffer_size)
175
+
176
+ # epsilon schedule
177
+ exploration_steps = max(1, int(args.exploration_fraction * args.total_timesteps))
178
+ epsilon_by_step = lambda t: args.end_e + (args.start_e - args.end_e) * max(0.0, (exploration_steps - t) / exploration_steps)
179
+
180
+ # periodic eval setup (mirrors noisy_dqn_sokoban_small.py)
181
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes: int, step_tag: int):
182
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
183
+ out_dir.mkdir(parents=True, exist_ok=True)
184
+ out_path = out_dir / "trajectories.jsonl"
185
+ env_eval = make_env_fn()
186
+ collected = 0
187
+ summary_returns = []
188
+ summary_success = []
189
+ with out_path.open("w") as f:
190
+ while collected < n_episodes:
191
+ state, _ = env_eval.reset(seed=args.seed + 100000 + collected)
192
+ # try to fetch the original prompt text from underlying env
193
+ prompt_text = None
194
+ try:
195
+ if hasattr(env_eval, 'env') and hasattr(env_eval.env, 'render'):
196
+ p = env_eval.env.render()
197
+ if isinstance(p, str):
198
+ prompt_text = p
199
+ except Exception:
200
+ pass
201
+ # lightweight name parser (aligned with converter/wrapper)
202
+ def _parse_names(text: str):
203
+ try:
204
+ anchor = "named "
205
+ if isinstance(text, str) and anchor in text:
206
+ segment = text.split(anchor, 1)[1]
207
+ segment = segment.split("\n", 1)[0]
208
+ parts = segment.split(" and ")
209
+ if len(parts) >= 2:
210
+ a = parts[0].strip().strip(' .!?,')
211
+ b = parts[1].strip().strip(' .!?,')
212
+ if a and b:
213
+ return a, b
214
+ except Exception:
215
+ pass
216
+ return None
217
+ names_tuple = _parse_names(prompt_text) if prompt_text else None
218
+ traj_states = [np.asarray(state).tolist()]
219
+ traj_actions = []
220
+ traj_rewards = []
221
+ traj_dones = []
222
+ traj_success = []
223
+ done = False
224
+ # bandit is single-step, but keep loop for generality
225
+ while not done:
226
+ with torch.no_grad():
227
+ q = agent_model(torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0))
228
+ action = int(torch.argmax(q, dim=1).item())
229
+ next_state, reward, terminated, truncated, info = env_eval.step(action)
230
+ d = bool(terminated) or bool(truncated)
231
+ traj_actions.append(int(action))
232
+ traj_rewards.append(float(reward))
233
+ traj_dones.append(d)
234
+ traj_success.append(bool((info or {}).get('success', False)))
235
+ state = next_state
236
+ traj_states.append(np.asarray(state).tolist())
237
+ done = d
238
+ ep_ret = float(sum(traj_rewards))
239
+ ep_succ = bool(any(traj_success))
240
+ record = {
241
+ "states": traj_states,
242
+ "actions": traj_actions,
243
+ "rewards": traj_rewards,
244
+ "dones": traj_dones,
245
+ "success": traj_success,
246
+ "episode_return": ep_ret,
247
+ "episode_success": ep_succ,
248
+ "prompt": prompt_text,
249
+ "names": list(names_tuple) if names_tuple is not None else None,
250
+ }
251
+ f.write(json.dumps(record) + "\n")
252
+ collected += 1
253
+ summary_returns.append(ep_ret)
254
+ summary_success.append(1.0 if ep_succ else 0.0)
255
+ env_eval.close()
256
+ try:
257
+ metrics = {
258
+ "global_step": int(step_tag),
259
+ "episodes": int(n_episodes),
260
+ "success_rate": float(np.mean(summary_success)) if len(summary_success) else 0.0,
261
+ "avg_return": float(np.mean(summary_returns)) if len(summary_returns) else 0.0,
262
+ "std_return": float(np.std(summary_returns)) if len(summary_returns) else 0.0,
263
+ }
264
+ with (out_dir / "metrics.json").open("w") as mf:
265
+ json.dump(metrics, mf)
266
+ except Exception as e:
267
+ print(f"Warning: failed to write eval metrics: {e}")
268
+
269
+ # choose periodicity similar to reference
270
+ eval_splits = 2
271
+ eval_episodes = 4000
272
+ eval_every_steps = max(1, args.total_timesteps // eval_splits)
273
+
274
+ # training loop
275
+ global_step = 0
276
+ start_time = time.time()
277
+
278
+ obs, _ = env.reset(seed=args.seed)
279
+ # success tracking
280
+ ep_success_window = deque(maxlen=100)
281
+ total_episodes = 0
282
+ total_successes = 0
283
+
284
+ while global_step < args.total_timesteps:
285
+ epsilon = epsilon_by_step(global_step)
286
+ if np.random.rand() < epsilon:
287
+ action = env.action_space.sample()
288
+ else:
289
+ with torch.no_grad():
290
+ q_values = policy_net(torch.tensor(obs, dtype=torch.float32, device=device).unsqueeze(0))
291
+ action = int(torch.argmax(q_values, dim=1).item())
292
+ next_obs, reward, terminated, truncated, info = env.step(action)
293
+ done = bool(terminated) or bool(truncated)
294
+
295
+ rb.add(obs.astype(np.float32), action, float(reward), done, next_obs.astype(np.float32))
296
+
297
+ obs = next_obs
298
+ global_step += 1
299
+
300
+ # Bandit episodes end in one step; reset immediately
301
+ if done:
302
+ # record success
303
+ succ = bool(info.get('success', False))
304
+ ep_success_window.append(1.0 if succ else 0.0)
305
+ total_episodes += 1
306
+ total_successes += (1 if succ else 0)
307
+ if args.track:
308
+ try:
309
+ import wandb
310
+ wandb.log({
311
+ "global_step": int(global_step),
312
+ "rollout/success": float(1.0 if succ else 0.0),
313
+ "rollout/success_rate_100": float(np.mean(ep_success_window)) if len(ep_success_window) > 0 else None,
314
+ "rollout/episodes": int(total_episodes),
315
+ }, step=global_step)
316
+ except Exception:
317
+ pass
318
+ obs, _ = env.reset()
319
+
320
+ # optimize
321
+ if rb.can_sample(args.batch_size) and (global_step % args.train_frequency == 0):
322
+ batch_obs, batch_act, batch_rew, batch_done, batch_next_obs = rb.sample(args.batch_size)
323
+ b_obs = torch.tensor(batch_obs, dtype=torch.float32, device=device)
324
+ b_act = torch.tensor(batch_act, dtype=torch.int64, device=device)
325
+ b_rew = torch.tensor(batch_rew, dtype=torch.float32, device=device)
326
+ b_done = torch.tensor(batch_done, dtype=torch.float32, device=device)
327
+ b_next_obs = torch.tensor(batch_next_obs, dtype=torch.float32, device=device)
328
+
329
+ # Q-learning target: r + gamma * max_a' Q_target(s', a') * (1-done)
330
+ with torch.no_grad():
331
+ next_q = target_net(b_next_obs).max(dim=1)[0]
332
+ target_q = b_rew + args.gamma * (1.0 - b_done) * next_q
333
+
334
+ current_q = policy_net(b_obs).gather(1, b_act.view(-1, 1)).squeeze(1)
335
+ loss = criterion(current_q, target_q)
336
+
337
+ optimizer.zero_grad()
338
+ loss.backward()
339
+ nn.utils.clip_grad_norm_(policy_net.parameters(), max_norm=10.0)
340
+ optimizer.step()
341
+
342
+ if args.track:
343
+ try:
344
+ import wandb
345
+ wandb.log({
346
+ "global_step": int(global_step),
347
+ "train/loss": float(loss.item()),
348
+ "charts/epsilon": float(epsilon),
349
+ "perf/SPS": int(global_step / (time.time() - start_time)),
350
+ }, step=global_step)
351
+ except Exception:
352
+ pass
353
+
354
+ # target network update
355
+ if global_step % args.target_network_frequency == 0:
356
+ target_net.load_state_dict(policy_net.state_dict())
357
+
358
+ # occasional print
359
+ if global_step % 1000 == 0:
360
+ sps = int(global_step / (time.time() - start_time))
361
+ sr100 = float(np.mean(ep_success_window)) if len(ep_success_window) > 0 else 0.0
362
+ print(f"Step {global_step} | SPS: {sps} | Epsilon: {epsilon:.3f} | SR@100: {sr100:.3f}")
363
+
364
+ # periodic evaluation and trajectory dump (mirrors reference)
365
+ if global_step == 1 or (global_step % eval_every_steps == 0):
366
+ try:
367
+ def eval_thunk():
368
+ return make_env(run_name, args.seed + 9999, args.feature_dim_per_name, False)
369
+ collect_eval_trajectories(policy_net, eval_thunk, n_episodes=eval_episodes, step_tag=global_step)
370
+ if args.track:
371
+ try:
372
+ import wandb
373
+ mpath = Path(f"runs/{run_name}/trajectories/step_{global_step}/metrics.json")
374
+ if mpath.exists():
375
+ with mpath.open("r") as mf:
376
+ metrics = json.load(mf)
377
+ wandb.log({
378
+ "eval/success_rate": metrics.get("success_rate"),
379
+ "eval/avg_return": metrics.get("avg_return"),
380
+ "eval/std_return": metrics.get("std_return"),
381
+ "eval/episodes": metrics.get("episodes"),
382
+ }, step=global_step)
383
+ except Exception:
384
+ pass
385
+ print(f"Collected {eval_episodes} eval trajectories at step {global_step}")
386
+ except Exception as e:
387
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
388
+
389
+ # simple evaluation after training
390
+ def evaluate(n_episodes=200):
391
+ returns = []
392
+ successes = []
393
+ for i in range(n_episodes):
394
+ s, _ = env.reset(seed=args.seed + 100000 + i)
395
+ done = False
396
+ G = 0.0
397
+ while not done:
398
+ with torch.no_grad():
399
+ q = policy_net(torch.tensor(s, dtype=torch.float32, device=device).unsqueeze(0))
400
+ a = int(torch.argmax(q, dim=1).item())
401
+ s, r, term, trunc, info = env.step(a)
402
+ G += float(r)
403
+ done = bool(term) or bool(trunc)
404
+ successes.append(1.0 if bool(info.get('success', False)) else 0.0)
405
+ returns.append(G)
406
+ return float(np.mean(returns)), float(np.std(returns)), float(np.mean(successes))
407
+
408
+ avg_ret, std_ret, succ_rate = evaluate(4000)
409
+ if args.track:
410
+ try:
411
+ import wandb
412
+ wandb.log({
413
+ "global_step": int(global_step),
414
+ "eval/avg_return": float(avg_ret),
415
+ "eval/std_return": float(std_ret),
416
+ "eval/episodes": int(4000),
417
+ "eval/success_rate": float(succ_rate),
418
+ }, step=global_step)
419
+ except Exception:
420
+ pass
421
+
422
+ env.close()
cleanrl/cleanrl/scout_dqn/dqn_frozenlake.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DQN with small MLP for RAGEN FrozenLake 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
8
+ import json
9
+ import re # Added for ANSI strip
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
+
18
+ import sys
19
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../'))
20
+
21
+ from ragen.env.frozen_lake.env import FrozenLakeEnv
22
+ from ragen.env.frozen_lake.config import FrozenLakeEnvConfig
23
+
24
+
25
+ class FrozenLakeWrapper(gym.Env):
26
+ metadata = {"render_modes": ["rgb_array", "human", "ansi"]}
27
+
28
+ def __init__(self, env: FrozenLakeEnv):
29
+ super().__init__()
30
+ self._env = env
31
+ self._size = int(self._env.nrow)
32
+ self._tokens = ['P', '_', 'O', 'G', 'X', '√']
33
+ self._token_to_idx = {t: i for i, t in enumerate(self._tokens)}
34
+ self.observation_space = gym.spaces.Box(low=0.0, high=1.0, shape=(self._size * self._size * len(self._tokens),), dtype=np.float32)
35
+ self.action_space = gym.spaces.Discrete(4)
36
+
37
+ def _encode_obs(self, text_obs: str) -> np.ndarray:
38
+ # 1. 去除 ANSI 颜色代码
39
+ ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
40
+ text_obs = ansi_escape.sub('', text_obs)
41
+
42
+ # 2. 清理边框和分割行
43
+ raw_rows = text_obs.split('\n')
44
+ rows = []
45
+ for r in raw_rows:
46
+ clean_r = r.strip()
47
+ # 跳过边框行 (如 +---+) 或空行
48
+ if not clean_r or set(clean_r).issubset({'+', '-', ' '}):
49
+ continue
50
+ # 去除行首行尾的竖线 (如 | P | -> P )
51
+ clean_r = clean_r.strip('|')
52
+ rows.append(list(clean_r))
53
+
54
+ # 3. 构建 Grid
55
+ h = self._size
56
+ w = self._size
57
+ grid = np.zeros((h, w, len(self._tokens)), dtype=np.float32)
58
+
59
+ # 安全填充,防止索引越界
60
+ for i in range(min(h, len(rows))):
61
+ for j in range(min(w, len(rows[i]))):
62
+ ch = rows[i][j]
63
+ # 修复: 只有在 token 列表中才置1,遇到未知字符(如墙壁)不默认为 Player(0)
64
+ if ch in self._token_to_idx:
65
+ idx = self._token_to_idx[ch]
66
+ grid[i, j, idx] = 1.0
67
+
68
+ return grid.reshape(-1).astype(np.float32)
69
+
70
+ def reset(self, *, seed: int | None = None, options: Dict[str, Any] | None = None):
71
+ text_obs = self._env.reset(seed=seed)
72
+ obs = self._encode_obs(text_obs)
73
+ return obs, {}
74
+
75
+ def step(self, action: int):
76
+ mapped = int(action) + 1
77
+ text_obs, reward, done, info = self._env.step(mapped)
78
+ obs = self._encode_obs(text_obs)
79
+ terminated = bool(done)
80
+ truncated = False
81
+ return obs, float(reward), terminated, truncated, info or {}
82
+
83
+ def render(self):
84
+ return self._env.render()
85
+
86
+ def close(self):
87
+ self._env.close()
88
+
89
+
90
+ @dataclass
91
+ class Args:
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 = "cleanRL"
98
+ wandb_entity: str | None = None
99
+ capture_video: bool = False
100
+
101
+ # Algorithm
102
+ env_id: str = "FrozenLakeDQN"
103
+ total_timesteps: int = 4000_000
104
+ learning_rate: float = 2.5e-4
105
+ gamma: float = 0.99
106
+ batch_size: int = 128
107
+ buffer_size: int = 200_000
108
+ target_network_frequency: int = 2000
109
+ train_frequency: int = 4
110
+ learning_starts: int = 5000
111
+
112
+ # Epsilon-greedy
113
+ start_e: float = 1.0
114
+ end_e: float = 0.05
115
+ exploration_fraction: float = 0.2
116
+
117
+ # Model size
118
+ hidden_size: int = 128
119
+
120
+ # FrozenLake specific
121
+ grid_size: int = 4
122
+ is_slippery: bool = False
123
+
124
+ # Eval
125
+ eval_splits: int = 1
126
+ eval_episodes: int = 4000
127
+
128
+
129
+ def make_env(idx, run_name, seed, grid_size, is_slippery, capture_video=False):
130
+ def thunk():
131
+ config = FrozenLakeEnvConfig(size=grid_size, p=0.9, success_rate=0.8, is_slippery=is_slippery, map_seed=seed + idx, render_mode='text')
132
+ env = FrozenLakeEnv(config)
133
+ env = FrozenLakeWrapper(env)
134
+ max_steps = int(grid_size * grid_size * 4)
135
+ env = gym.wrappers.TimeLimit(env, max_episode_steps=max_steps)
136
+ env = gym.wrappers.RecordEpisodeStatistics(env)
137
+ if capture_video and idx == 0:
138
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
139
+ return env
140
+ return thunk
141
+
142
+
143
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
144
+ torch.nn.init.orthogonal_(layer.weight, std)
145
+ torch.nn.init.constant_(layer.bias, bias_const)
146
+ return layer
147
+
148
+
149
+ class QNetwork(nn.Module):
150
+ def __init__(self, obs_dim: int, act_dim: int, hidden: int):
151
+ super().__init__()
152
+ self.net = nn.Sequential(
153
+ layer_init(nn.Linear(obs_dim, hidden)),
154
+ nn.ReLU(),
155
+ layer_init(nn.Linear(hidden, hidden)),
156
+ nn.ReLU(),
157
+ layer_init(nn.Linear(hidden, act_dim), std=0.01),
158
+ )
159
+
160
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
161
+ return self.net(x)
162
+
163
+
164
+ class ReplayBuffer:
165
+ def __init__(self, capacity: int, obs_shape: Tuple[int, ...]):
166
+ self.capacity = capacity
167
+ self.ptr = 0
168
+ self.full = False
169
+ self.obs_buf = np.zeros((capacity,) + obs_shape, dtype=np.float32)
170
+ self.next_obs_buf = np.zeros((capacity,) + obs_shape, dtype=np.float32)
171
+ self.act_buf = np.zeros((capacity,), dtype=np.int64)
172
+ self.rew_buf = np.zeros((capacity,), dtype=np.float32)
173
+ self.done_buf = np.zeros((capacity,), dtype=np.float32)
174
+
175
+ def add(self, obs: np.ndarray, act: int, rew: float, done: bool, next_obs: np.ndarray):
176
+ i = self.ptr
177
+ self.obs_buf[i] = obs
178
+ self.next_obs_buf[i] = next_obs
179
+ self.act_buf[i] = act
180
+ self.rew_buf[i] = rew
181
+ self.done_buf[i] = 1.0 if done else 0.0
182
+ self.ptr = (self.ptr + 1) % self.capacity
183
+ if self.ptr == 0:
184
+ self.full = True
185
+
186
+ def can_sample(self, batch_size: int) -> bool:
187
+ return (self.capacity if self.full else self.ptr) >= batch_size
188
+
189
+ def sample(self, batch_size: int):
190
+ size = self.capacity if self.full else self.ptr
191
+ idxs = np.random.randint(0, size, size=batch_size)
192
+ return (
193
+ self.obs_buf[idxs],
194
+ self.act_buf[idxs],
195
+ self.rew_buf[idxs],
196
+ self.done_buf[idxs],
197
+ self.next_obs_buf[idxs],
198
+ )
199
+
200
+
201
+ if __name__ == "__main__":
202
+ args = tyro.cli(Args)
203
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
204
+
205
+ if args.track:
206
+ import wandb
207
+ wandb.init(
208
+ project=args.wandb_project_name,
209
+ entity=args.wandb_entity,
210
+ config=vars(args),
211
+ name=run_name,
212
+ monitor_gym=True,
213
+ save_code=True,
214
+ )
215
+ try:
216
+ wandb.define_metric("global_step")
217
+ for prefix in ["train/*", "rollout/*", "eval/*", "losses/*", "charts/*", "perf/*"]:
218
+ wandb.define_metric(prefix, step_metric="global_step")
219
+ except Exception:
220
+ pass
221
+
222
+ random.seed(args.seed)
223
+ np.random.seed(args.seed)
224
+ torch.manual_seed(args.seed)
225
+ torch.backends.cudnn.deterministic = args.torch_deterministic
226
+
227
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
228
+
229
+ env = make_env(0, run_name, args.seed, args.grid_size, args.is_slippery, args.capture_video)()
230
+ obs_shape = env.observation_space.shape
231
+ act_dim = env.action_space.n
232
+
233
+ policy_net = QNetwork(int(np.prod(obs_shape)), act_dim, args.hidden_size).to(device)
234
+ target_net = QNetwork(int(np.prod(obs_shape)), act_dim, args.hidden_size).to(device)
235
+ target_net.load_state_dict(policy_net.state_dict())
236
+ target_net.eval()
237
+
238
+ optimizer = optim.Adam(policy_net.parameters(), lr=args.learning_rate)
239
+ criterion = nn.SmoothL1Loss()
240
+
241
+ rb = ReplayBuffer(args.buffer_size, obs_shape)
242
+
243
+ exploration_steps = max(1, int(args.exploration_fraction * args.total_timesteps))
244
+ epsilon_by_step = lambda t: args.end_e + (args.start_e - args.end_e) * max(0.0, (exploration_steps - t) / exploration_steps)
245
+
246
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes, step_tag):
247
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
248
+ out_dir.mkdir(parents=True, exist_ok=True)
249
+ out_path = out_dir / "trajectories.jsonl"
250
+ env_eval = make_env_fn()
251
+ collected = 0
252
+ summary_returns = []
253
+ summary_success = []
254
+ with out_path.open("w") as f:
255
+ while collected < n_episodes:
256
+ state, _ = env_eval.reset(seed=args.seed + 100000 + collected)
257
+ traj_states = [np.asarray(state).tolist()]
258
+ traj_actions = []
259
+ traj_rewards = []
260
+ traj_dones = []
261
+ traj_success = []
262
+ done = False
263
+ step_count = 0
264
+ max_eval_steps = getattr(env_eval, '_max_episode_steps', None) or int(args.grid_size * args.grid_size * 4)
265
+ while not done:
266
+ with torch.no_grad():
267
+ q = agent_model(torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0))
268
+ action = int(torch.argmax(q, dim=1).item())
269
+ next_state, reward, terminated, truncated, info = env_eval.step(action)
270
+ traj_actions.append(int(action))
271
+ traj_rewards.append(float(reward))
272
+ step_count += 1
273
+ d = bool(terminated) or bool(truncated) or (step_count >= max_eval_steps)
274
+ traj_dones.append(d)
275
+ traj_success.append(bool((info or {}).get('success', False)))
276
+ state = next_state
277
+ traj_states.append(np.asarray(state).tolist())
278
+ done = d
279
+ ep_ret = float(sum(traj_rewards))
280
+ ep_succ = bool(any(traj_success))
281
+ record = {
282
+ "states": traj_states,
283
+ "actions": traj_actions,
284
+ "rewards": traj_rewards,
285
+ "dones": traj_dones,
286
+ "success": traj_success,
287
+ "episode_return": ep_ret,
288
+ "episode_success": ep_succ,
289
+ }
290
+ f.write(json.dumps(record) + "\n")
291
+ collected += 1
292
+ summary_returns.append(ep_ret)
293
+ summary_success.append(1.0 if ep_succ else 0.0)
294
+ env_eval.close()
295
+ try:
296
+ metrics = {
297
+ "global_step": int(step_tag),
298
+ "episodes": int(n_episodes),
299
+ "success_rate": float(np.mean(summary_success)) if len(summary_success) else 0.0,
300
+ "avg_return": float(np.mean(summary_returns)) if len(summary_returns) else 0.0,
301
+ "std_return": float(np.std(summary_returns)) if len(summary_returns) else 0.0,
302
+ }
303
+ with (out_dir / "metrics.json").open("w") as mf:
304
+ json.dump(metrics, mf)
305
+ except Exception as e:
306
+ print(f"Warning: failed to write eval metrics: {e}")
307
+
308
+ global_step = 0
309
+ start_time = time.time()
310
+
311
+ obs, _ = env.reset(seed=args.seed)
312
+ ep_success_window = []
313
+ ep_return = 0.0
314
+ ep_len = 0
315
+
316
+ eval_every_steps = max(1, args.total_timesteps // args.eval_splits)
317
+
318
+ while global_step < args.total_timesteps:
319
+ epsilon = epsilon_by_step(global_step)
320
+ if np.random.rand() < epsilon or global_step < args.learning_starts:
321
+ action = env.action_space.sample()
322
+ else:
323
+ with torch.no_grad():
324
+ q_values = policy_net(torch.tensor(obs, dtype=torch.float32, device=device).unsqueeze(0))
325
+ action = int(torch.argmax(q_values, dim=1).item())
326
+
327
+ next_obs, reward, terminated, truncated, info = env.step(action)
328
+ # 注意:这里 done 仅用于控制循环和 logging,不用于 ReplayBuffer 的逻辑判断
329
+ done = bool(terminated) or bool(truncated)
330
+
331
+ # 修复:Buffer 中只存储真正的 termination (死亡或到达),不存 truncation (超时)
332
+ # 这样 Q-learning 在超时时不会错误地认为价值归零
333
+ rb.add(obs.astype(np.float32), int(action), float(reward), bool(terminated), next_obs.astype(np.float32))
334
+
335
+ obs = next_obs
336
+ ep_return += float(reward)
337
+ ep_len += 1
338
+ global_step += 1
339
+
340
+ if done:
341
+ succ = bool((info or {}).get('success', False))
342
+ ep_success_window.append(1.0 if succ else 0.0)
343
+ if len(ep_success_window) > 100:
344
+ ep_success_window.pop(0)
345
+ if args.track:
346
+ try:
347
+ import wandb
348
+ wandb.log({
349
+ "global_step": int(global_step),
350
+ "rollout/success": float(1.0 if succ else 0.0),
351
+ "rollout/success_rate_100": float(np.mean(ep_success_window)) if len(ep_success_window) > 0 else None,
352
+ # PPO-compatible episodic keys
353
+ "train/episodic_return": float(ep_return),
354
+ "train/episodic_length": int(ep_len),
355
+ "train/success": float(1.0 if succ else 0.0),
356
+ "train/success_rate_100": float(np.mean(ep_success_window)) if len(ep_success_window) > 0 else None,
357
+ }, step=global_step)
358
+ except Exception:
359
+ pass
360
+ obs, _ = env.reset()
361
+ ep_return, ep_len = 0.0, 0
362
+
363
+ if rb.can_sample(args.batch_size) and (global_step % args.train_frequency == 0) and (global_step > args.learning_starts):
364
+ batch_obs, batch_act, batch_rew, batch_done, batch_next_obs = rb.sample(args.batch_size)
365
+ b_obs = torch.tensor(batch_obs, dtype=torch.float32, device=device)
366
+ b_act = torch.tensor(batch_act, dtype=torch.int64, device=device)
367
+ b_rew = torch.tensor(batch_rew, dtype=torch.float32, device=device)
368
+ b_done = torch.tensor(batch_done, dtype=torch.float32, device=device)
369
+ b_next_obs = torch.tensor(batch_next_obs, dtype=torch.float32, device=device)
370
+
371
+ with torch.no_grad():
372
+ next_q = target_net(b_next_obs).max(dim=1)[0]
373
+ target_q = b_rew + args.gamma * (1.0 - b_done) * next_q
374
+
375
+ current_q = policy_net(b_obs).gather(1, b_act.view(-1, 1)).squeeze(1)
376
+ loss = criterion(current_q, target_q)
377
+
378
+ optimizer.zero_grad()
379
+ loss.backward()
380
+ nn.utils.clip_grad_norm_(policy_net.parameters(), max_norm=10.0)
381
+ optimizer.step()
382
+
383
+ if args.track:
384
+ try:
385
+ import wandb
386
+ wandb.log({
387
+ "global_step": int(global_step),
388
+ "train/loss": float(loss.item()),
389
+ "charts/epsilon": float(epsilon),
390
+ "perf/SPS": int(global_step / (time.time() - start_time)),
391
+ "train/learning_rate": float(optimizer.param_groups[0]["lr"]),
392
+ }, step=global_step)
393
+ except Exception:
394
+ pass
395
+
396
+ if global_step % args.target_network_frequency == 0:
397
+ target_net.load_state_dict(policy_net.state_dict())
398
+
399
+ if global_step % 1000 == 0:
400
+ sps = int(global_step / (time.time() - start_time))
401
+ sr100 = float(np.mean(ep_success_window)) if len(ep_success_window) > 0 else 0.0
402
+ print(f"Step {global_step} | SPS: {sps} | Epsilon: {epsilon:.3f} | SR@100: {sr100:.3f}")
403
+
404
+ if global_step == 1 or (global_step % eval_every_steps == 0):
405
+ try:
406
+ def eval_thunk():
407
+ return make_env(0, run_name, args.seed + 9999, args.grid_size, args.is_slippery, False)()
408
+ collect_eval_trajectories(policy_net, eval_thunk, n_episodes=args.eval_episodes, step_tag=global_step)
409
+ if args.track:
410
+ try:
411
+ import wandb
412
+ mpath = Path(f"runs/{run_name}/trajectories/step_{global_step}/metrics.json")
413
+ if mpath.exists():
414
+ with mpath.open("r") as mf:
415
+ metrics = json.load(mf)
416
+ wandb.log({
417
+ "eval/success_rate": metrics.get("success_rate"),
418
+ "eval/avg_return": metrics.get("avg_return"),
419
+ "eval/std_return": metrics.get("std_return"),
420
+ "eval/episodes": metrics.get("episodes"),
421
+ }, step=global_step)
422
+ except Exception:
423
+ pass
424
+ print(f"Collected {args.eval_episodes} eval trajectories at step {global_step}")
425
+ except Exception as e:
426
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
427
+
428
+ env.close()
cleanrl/cleanrl/scout_dqn/dqn_rubikscube.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DQN with Step Penalty & Time Limit Bootstrap for RAGEN Rubik's Cube 2x2
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
+
18
+ import sys
19
+ # 假设 ragen 库在当前目录的上两级,请根据实际情况调整
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
+ metadata = {"render_modes": ["rgb_array", "human", "ansi"]}
28
+
29
+ def __init__(self, env: RubiksCube2x2Env):
30
+ super().__init__()
31
+ self._env = env
32
+ self._colors = ['W', 'O', 'G', 'R', 'B', 'Y']
33
+ self._color_to_idx = {c: i for i, c in enumerate(self._colors)}
34
+ self.observation_space = gym.spaces.Box(low=0.0, high=1.0, shape=(24 * len(self._colors),), dtype=np.float32)
35
+ self.action_space = gym.spaces.Discrete(12)
36
+ self._face_pat = re.compile(r"\[(?:\s*([A-Z])\s*,\s*([A-Z])\s*\])\n\s*\[(?:\s*([A-Z])\s*,\s*([A-Z])\s*\])")
37
+
38
+ # [关键修改] 每步惩罚
39
+ # 如果20步都没解出来,累计惩罚是 20 * -0.05 = -1.0,抵消掉最后可能获得的 +1.0
40
+ # 这迫使 agent 寻找更短路径
41
+ self.step_penalty = -0.044
42
+
43
+ def _encode_obs(self, text_obs: str) -> np.ndarray:
44
+ faces_order = ["Up (U):", "Left (L):", "Front (F):", "Right (R):", "Back (B):", "Down (D):"]
45
+ lines = text_obs.splitlines()
46
+ blocks: List[str] = []
47
+ i = 0
48
+ while i < len(lines):
49
+ line = lines[i]
50
+ for header in faces_order:
51
+ if line.startswith(header):
52
+ content = line[len(header):].strip()
53
+ next_line = lines[i + 1] if i + 1 < len(lines) else ""
54
+ block = f"{content}\n{next_line}"
55
+ blocks.append(block)
56
+ break
57
+ i += 1
58
+ if len(blocks) != 6:
59
+ return np.zeros(24 * len(self._colors), dtype=np.float32)
60
+ stickers: List[int] = []
61
+ for blk in blocks:
62
+ m = self._face_pat.search(blk)
63
+ if not m:
64
+ return np.zeros(24 * len(self._colors), dtype=np.float32)
65
+ c0, c1, c2, c3 = m.group(1), m.group(2), m.group(3), m.group(4)
66
+ stickers.extend([c0, c1, c2, c3])
67
+ grid = np.zeros((24, len(self._colors)), dtype=np.float32)
68
+ for idx, ch in enumerate(stickers):
69
+ cidx = self._color_to_idx.get(ch, None)
70
+ if cidx is not None:
71
+ grid[idx, cidx] = 1.0
72
+ return grid.reshape(-1)
73
+
74
+ def reset(self, *, seed: int | None = None, options: Dict[str, Any] | None = None):
75
+ text_obs = self._env.reset(seed=seed)
76
+ obs = self._encode_obs(text_obs)
77
+ return obs, {}
78
+
79
+ def step(self, action: int):
80
+ mapped = int(action) + 1
81
+ text_obs, reward, done, info = self._env.step(mapped)
82
+ obs = self._encode_obs(text_obs)
83
+ terminated = bool(done)
84
+ truncated = False
85
+
86
+ # [关键修改] 应用惩罚
87
+ # 此时 reward 包含原本的稀疏奖励 (0 或 1) 加上每步惩罚
88
+ reward = float(reward) + self.step_penalty
89
+
90
+ return obs, reward, terminated, truncated, info or {}
91
+
92
+ def render(self):
93
+ return self._env.render()
94
+
95
+ def close(self):
96
+ self._env.close()
97
+
98
+
99
+ @dataclass
100
+ class Args:
101
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
102
+ seed: int = 1
103
+ torch_deterministic: bool = True
104
+ cuda: bool = True
105
+ track: bool = True
106
+ wandb_project_name: str = "cleanRL"
107
+ wandb_entity: str | None = None
108
+ capture_video: bool = False
109
+
110
+ # Algorithm
111
+ env_id: str = "RubiksCube2x2DQN"
112
+ total_timesteps: int = 400_000
113
+ learning_rate: float = 2.5e-4
114
+ gamma: float = 0.99
115
+ batch_size: int = 128
116
+ buffer_size: int = 200_000
117
+ target_network_frequency: int = 4000
118
+ train_frequency: int = 4
119
+ learning_starts: int = 5000
120
+
121
+ # Epsilon-greedy
122
+ start_e: float = 1.0
123
+ end_e: float = 0.05
124
+ exploration_fraction: float = 0.2
125
+
126
+ # Model size
127
+ hidden_size: int = 256
128
+
129
+ # Rubik specific
130
+ scramble_depth: int = 3 # 初始难度
131
+ max_steps_env: int = 20 # 硬性时间限制
132
+
133
+ # Eval
134
+ eval_splits: int = 2
135
+ eval_episodes: int = 4000
136
+
137
+
138
+ def make_env(idx, run_name, seed, scramble_depth, max_steps_env, capture_video=False):
139
+ def thunk():
140
+ # [关键修改] 内部 max_steps 设为 1000,防止 env 内部发出 done=True
141
+ # 我们完全依赖外部 TimeLimit wrapper 来处理超时
142
+ config = RubiksCube2x2Config(scramble_depth=scramble_depth, max_steps=20, render_mode='text')
143
+ env = RubiksCube2x2Env(config)
144
+ env = RubiksCubeWrapper(env)
145
+ # 外部限制设为 20
146
+ env = gym.wrappers.TimeLimit(env, max_episode_steps=max_steps_env)
147
+ env = gym.wrappers.RecordEpisodeStatistics(env)
148
+ if capture_video and idx == 0:
149
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
150
+ return env
151
+ return thunk
152
+
153
+
154
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
155
+ torch.nn.init.orthogonal_(layer.weight, std)
156
+ torch.nn.init.constant_(layer.bias, bias_const)
157
+ return layer
158
+
159
+
160
+ class QNetwork(nn.Module):
161
+ def __init__(self, obs_dim: int, act_dim: int, hidden: int):
162
+ super().__init__()
163
+ self.net = nn.Sequential(
164
+ layer_init(nn.Linear(obs_dim, hidden)),
165
+ nn.ReLU(),
166
+ layer_init(nn.Linear(hidden, hidden)),
167
+ nn.ReLU(),
168
+ layer_init(nn.Linear(hidden, act_dim), std=0.01),
169
+ )
170
+
171
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
172
+ return self.net(x)
173
+
174
+
175
+ class ReplayBuffer:
176
+ def __init__(self, capacity: int, obs_shape: Tuple[int, ...]):
177
+ self.capacity = capacity
178
+ self.ptr = 0
179
+ self.full = False
180
+ self.obs_buf = np.zeros((capacity,) + obs_shape, dtype=np.float32)
181
+ self.next_obs_buf = np.zeros((capacity,) + obs_shape, dtype=np.float32)
182
+ self.act_buf = np.zeros((capacity,), dtype=np.int64)
183
+ self.rew_buf = np.zeros((capacity,), dtype=np.float32)
184
+ self.done_buf = np.zeros((capacity,), dtype=np.float32)
185
+
186
+ def add(self, obs: np.ndarray, act: int, rew: float, done: bool, next_obs: np.ndarray):
187
+ i = self.ptr
188
+ self.obs_buf[i] = obs
189
+ self.next_obs_buf[i] = next_obs
190
+ self.act_buf[i] = act
191
+ self.rew_buf[i] = rew
192
+ self.done_buf[i] = 1.0 if done else 0.0
193
+ self.ptr = (self.ptr + 1) % self.capacity
194
+ if self.ptr == 0:
195
+ self.full = True
196
+
197
+ def can_sample(self, batch_size: int) -> bool:
198
+ return (self.capacity if self.full else self.ptr) >= batch_size
199
+
200
+ def sample(self, batch_size: int):
201
+ size = self.capacity if self.full else self.ptr
202
+ idxs = np.random.randint(0, size, size=batch_size)
203
+ return (
204
+ self.obs_buf[idxs],
205
+ self.act_buf[idxs],
206
+ self.rew_buf[idxs],
207
+ self.done_buf[idxs],
208
+ self.next_obs_buf[idxs],
209
+ )
210
+
211
+
212
+ if __name__ == "__main__":
213
+ args = tyro.cli(Args)
214
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
215
+
216
+ if args.track:
217
+ import wandb
218
+ wandb.init(
219
+ project=args.wandb_project_name,
220
+ entity=args.wandb_entity,
221
+ config=vars(args),
222
+ name=run_name,
223
+ monitor_gym=True,
224
+ save_code=True,
225
+ )
226
+ try:
227
+ wandb.define_metric("global_step")
228
+ for prefix in ["train/*", "rollout/*", "eval/*", "losses/*", "charts/*", "perf/*"]:
229
+ wandb.define_metric(prefix, step_metric="global_step")
230
+ except Exception:
231
+ pass
232
+
233
+ random.seed(args.seed)
234
+ np.random.seed(args.seed)
235
+ torch.manual_seed(args.seed)
236
+ torch.backends.cudnn.deterministic = args.torch_deterministic
237
+
238
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
239
+
240
+ env = make_env(0, run_name, args.seed, args.scramble_depth, args.max_steps_env, args.capture_video)()
241
+ obs_shape = env.observation_space.shape
242
+ act_dim = env.action_space.n
243
+
244
+ policy_net = QNetwork(int(np.prod(obs_shape)), act_dim, args.hidden_size).to(device)
245
+ target_net = QNetwork(int(np.prod(obs_shape)), act_dim, args.hidden_size).to(device)
246
+ target_net.load_state_dict(policy_net.state_dict())
247
+ target_net.eval()
248
+
249
+ optimizer = optim.Adam(policy_net.parameters(), lr=args.learning_rate)
250
+ criterion = nn.SmoothL1Loss()
251
+
252
+ rb = ReplayBuffer(args.buffer_size, obs_shape)
253
+
254
+ exploration_steps = max(1, int(args.exploration_fraction * args.total_timesteps))
255
+ epsilon_by_step = lambda t: args.end_e + (args.start_e - args.end_e) * max(0.0, (exploration_steps - t) / exploration_steps)
256
+
257
+ # 评估函数
258
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes, step_tag):
259
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
260
+ out_dir.mkdir(parents=True, exist_ok=True)
261
+ out_path = out_dir / "trajectories.jsonl"
262
+ env_eval = make_env_fn()
263
+ collected = 0
264
+ summary_returns = []
265
+ summary_success = []
266
+ with out_path.open("w") as f:
267
+ while collected < n_episodes:
268
+ state, _ = env_eval.reset(seed=args.seed + 100000 + collected)
269
+ traj_states = [np.asarray(state).tolist()]
270
+ traj_actions = []
271
+ traj_rewards = []
272
+ traj_dones = []
273
+ traj_success = []
274
+ done = False
275
+ step_count = 0
276
+ max_eval_steps = getattr(env_eval, '_max_episode_steps', None) or int(args.max_steps_env)
277
+ while not done:
278
+ with torch.no_grad():
279
+ q = agent_model(torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0))
280
+ action = int(torch.argmax(q, dim=1).item())
281
+ next_state, reward, terminated, truncated, info = env_eval.step(action)
282
+
283
+ traj_actions.append(int(action))
284
+ traj_rewards.append(float(reward))
285
+ step_count += 1
286
+ d = bool(terminated) or bool(truncated) or (step_count >= max_eval_steps)
287
+ traj_dones.append(d)
288
+ traj_success.append(bool((info or {}).get('success', False)))
289
+ state = next_state
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
+ # 主训练循环
322
+ global_step = 0
323
+ start_time = time.time()
324
+
325
+ obs, _ = env.reset(seed=args.seed)
326
+ ep_return = 0.0
327
+ ep_len = 0
328
+ ep_success_window: List[float] = []
329
+
330
+ eval_every_steps = max(1, args.total_timesteps // args.eval_splits)
331
+
332
+ while global_step < args.total_timesteps:
333
+ epsilon = epsilon_by_step(global_step)
334
+ if np.random.rand() < epsilon or global_step < args.learning_starts:
335
+ action = env.action_space.sample()
336
+ else:
337
+ with torch.no_grad():
338
+ q_values = policy_net(torch.tensor(obs, dtype=torch.float32, device=device).unsqueeze(0))
339
+ action = int(torch.argmax(q_values, dim=1).item())
340
+
341
+ next_obs, reward, terminated, truncated, info = env.step(action)
342
+
343
+ # 判断是否需要 Reset (任何结束都 Reset)
344
+ real_done = bool(terminated) or bool(truncated)
345
+
346
+ # [核心逻辑]
347
+ # 1. 即使是 truncated (超时),done 也记为 False,以便进行 bootstrap (计算未来价值)
348
+ # 2. 只有 terminated (真正解开了),done 才记为 True
349
+ # 3. Step Penalty 已经包含在 reward 中,DQN 会学到"为了避免扣分,必须在未来几步内解决"
350
+ rb.add(
351
+ obs.astype(np.float32),
352
+ int(action),
353
+ float(reward),
354
+ bool(terminated), # 注意:只用 terminated
355
+ next_obs.astype(np.float32)
356
+ )
357
+
358
+ obs = next_obs
359
+ ep_return += float(reward)
360
+ ep_len += 1
361
+ global_step += 1
362
+
363
+ # 训练过程
364
+ if rb.can_sample(args.batch_size) and (global_step % args.train_frequency == 0) and (global_step > args.learning_starts):
365
+ batch_obs, batch_act, batch_rew, batch_done, batch_next_obs = rb.sample(args.batch_size)
366
+ b_obs = torch.tensor(batch_obs, dtype=torch.float32, device=device)
367
+ b_act = torch.tensor(batch_act, dtype=torch.int64, device=device)
368
+ b_rew = torch.tensor(batch_rew, dtype=torch.float32, device=device)
369
+ b_done = torch.tensor(batch_done, dtype=torch.float32, device=device)
370
+ b_next_obs = torch.tensor(batch_next_obs, dtype=torch.float32, device=device)
371
+
372
+ with torch.no_grad():
373
+ next_q = target_net(b_next_obs).max(dim=1)[0]
374
+ target_q = b_rew + args.gamma * (1.0 - b_done) * next_q
375
+
376
+ current_q = policy_net(b_obs).gather(1, b_act.view(-1, 1)).squeeze(1)
377
+ loss = criterion(current_q, target_q)
378
+
379
+ optimizer.zero_grad()
380
+ loss.backward()
381
+ nn.utils.clip_grad_norm_(policy_net.parameters(), max_norm=10.0)
382
+ optimizer.step()
383
+
384
+ if args.track:
385
+ try:
386
+ import wandb
387
+ wandb.log({
388
+ "global_step": int(global_step),
389
+ "train/loss": float(loss.item()),
390
+ "charts/epsilon": float(epsilon),
391
+ "perf/SPS": int(global_step / (time.time() - start_time)),
392
+ "train/learning_rate": float(optimizer.param_groups[0]["lr"]),
393
+ }, step=global_step)
394
+ except Exception:
395
+ pass
396
+
397
+ # 结束时 Reset
398
+ if real_done:
399
+ succ = bool((info or {}).get('success', False))
400
+ ep_success_window.append(1.0 if succ else 0.0)
401
+ if len(ep_success_window) > 100:
402
+ ep_success_window.pop(0)
403
+ if args.track:
404
+ try:
405
+ import wandb
406
+ wandb.log({
407
+ "global_step": int(global_step),
408
+ "train/episodic_return": float(ep_return),
409
+ "train/episodic_length": int(ep_len),
410
+ "train/success": float(1.0 if succ else 0.0),
411
+ "train/success_rate_100": float(np.mean(ep_success_window)) if len(ep_success_window) >= 1 else None,
412
+ }, step=global_step)
413
+ except Exception:
414
+ pass
415
+ obs, _ = env.reset()
416
+ ep_return, ep_len = 0.0, 0
417
+
418
+ # 更新目标网络
419
+ if global_step % args.target_network_frequency == 0:
420
+ target_net.load_state_dict(policy_net.state_dict())
421
+
422
+ # 打印日志
423
+ if global_step % 1000 == 0:
424
+ sps = int(global_step / (time.time() - start_time))
425
+ sr100 = float(np.mean(ep_success_window)) if len(ep_success_window) > 0 else 0.0
426
+ print(f"Step {global_step} | SPS: {sps} | Epsilon: {epsilon:.3f} | SR@100: {sr100:.3f}")
427
+
428
+ # 评估
429
+ if global_step == 1 or (global_step % eval_every_steps == 0):
430
+ try:
431
+ def eval_thunk():
432
+ # 评估环境也同样设置:内部1000,外部20
433
+ return make_env(0, run_name, args.seed + 9999, args.scramble_depth, args.max_steps_env, False)()
434
+ collect_eval_trajectories(policy_net, eval_thunk, n_episodes=args.eval_episodes, step_tag=global_step)
435
+ if args.track:
436
+ try:
437
+ import wandb
438
+ mpath = Path(f"runs/{run_name}/trajectories/step_{global_step}/metrics.json")
439
+ if mpath.exists():
440
+ with mpath.open("r") as mf:
441
+ metrics = json.load(mf)
442
+ wandb.log({
443
+ "eval/success_rate": metrics.get("success_rate"),
444
+ "eval/avg_return": metrics.get("avg_return"),
445
+ "eval/std_return": metrics.get("std_return"),
446
+ "eval/episodes": metrics.get("episodes"),
447
+ }, step=global_step)
448
+ except Exception:
449
+ pass
450
+ print(f"Collected {args.eval_episodes} eval trajectories at step {global_step}")
451
+ except Exception as e:
452
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
453
+
454
+ env.close()
cleanrl/cleanrl/scout_dqn/dqn_sudoku.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DQN with Action Masking for RAGEN Sudoku (4x4, max_step=20)
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
+
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
+
17
+ import sys
18
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../'))
19
+
20
+ from ragen.env.sudoku.env import SudokuEnv
21
+ from ragen.env.sudoku.config import SudokuEnvConfig
22
+
23
+
24
+ class SudokuWrapper(gym.Env):
25
+ metadata = {"render_modes": ["rgb_array", "human", "ansi"]}
26
+
27
+ def __init__(self, env: SudokuEnv, grid_size: int):
28
+ super().__init__()
29
+ self._env = env
30
+ self._size = grid_size
31
+ self._val_dim = self._size + 1
32
+ self._act_n = self._size * self._size * self._size
33
+ self.action_space = gym.spaces.Discrete(self._act_n)
34
+ self.observation_space = gym.spaces.Dict({
35
+ "observation": gym.spaces.Box(low=0.0, high=1.0, shape=(self._size * self._size * self._val_dim,), dtype=np.float32),
36
+ "action_mask": gym.spaces.Box(low=0.0, high=1.0, shape=(self._act_n,), dtype=np.float32)
37
+ })
38
+
39
+ def _encode_obs(self, text_obs: str) -> Dict[str, np.ndarray]:
40
+ vals: List[int] = []
41
+ for line in text_obs.splitlines():
42
+ ls = line.strip()
43
+ if len(ls) == 0:
44
+ continue
45
+ if set(ls) <= {'-'}:
46
+ continue
47
+ tokens = [t for t in ls.split() if t != '|']
48
+ if len(tokens) == 0:
49
+ continue
50
+ for t in tokens:
51
+ if t == '.':
52
+ vals.append(0)
53
+ else:
54
+ try:
55
+ v = int(t)
56
+ except ValueError:
57
+ v = 0
58
+ vals.append(v)
59
+ target = self._size * self._size
60
+ if len(vals) < target:
61
+ vals.extend([0] * (target - len(vals)))
62
+ if len(vals) > target:
63
+ vals = vals[:target]
64
+ grid = np.zeros((target, self._val_dim), dtype=np.float32)
65
+ mask = np.zeros(self._act_n, dtype=np.float32)
66
+ for i, v in enumerate(vals):
67
+ v_clamped = int(v)
68
+ if v_clamped < 0 or v_clamped > self._size:
69
+ v_clamped = 0
70
+ grid[i, v_clamped] = 1.0
71
+ if v_clamped != 0:
72
+ start_idx = i * self._size
73
+ end_idx = start_idx + self._size
74
+ mask[start_idx:end_idx] = 0.0
75
+ cur = np.array(vals, dtype=np.int64).reshape(self._size, self._size)
76
+ box = int(np.sqrt(self._size))
77
+ for i, v in enumerate(vals):
78
+ if int(v) == 0:
79
+ r = i // self._size
80
+ c = i % self._size
81
+ row_vals = set(cur[r, :].tolist())
82
+ col_vals = set(cur[:, c].tolist())
83
+ br = (r // box) * box
84
+ bc = (c // box) * box
85
+ box_vals = set(cur[br:br + box, bc:bc + box].reshape(-1).tolist())
86
+ start_idx = i * self._size
87
+ for num in range(1, self._size + 1):
88
+ if (num not in row_vals) and (num not in col_vals) and (num not in box_vals):
89
+ mask[start_idx + (num - 1)] = 1.0
90
+ if mask.sum() == 0:
91
+ for i, v in enumerate(vals):
92
+ if int(v) == 0:
93
+ start_idx = i * self._size
94
+ end_idx = start_idx + self._size
95
+ mask[start_idx:end_idx] = 1.0
96
+ if mask.sum() == 0:
97
+ mask[:] = 1.0
98
+ return {
99
+ "observation": grid.reshape(-1),
100
+ "action_mask": mask,
101
+ }
102
+
103
+ @staticmethod
104
+ def _decode_action(action_id: int, grid_size: int) -> Tuple[int, int, int]:
105
+ g = grid_size
106
+ row = action_id // (g * g)
107
+ rem = action_id % (g * g)
108
+ col = rem // g
109
+ num = (rem % g) + 1
110
+ return row, col, num
111
+
112
+ def reset(self, *, seed: int | None = None, options: Dict[str, Any] | None = None):
113
+ text_obs = self._env.reset(seed=seed)
114
+ obs = self._encode_obs(text_obs)
115
+ return obs, {}
116
+
117
+ def step(self, action: int):
118
+ row, col, num = self._decode_action(int(action), self._size)
119
+ act_str = f"{row + 1},{col + 1},{num}"
120
+ text_obs, reward, done, info = self._env.step(act_str)
121
+ obs = self._encode_obs(text_obs)
122
+ terminated = bool(done)
123
+ truncated = False
124
+ return obs, float(reward), terminated, truncated, info or {}
125
+
126
+ def render(self):
127
+ return self._env.render()
128
+
129
+ def close(self):
130
+ self._env.close()
131
+
132
+
133
+ @dataclass
134
+ class Args:
135
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
136
+ seed: int = 1
137
+ torch_deterministic: bool = True
138
+ cuda: bool = True
139
+ track: bool = True
140
+ wandb_project_name: str = "cleanRL"
141
+ wandb_entity: str | None = None
142
+ capture_video: bool = False
143
+
144
+ # Algorithm
145
+ env_id: str = "SudokuDQN"
146
+ total_timesteps: int = 200000
147
+ learning_rate: float = 3e-4
148
+ gamma: float = 0.99
149
+ batch_size: int = 128
150
+ buffer_size: int = 400_000
151
+ target_network_frequency: int = 4000
152
+ train_frequency: int = 1
153
+ learning_starts: int = 10000
154
+
155
+ # Epsilon-greedy
156
+ start_e: float = 1.0
157
+ end_e: float = 0.05
158
+ exploration_fraction: float = 0.2
159
+
160
+ # Model size
161
+ hidden_size: int = 256
162
+
163
+ # Sudoku specific
164
+ grid_size: int = 4
165
+ difficulty: str = "easy"
166
+
167
+ # Eval
168
+ eval_splits: int = 2
169
+ eval_episodes: int = 4000
170
+
171
+
172
+ def make_env(idx, run_name, seed, grid_size, difficulty, capture_video=False):
173
+ def thunk():
174
+ config = SudokuEnvConfig(
175
+ grid_size=grid_size,
176
+ difficulty=difficulty,
177
+ render_mode='text',
178
+ render_format='simple',
179
+ )
180
+ env = SudokuEnv(config)
181
+ env = SudokuWrapper(env, grid_size)
182
+ max_steps = 20
183
+ env = gym.wrappers.TimeLimit(env, max_episode_steps=max_steps)
184
+ env = gym.wrappers.RecordEpisodeStatistics(env)
185
+ if capture_video and idx == 0:
186
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
187
+ return env
188
+ return thunk
189
+
190
+
191
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
192
+ torch.nn.init.orthogonal_(layer.weight, std)
193
+ torch.nn.init.constant_(layer.bias, bias_const)
194
+ return layer
195
+
196
+
197
+ class QNetwork(nn.Module):
198
+ def __init__(self, obs_dim: int, act_dim: int, hidden: int):
199
+ super().__init__()
200
+ self.net = nn.Sequential(
201
+ layer_init(nn.Linear(obs_dim, hidden)),
202
+ nn.ReLU(),
203
+ layer_init(nn.Linear(hidden, hidden)),
204
+ nn.ReLU(),
205
+ layer_init(nn.Linear(hidden, act_dim), std=0.01),
206
+ )
207
+
208
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
209
+ return self.net(x)
210
+
211
+
212
+ class ReplayBuffer:
213
+ def __init__(self, capacity: int, obs_dim: int):
214
+ self.capacity = capacity
215
+ self.ptr = 0
216
+ self.full = False
217
+ self.obs_buf = np.zeros((capacity, obs_dim), dtype=np.float32)
218
+ self.next_obs_buf = np.zeros((capacity, obs_dim), dtype=np.float32)
219
+ self.act_buf = np.zeros((capacity,), dtype=np.int64)
220
+ self.rew_buf = np.zeros((capacity,), dtype=np.float32)
221
+ self.done_buf = np.zeros((capacity,), dtype=np.float32)
222
+
223
+ def add(self, obs: np.ndarray, act: int, rew: float, done: bool, next_obs: np.ndarray):
224
+ i = self.ptr
225
+ self.obs_buf[i] = obs
226
+ self.next_obs_buf[i] = next_obs
227
+ self.act_buf[i] = act
228
+ self.rew_buf[i] = rew
229
+ self.done_buf[i] = 1.0 if done else 0.0
230
+ self.ptr = (self.ptr + 1) % self.capacity
231
+ if self.ptr == 0:
232
+ self.full = True
233
+
234
+ def can_sample(self, batch_size: int) -> bool:
235
+ return (self.capacity if self.full else self.ptr) >= batch_size
236
+
237
+ def sample(self, batch_size: int):
238
+ size = self.capacity if self.full else self.ptr
239
+ idxs = np.random.randint(0, size, size=batch_size)
240
+ return (
241
+ self.obs_buf[idxs],
242
+ self.act_buf[idxs],
243
+ self.rew_buf[idxs],
244
+ self.done_buf[idxs],
245
+ self.next_obs_buf[idxs],
246
+ )
247
+
248
+
249
+ if __name__ == "__main__":
250
+ args = tyro.cli(Args)
251
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
252
+
253
+ if args.track:
254
+ import wandb
255
+ wandb.init(
256
+ project=args.wandb_project_name,
257
+ entity=args.wandb_entity,
258
+ config=vars(args),
259
+ name=run_name,
260
+ monitor_gym=True,
261
+ save_code=True,
262
+ )
263
+ try:
264
+ wandb.define_metric("global_step")
265
+ for prefix in ["train/*", "rollout/*", "eval/*", "losses/*", "charts/*", "perf/*"]:
266
+ wandb.define_metric(prefix, step_metric="global_step")
267
+ except Exception:
268
+ pass
269
+
270
+ random.seed(args.seed)
271
+ np.random.seed(args.seed)
272
+ torch.manual_seed(args.seed)
273
+ torch.backends.cudnn.deterministic = args.torch_deterministic
274
+
275
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
276
+
277
+ env = make_env(0, run_name, args.seed, args.grid_size, args.difficulty, args.capture_video)()
278
+ # Flattened grid only from Dict observation
279
+ sample_obs, _ = env.reset(seed=args.seed)
280
+ obs_dim = int(np.prod(sample_obs["observation"].shape))
281
+ act_dim = env.action_space.n
282
+
283
+ policy_net = QNetwork(obs_dim, act_dim, args.hidden_size).to(device)
284
+ target_net = QNetwork(obs_dim, act_dim, args.hidden_size).to(device)
285
+ target_net.load_state_dict(policy_net.state_dict())
286
+ target_net.eval()
287
+
288
+ optimizer = optim.Adam(policy_net.parameters(), lr=args.learning_rate)
289
+ criterion = nn.SmoothL1Loss()
290
+
291
+ rb = ReplayBuffer(args.buffer_size, obs_dim)
292
+
293
+ exploration_steps = max(1, int(args.exploration_fraction * args.total_timesteps))
294
+ epsilon_by_step = lambda t: args.end_e + (args.start_e - args.end_e) * max(0.0, (exploration_steps - t) / exploration_steps)
295
+
296
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes, step_tag):
297
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
298
+ out_dir.mkdir(parents=True, exist_ok=True)
299
+ out_path = out_dir / "trajectories.jsonl"
300
+ env_eval = make_env_fn()
301
+ collected = 0
302
+ summary_returns = []
303
+ summary_success = []
304
+ with out_path.open("w") as f:
305
+ while collected < n_episodes:
306
+ obs_dict, _ = env_eval.reset(seed=args.seed + 100000 + collected)
307
+ state = obs_dict['observation']
308
+ mask = obs_dict['action_mask']
309
+ traj_states = [state.tolist()]
310
+ traj_actions = []
311
+ traj_rewards = []
312
+ traj_dones = []
313
+ traj_success = []
314
+ done = False
315
+ step_count = 0
316
+ max_eval_steps = getattr(env_eval, '_max_episode_steps', None) or int(args.grid_size * args.grid_size * 6)
317
+ while not done:
318
+ with torch.no_grad():
319
+ q = agent_model(torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0))
320
+ mask_t = torch.tensor(mask, dtype=torch.float32, device=device).unsqueeze(0)
321
+ masked_q = q + (mask_t - 1.0) * 1e8
322
+ action = int(torch.argmax(masked_q, dim=1).item())
323
+ next_obs_dict, reward, terminated, truncated, info = env_eval.step(action)
324
+ traj_actions.append(int(action))
325
+ traj_rewards.append(float(reward))
326
+ step_count += 1
327
+ d = bool(terminated) or bool(truncated) or (step_count >= max_eval_steps)
328
+ traj_dones.append(d)
329
+ traj_success.append(bool((info or {}).get('success', False)))
330
+ state = next_obs_dict['observation']
331
+ mask = next_obs_dict['action_mask']
332
+ traj_states.append(state.tolist())
333
+ done = d
334
+ ep_ret = float(sum(traj_rewards))
335
+ ep_succ = bool(any(traj_success))
336
+ record = {
337
+ "states": traj_states,
338
+ "actions": traj_actions,
339
+ "rewards": traj_rewards,
340
+ "dones": traj_dones,
341
+ "success": traj_success,
342
+ "episode_return": ep_ret,
343
+ "episode_success": ep_succ,
344
+ }
345
+ f.write(json.dumps(record) + "\n")
346
+ collected += 1
347
+ summary_returns.append(ep_ret)
348
+ summary_success.append(1.0 if ep_succ else 0.0)
349
+ env_eval.close()
350
+ try:
351
+ metrics = {
352
+ "global_step": int(step_tag),
353
+ "episodes": int(n_episodes),
354
+ "success_rate": float(np.mean(summary_success)) if len(summary_success) else 0.0,
355
+ "avg_return": float(np.mean(summary_returns)) if len(summary_returns) else 0.0,
356
+ "std_return": float(np.std(summary_returns)) if len(summary_returns) else 0.0,
357
+ }
358
+ with (out_dir / "metrics.json").open("w") as mf:
359
+ json.dump(metrics, mf)
360
+ except Exception as e:
361
+ print(f"Warning: failed to write eval metrics: {e}")
362
+
363
+ global_step = 0
364
+ start_time = time.time()
365
+
366
+ obs_dict, _ = env.reset(seed=args.seed)
367
+ obs = obs_dict['observation']
368
+ mask = obs_dict['action_mask']
369
+ ep_success_window: List[float] = []
370
+
371
+ eval_every_steps = max(1, args.total_timesteps // args.eval_splits)
372
+
373
+ while global_step < args.total_timesteps:
374
+ epsilon = epsilon_by_step(global_step)
375
+ with torch.no_grad():
376
+ q_values = policy_net(torch.tensor(obs, dtype=torch.float32, device=device).unsqueeze(0))
377
+ mask_t = torch.tensor(mask, dtype=torch.float32, device=device).unsqueeze(0)
378
+ masked_q = q_values + (mask_t - 1.0) * 1e8
379
+ greedy_action = int(torch.argmax(masked_q, dim=1).item())
380
+ if (np.random.rand() < epsilon) or (global_step < args.learning_starts):
381
+ valid = np.where(mask > 0.5)[0]
382
+ if len(valid) > 0:
383
+ action = int(np.random.choice(valid))
384
+ else:
385
+ action = int(np.random.randint(0, act_dim))
386
+ else:
387
+ action = greedy_action
388
+
389
+ next_obs_dict, reward, terminated, truncated, info = env.step(action)
390
+ done = bool(terminated) or bool(truncated)
391
+
392
+ next_obs = next_obs_dict['observation']
393
+ next_mask = next_obs_dict['action_mask']
394
+
395
+ rb.add(obs.astype(np.float32), int(action), float(reward), bool(done), next_obs.astype(np.float32))
396
+
397
+ obs = next_obs
398
+ mask = next_mask
399
+ global_step += 1
400
+
401
+ if done:
402
+ succ = bool((info or {}).get('success', False))
403
+ ep_success_window.append(1.0 if succ else 0.0)
404
+ if len(ep_success_window) > 100:
405
+ ep_success_window.pop(0)
406
+ if args.track:
407
+ try:
408
+ import wandb
409
+ wandb.log({
410
+ "global_step": int(global_step),
411
+ "rollout/success": float(1.0 if succ else 0.0),
412
+ "rollout/success_rate_100": float(np.mean(ep_success_window)) if len(ep_success_window) > 0 else None,
413
+ }, step=global_step)
414
+ except Exception:
415
+ pass
416
+ obs_dict, _ = env.reset()
417
+ obs = obs_dict['observation']
418
+ mask = obs_dict['action_mask']
419
+
420
+ if rb.can_sample(args.batch_size) and (global_step % args.train_frequency == 0) and (global_step > args.learning_starts):
421
+ batch_obs, batch_act, batch_rew, batch_done, batch_next_obs = rb.sample(args.batch_size)
422
+ b_obs = torch.tensor(batch_obs, dtype=torch.float32, device=device)
423
+ b_act = torch.tensor(batch_act, dtype=torch.int64, device=device)
424
+ b_rew = torch.tensor(batch_rew, dtype=torch.float32, device=device)
425
+ b_done = torch.tensor(batch_done, dtype=torch.float32, device=device)
426
+ b_next_obs = torch.tensor(batch_next_obs, dtype=torch.float32, device=device)
427
+
428
+ with torch.no_grad():
429
+ next_q = target_net(b_next_obs).max(dim=1)[0]
430
+ target_q = b_rew + args.gamma * (1.0 - b_done) * next_q
431
+
432
+ current_q = policy_net(b_obs).gather(1, b_act.view(-1, 1)).squeeze(1)
433
+ loss = criterion(current_q, target_q)
434
+
435
+ optimizer.zero_grad()
436
+ loss.backward()
437
+ nn.utils.clip_grad_norm_(policy_net.parameters(), max_norm=10.0)
438
+ optimizer.step()
439
+
440
+ if args.track:
441
+ try:
442
+ import wandb
443
+ wandb.log({
444
+ "global_step": int(global_step),
445
+ "train/loss": float(loss.item()),
446
+ "charts/epsilon": float(epsilon),
447
+ "perf/SPS": int(global_step / (time.time() - start_time)),
448
+ "train/learning_rate": float(optimizer.param_groups[0]["lr"]),
449
+ }, step=global_step)
450
+ except Exception:
451
+ pass
452
+
453
+ if global_step % args.target_network_frequency == 0:
454
+ target_net.load_state_dict(policy_net.state_dict())
455
+
456
+ if global_step % 1000 == 0:
457
+ sps = int(global_step / (time.time() - start_time))
458
+ sr100 = float(np.mean(ep_success_window)) if len(ep_success_window) > 0 else 0.0
459
+ print(f"Step {global_step} | SPS: {sps} | Epsilon: {epsilon:.3f} | SR@100: {sr100:.3f}")
460
+
461
+ if global_step == 1 or (global_step % eval_every_steps == 0):
462
+ try:
463
+ def eval_thunk():
464
+ return make_env(0, run_name, args.seed + 9999, args.grid_size, args.difficulty, False)()
465
+ collect_eval_trajectories(policy_net, eval_thunk, n_episodes=args.eval_episodes, step_tag=global_step)
466
+ if args.track:
467
+ try:
468
+ import wandb
469
+ mpath = Path(f"runs/{run_name}/trajectories/step_{global_step}/metrics.json")
470
+ if mpath.exists():
471
+ with mpath.open("r") as mf:
472
+ metrics = json.load(mf)
473
+ wandb.log({
474
+ "eval/success_rate": metrics.get("success_rate"),
475
+ "eval/avg_return": metrics.get("avg_return"),
476
+ "eval/std_return": metrics.get("std_return"),
477
+ "eval/episodes": metrics.get("episodes"),
478
+ }, step=global_step)
479
+ except Exception:
480
+ pass
481
+ print(f"Collected {args.eval_episodes} eval trajectories at step {global_step}")
482
+ except Exception as e:
483
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
484
+
485
+ env.close()
cleanrl/cleanrl/scout_dqn/noisy_dqn_sokoban.py ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NoisyNet DQN (dueling CNN) for RAGEN Sokoban, tuned for box=2
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
+ from ragen.env.sokoban.env import SokobanEnv
22
+ from ragen.env.sokoban.config import SokobanEnvConfig
23
+
24
+
25
+ class SokobanWrapper(gym.Env):
26
+ metadata = {"render_modes": ["rgb_array", "human", "ansi", "text"]}
27
+
28
+ def __init__(self, env: SokobanEnv):
29
+ super().__init__()
30
+ self._env = env
31
+ self._h = int(self._env.dim_room[0])
32
+ self._w = int(self._env.dim_room[1])
33
+ self._tokens = ['#', '_', 'O', '√', 'X', 'P', 'S']
34
+ self._token_to_idx = {t: i for i, t in enumerate(self._tokens)}
35
+ self._c = len(self._tokens)
36
+ self.observation_space = gym.spaces.Box(low=0.0, high=1.0, shape=(self._c, self._h, self._w), dtype=np.float32)
37
+ self.action_space = gym.spaces.Discrete(4)
38
+
39
+ def _encode_obs(self, text_obs: str) -> np.ndarray:
40
+ rows = text_obs.split('\n')
41
+ rows = [list(r) for r in rows if len(r) > 0]
42
+ h = len(rows)
43
+ w = len(rows[0]) if h > 0 else self._w
44
+ grid = np.zeros((self._c, self._h, self._w), dtype=np.float32)
45
+ for i in range(min(h, self._h)):
46
+ for j in range(min(w, self._w)):
47
+ ch = rows[i][j]
48
+ idx = self._token_to_idx.get(ch, 0)
49
+ grid[idx, i, j] = 1.0
50
+ return grid
51
+
52
+ def reset(self, *, seed: int | None = None, options: Dict[str, Any] | None = None):
53
+ text_obs = self._env.reset(seed=seed)
54
+ obs = self._encode_obs(text_obs)
55
+ return obs, {}
56
+
57
+ def step(self, action: int):
58
+ mapped = int(action) + 1 # env expects 1..4
59
+ text_obs, reward, done, info = self._env.step(mapped)
60
+ obs = self._encode_obs(text_obs)
61
+ terminated = bool(done)
62
+ truncated = False
63
+ return obs, float(reward), terminated, truncated, info or {}
64
+
65
+ def render(self):
66
+ return self._env.render()
67
+
68
+ def close(self):
69
+ self._env.close()
70
+
71
+
72
+ @dataclass
73
+ class Args:
74
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
75
+ seed: int = 1
76
+ torch_deterministic: bool = True
77
+ cuda: bool = True
78
+ track: bool = True
79
+ wandb_project_name: str = "cleanRL"
80
+ wandb_entity: str | None = None
81
+ capture_video: bool = False
82
+
83
+ # Algorithm
84
+ env_id: str = "SokobanNoisyDQN"
85
+ total_timesteps: int = 1_000_000
86
+ learning_rate: float = 2.5e-4
87
+ gamma: float = 0.99
88
+ batch_size: int = 128
89
+ buffer_size: int = 200_000
90
+ target_network_frequency: int = 8000
91
+ train_frequency: int = 4
92
+ learning_starts: int = 20_000
93
+
94
+ # Epsilon-greedy (used lightly for warmup)
95
+ start_e: float = 1.0
96
+ end_e: float = 0.1
97
+ exploration_fraction: float = 0.8
98
+
99
+ # Model
100
+ dueling: bool = True
101
+ reward_clip_abs: float | None = 1.0
102
+
103
+ # Eval config
104
+ eval_splits: int = 2
105
+ eval_episodes: int = 8000
106
+
107
+ # Sokoban env config (default for harder task)
108
+ grid_h: int = 6
109
+ grid_w: int = 6
110
+ num_boxes: int = 2
111
+ max_steps_env: int = 100
112
+ search_depth: int = 300
113
+
114
+
115
+ def make_env(run_name: str, seed: int, args: Args, capture_video: bool = False):
116
+ cfg = SokobanEnvConfig(
117
+ dim_room=(args.grid_h, args.grid_w),
118
+ max_steps=args.max_steps_env,
119
+ num_boxes=args.num_boxes,
120
+ search_depth=args.search_depth,
121
+ render_mode='text',
122
+ observation_format='grid',
123
+ )
124
+ env = SokobanEnv(cfg)
125
+ env = SokobanWrapper(env)
126
+ env = gym.wrappers.RecordEpisodeStatistics(env)
127
+ if capture_video:
128
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
129
+ return env
130
+
131
+
132
+ class NoisyLinear(nn.Module):
133
+ def __init__(self, in_features: int, out_features: int, std_init: float = 0.5):
134
+ super().__init__()
135
+ self.in_features = in_features
136
+ self.out_features = out_features
137
+ self.weight_mu = nn.Parameter(torch.empty(out_features, in_features))
138
+ self.weight_sigma = nn.Parameter(torch.empty(out_features, in_features))
139
+ self.register_buffer('weight_epsilon', torch.empty(out_features, in_features))
140
+ self.bias_mu = nn.Parameter(torch.empty(out_features))
141
+ self.bias_sigma = nn.Parameter(torch.empty(out_features))
142
+ self.register_buffer('bias_epsilon', torch.empty(out_features))
143
+ self.std_init = std_init / np.sqrt(in_features)
144
+ self.reset_parameters()
145
+ self.reset_noise()
146
+
147
+ def reset_parameters(self):
148
+ mu_range = 1 / np.sqrt(self.in_features)
149
+ self.weight_mu.data.uniform_(-mu_range, mu_range)
150
+ self.weight_sigma.data.fill_(self.std_init)
151
+ self.bias_mu.data.uniform_(-mu_range, mu_range)
152
+ self.bias_sigma.data.fill_(self.std_init)
153
+
154
+ def reset_noise(self):
155
+ epsilon_in = torch.randn(self.in_features, device=self.weight_mu.device)
156
+ epsilon_out = torch.randn(self.out_features, device=self.weight_mu.device)
157
+ self.weight_epsilon.copy_(epsilon_out.ger(epsilon_in))
158
+ self.bias_epsilon.copy_(epsilon_out)
159
+
160
+ def forward(self, x):
161
+ if self.training:
162
+ w = self.weight_mu + self.weight_sigma * self.weight_epsilon
163
+ b = self.bias_mu + self.bias_sigma * self.bias_epsilon
164
+ else:
165
+ w = self.weight_mu
166
+ b = self.bias_mu
167
+ return torch.nn.functional.linear(x, w, b)
168
+
169
+
170
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
171
+ if isinstance(layer, NoisyLinear):
172
+ nn.init.orthogonal_(layer.weight_mu, std)
173
+ nn.init.constant_(layer.bias_mu, bias_const)
174
+ layer.weight_sigma.data.fill_(layer.std_init)
175
+ layer.bias_sigma.data.fill_(layer.std_init)
176
+ else:
177
+ nn.init.orthogonal_(layer.weight, std)
178
+ nn.init.constant_(layer.bias, bias_const)
179
+ return layer
180
+
181
+
182
+ class QConvNoisy(nn.Module):
183
+ def __init__(self, obs_shape: Tuple[int, int, int], act_dim: int, dueling: bool = True):
184
+ super().__init__()
185
+ c, h, w = obs_shape
186
+ self.dueling = dueling
187
+ self._act_dim = act_dim
188
+ self.features = nn.Sequential(
189
+ layer_init(nn.Conv2d(c, 32, 3, 1, 1)),
190
+ nn.ReLU(),
191
+ layer_init(nn.Conv2d(32, 64, 3, 1, 1)),
192
+ nn.ReLU(),
193
+ layer_init(nn.Conv2d(64, 64, 3, 1, 1)),
194
+ nn.ReLU(),
195
+ nn.Flatten(),
196
+ )
197
+ fc_in = 64 * h * w
198
+ if self.dueling:
199
+ self.adv_head = nn.Sequential(
200
+ layer_init(NoisyLinear(fc_in, 512)),
201
+ nn.ReLU(),
202
+ layer_init(NoisyLinear(512, act_dim), std=0.01),
203
+ )
204
+ self.val_head = nn.Sequential(
205
+ layer_init(NoisyLinear(fc_in, 512)),
206
+ nn.ReLU(),
207
+ layer_init(NoisyLinear(512, 1), std=0.01),
208
+ )
209
+ else:
210
+ self.head = nn.Sequential(
211
+ layer_init(NoisyLinear(fc_in, 512)),
212
+ nn.ReLU(),
213
+ layer_init(NoisyLinear(512, act_dim), std=0.01),
214
+ )
215
+
216
+ def reset_noise(self):
217
+ for m in self.modules():
218
+ if isinstance(m, NoisyLinear):
219
+ m.reset_noise()
220
+
221
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
222
+ x = self.features(x)
223
+ if self.dueling:
224
+ adv = self.adv_head(x)
225
+ val = self.val_head(x)
226
+ q = val + adv - adv.mean(dim=1, keepdim=True)
227
+ return q
228
+ else:
229
+ q = self.head(x)
230
+ return q
231
+
232
+
233
+ class ReplayBuffer:
234
+ def __init__(self, capacity: int, obs_shape: Tuple[int, int, int]):
235
+ self.capacity = capacity
236
+ self.ptr = 0
237
+ self.full = False
238
+ self.obs_buf = np.zeros((capacity,) + obs_shape, dtype=np.float32)
239
+ self.next_obs_buf = np.zeros((capacity,) + obs_shape, dtype=np.float32)
240
+ self.act_buf = np.zeros((capacity,), dtype=np.int64)
241
+ self.rew_buf = np.zeros((capacity,), dtype=np.float32)
242
+ self.done_buf = np.zeros((capacity,), dtype=np.float32)
243
+
244
+ def add(self, obs: np.ndarray, act: int, rew: float, done: bool, next_obs: np.ndarray):
245
+ self.obs_buf[self.ptr] = obs
246
+ self.next_obs_buf[self.ptr] = next_obs
247
+ self.act_buf[self.ptr] = act
248
+ self.rew_buf[self.ptr] = rew
249
+ self.done_buf[self.ptr] = 1.0 if done else 0.0
250
+ self.ptr = (self.ptr + 1) % self.capacity
251
+ if self.ptr == 0:
252
+ self.full = True
253
+
254
+ def can_sample(self, batch_size: int) -> bool:
255
+ return (self.capacity if self.full else self.ptr) >= batch_size
256
+
257
+ def sample(self, batch_size: int):
258
+ size = self.capacity if self.full else self.ptr
259
+ idxs = np.random.randint(0, size, size=batch_size)
260
+ return (
261
+ self.obs_buf[idxs],
262
+ self.act_buf[idxs],
263
+ self.rew_buf[idxs],
264
+ self.done_buf[idxs],
265
+ self.next_obs_buf[idxs],
266
+ )
267
+
268
+
269
+ if __name__ == "__main__":
270
+ args = tyro.cli(Args)
271
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
272
+
273
+ if args.track:
274
+ import wandb
275
+ wandb.init(
276
+ project=args.wandb_project_name,
277
+ entity=args.wandb_entity,
278
+ config=vars(args),
279
+ name=run_name,
280
+ monitor_gym=True,
281
+ save_code=True,
282
+ )
283
+ try:
284
+ wandb.define_metric("global_step")
285
+ for prefix in ["train/*", "rollout/*", "eval/*", "losses/*", "charts/*", "perf/*"]:
286
+ wandb.define_metric(prefix, step_metric="global_step")
287
+ except Exception:
288
+ pass
289
+
290
+ # seeding
291
+ random.seed(args.seed)
292
+ np.random.seed(args.seed)
293
+ torch.manual_seed(args.seed)
294
+ torch.backends.cudnn.deterministic = args.torch_deterministic
295
+
296
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
297
+
298
+ # env
299
+ env = make_env(run_name, args.seed, args, args.capture_video)
300
+ obs_shape = env.observation_space.shape # (C,H,W)
301
+ act_dim = env.action_space.n
302
+
303
+ # networks
304
+ policy_net = QConvNoisy(obs_shape, act_dim, dueling=args.dueling).to(device)
305
+ target_net = QConvNoisy(obs_shape, act_dim, dueling=args.dueling).to(device)
306
+ target_net.load_state_dict(policy_net.state_dict())
307
+ target_net.eval()
308
+
309
+ optimizer = optim.Adam(policy_net.parameters(), lr=args.learning_rate)
310
+ criterion = nn.SmoothL1Loss()
311
+
312
+ rb = ReplayBuffer(args.buffer_size, obs_shape)
313
+
314
+ # periodic eval setup
315
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes: int, step_tag: int):
316
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
317
+ out_dir.mkdir(parents=True, exist_ok=True)
318
+ out_path = out_dir / "trajectories.jsonl"
319
+ env_eval = make_env_fn()
320
+ collected = 0
321
+ summary_returns = []
322
+ summary_success = []
323
+ with out_path.open("w") as f:
324
+ while collected < n_episodes:
325
+ state, _ = env_eval.reset(seed=args.seed + 100000 + collected)
326
+ traj_states = [np.asarray(state).tolist()]
327
+ traj_actions = []
328
+ traj_rewards = []
329
+ traj_dones = []
330
+ traj_success = []
331
+ done = False
332
+ step_count = 0
333
+ max_eval_steps = getattr(env_eval, '_max_episode_steps', None) or (args.grid_h * args.grid_w * 6)
334
+ while not done:
335
+ with torch.no_grad():
336
+ q = agent_model(torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0))
337
+ action = int(torch.argmax(q, dim=1).item())
338
+ next_state, reward, terminated, truncated, info = env_eval.step(action)
339
+ traj_actions.append(int(action))
340
+ traj_rewards.append(float(reward))
341
+ step_count += 1
342
+ d = bool(terminated) or bool(truncated) or (step_count >= max_eval_steps)
343
+ traj_dones.append(d)
344
+ traj_success.append(bool((info or {}).get('success', False)))
345
+ state = next_state
346
+ traj_states.append(np.asarray(state).tolist())
347
+ done = d
348
+ ep_ret = float(sum(traj_rewards))
349
+ ep_succ = bool(any(traj_success))
350
+ record = {
351
+ "states": traj_states,
352
+ "actions": traj_actions,
353
+ "rewards": traj_rewards,
354
+ "dones": traj_dones,
355
+ "success": traj_success,
356
+ "episode_return": ep_ret,
357
+ "episode_success": ep_succ,
358
+ }
359
+ f.write(json.dumps(record) + "\n")
360
+ collected += 1
361
+ summary_returns.append(ep_ret)
362
+ summary_success.append(1.0 if ep_succ else 0.0)
363
+ env_eval.close()
364
+ try:
365
+ metrics = {
366
+ "global_step": int(step_tag),
367
+ "episodes": int(n_episodes),
368
+ "success_rate": float(np.mean(summary_success)) if len(summary_success) else 0.0,
369
+ "avg_return": float(np.mean(summary_returns)) if len(summary_returns) else 0.0,
370
+ "std_return": float(np.std(summary_returns)) if len(summary_returns) else 0.0,
371
+ }
372
+ with (out_dir / "metrics.json").open("w") as mf:
373
+ json.dump(metrics, mf)
374
+ except Exception as e:
375
+ print(f"Warning: failed to write eval metrics: {e}")
376
+
377
+ # epsilon schedule (log only; noisy nets handle exploration)
378
+ exploration_steps = max(1, int(args.exploration_fraction * args.total_timesteps))
379
+ def epsilon_by_step(t: int):
380
+ return args.end_e + (args.start_e - args.end_e) * max(0.0, (exploration_steps - t) / exploration_steps)
381
+
382
+ # training loop
383
+ global_step = 0
384
+ start_time = time.time()
385
+
386
+ obs, _ = env.reset(seed=args.seed)
387
+ ep_return = 0.0
388
+ ep_len = 0
389
+ ep_success_window = deque(maxlen=100)
390
+
391
+ eval_every_steps = max(1, args.total_timesteps // args.eval_splits)
392
+
393
+ while global_step < args.total_timesteps:
394
+ epsilon = epsilon_by_step(global_step)
395
+ with torch.no_grad():
396
+ q_values = policy_net(torch.tensor(obs, dtype=torch.float32, device=device).unsqueeze(0))
397
+ action_greedy = int(torch.argmax(q_values, dim=1).item())
398
+ if (global_step < args.learning_starts) and (np.random.rand() < 0.5):
399
+ action = env.action_space.sample()
400
+ else:
401
+ action = action_greedy
402
+ next_obs, reward, terminated, truncated, info = env.step(action)
403
+ done = bool(terminated) or bool(truncated)
404
+
405
+ r = float(reward)
406
+ if args.reward_clip_abs is not None:
407
+ cap = float(args.reward_clip_abs)
408
+ r = max(-cap, min(cap, r))
409
+
410
+ rb.add(obs.astype(np.float32), action, r, done, next_obs.astype(np.float32))
411
+
412
+ obs = next_obs
413
+ ep_return += float(reward)
414
+ ep_len += 1
415
+ global_step += 1
416
+
417
+ # optimize
418
+ if (global_step > args.learning_starts) and rb.can_sample(args.batch_size) and (global_step % args.train_frequency == 0):
419
+ batch_obs, batch_act, batch_rew, batch_done, batch_next_obs = rb.sample(args.batch_size)
420
+ b_obs = torch.tensor(batch_obs, dtype=torch.float32, device=device)
421
+ b_act = torch.tensor(batch_act, dtype=torch.int64, device=device)
422
+ b_rew = torch.tensor(batch_rew, dtype=torch.float32, device=device)
423
+ b_done = torch.tensor(batch_done, dtype=torch.float32, device=device)
424
+ b_next_obs = torch.tensor(batch_next_obs, dtype=torch.float32, device=device)
425
+
426
+ with torch.no_grad():
427
+ next_actions = policy_net(b_next_obs).argmax(dim=1)
428
+ next_q = target_net(b_next_obs).gather(1, next_actions.view(-1, 1)).squeeze(1)
429
+ target_q = b_rew + args.gamma * (1.0 - b_done) * next_q
430
+
431
+ current_q = policy_net(b_obs).gather(1, b_act.view(-1, 1)).squeeze(1)
432
+ loss = criterion(current_q, target_q)
433
+
434
+ optimizer.zero_grad()
435
+ loss.backward()
436
+ nn.utils.clip_grad_norm_(policy_net.parameters(), max_norm=10.0)
437
+ optimizer.step()
438
+
439
+ # reset noisy parameters
440
+ policy_net.reset_noise()
441
+ target_net.reset_noise()
442
+
443
+ if args.track:
444
+ try:
445
+ import wandb
446
+ wandb.log({
447
+ "global_step": int(global_step),
448
+ "train/loss": float(loss.item()),
449
+ "charts/epsilon": float(epsilon),
450
+ "perf/SPS": int(global_step / (time.time() - start_time)),
451
+ }, step=global_step)
452
+ except Exception:
453
+ pass
454
+
455
+ # target network update
456
+ if global_step % args.target_network_frequency == 0:
457
+ target_net.load_state_dict(policy_net.state_dict())
458
+
459
+ if done:
460
+ succ = bool((info or {}).get('success', False))
461
+ ep_success_window.append(1.0 if succ else 0.0)
462
+ if args.track:
463
+ try:
464
+ import wandb
465
+ wandb.log({
466
+ "global_step": int(global_step),
467
+ "rollout/episodic_return": float(ep_return),
468
+ "rollout/episodic_length": int(ep_len),
469
+ "rollout/success": float(1.0 if succ else 0.0),
470
+ "rollout/success_rate_100": float(np.mean(ep_success_window)) if len(ep_success_window) > 0 else None,
471
+ }, step=global_step)
472
+ except Exception:
473
+ pass
474
+ obs, _ = env.reset()
475
+ ep_return, ep_len = 0.0, 0
476
+
477
+ # occasional print
478
+ if global_step % 1000 == 0:
479
+ sps = int(global_step / (time.time() - start_time))
480
+ sr100 = float(np.mean(ep_success_window)) if len(ep_success_window) > 0 else 0.0
481
+ print(f"Step {global_step} | SPS: {sps} | Epsilon: {epsilon:.3f} | SR@100: {sr100:.3f}")
482
+
483
+ # periodic evaluation and trajectory dump
484
+ if global_step==0 or (global_step % eval_every_steps == 0):
485
+ try:
486
+ def eval_thunk():
487
+ return make_env(run_name, args.seed + 9999, args, False)
488
+ collect_eval_trajectories(policy_net, eval_thunk, n_episodes=args.eval_episodes, step_tag=global_step)
489
+ if args.track:
490
+ try:
491
+ import wandb
492
+ mpath = Path(f"runs/{run_name}/trajectories/step_{global_step}/metrics.json")
493
+ if mpath.exists():
494
+ with mpath.open("r") as mf:
495
+ metrics = json.load(mf)
496
+ wandb.log({
497
+ "eval/success_rate": metrics.get("success_rate"),
498
+ "eval/avg_return": metrics.get("avg_return"),
499
+ "eval/std_return": metrics.get("std_return"),
500
+ "eval/episodes": metrics.get("episodes"),
501
+ }, step=global_step)
502
+ except Exception:
503
+ pass
504
+ print(f"Collected {args.eval_episodes} eval trajectories at step {global_step}")
505
+ except Exception as e:
506
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
507
+
508
+ # simple evaluation after training
509
+ def evaluate(n_episodes=200):
510
+ returns = []
511
+ successes = []
512
+ for i in range(n_episodes):
513
+ s, _ = env.reset(seed=args.seed + 100000 + i)
514
+ done = False
515
+ G = 0.0
516
+ while not done:
517
+ with torch.no_grad():
518
+ q = policy_net(torch.tensor(s, dtype=torch.float32, device=device).unsqueeze(0))
519
+ a = int(torch.argmax(q, dim=1).item())
520
+ s, r, term, trunc, info = env.step(a)
521
+ G += float(r)
522
+ done = bool(term) or bool(trunc)
523
+ successes.append(1.0 if bool((info or {}).get('success', False)) else 0.0)
524
+ returns.append(G)
525
+ return float(np.mean(returns)), float(np.std(returns)), float(np.mean(successes))
526
+
527
+ avg_ret, std_ret, succ_rate = evaluate(400)
528
+ if args.track:
529
+ try:
530
+ import wandb
531
+ wandb.log({
532
+ "global_step": int(global_step),
533
+ "eval/avg_return": float(avg_ret),
534
+ "eval/std_return": float(std_ret),
535
+ "eval/episodes": int(400),
536
+ "eval/success_rate": float(succ_rate),
537
+ }, step=global_step)
538
+ except Exception:
539
+ pass
540
+
541
+ env.close()
cleanrl/cleanrl/scout_dqn/ragen_wrappers.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gymnasium-compatible wrappers for RAGEN environments to enable traditional RL training.
3
+ These wrappers convert text-based observations to numerical representations suitable for MLP networks.
4
+ """
5
+ import gymnasium as gym
6
+ import numpy as np
7
+ from typing import Any, Dict, Tuple
8
+
9
+
10
+ class BanditWrapper(gym.Wrapper):
11
+ """
12
+ Wrapper for RAGEN Bandit that uses only observable text.
13
+ Converts text observations to a fixed-size one-hot hash vector.
14
+ Does not alter episode semantics and does not inspect env internals.
15
+ """
16
+ def __init__(self, env, feature_dim_per_name: int = 16):
17
+ super().__init__(env)
18
+ # Two name slots (first/second), each hashed to one-hot of size K
19
+ self.k = feature_dim_per_name
20
+ self.observation_space = gym.spaces.Box(low=0, high=1, shape=(2 * self.k,), dtype=np.float32)
21
+ self.action_space = gym.spaces.Discrete(2)
22
+
23
+ def _parse_names(self, text_obs: str):
24
+ """Extract the two arm names from the prompt text purely via regex/string ops."""
25
+ # Heuristic: look for the segment after "named " and split by " and "
26
+ try:
27
+ anchor = "named "
28
+ if anchor in text_obs:
29
+ segment = text_obs.split(anchor, 1)[1]
30
+ # Cut at newline if present
31
+ segment = segment.split("\n", 1)[0]
32
+ # Now split by " and " to get two names; also strip punctuation
33
+ parts = segment.split(" and ")
34
+ if len(parts) >= 2:
35
+ name_a = parts[0].strip().strip(' .!?,')
36
+ name_b = parts[1].strip().strip(' .!?,')
37
+ return name_a, name_b
38
+ except Exception:
39
+ pass
40
+ # Fallback: no names found
41
+ return "", ""
42
+
43
+ def _names_to_vector(self, name_a: str, name_b: str) -> np.ndarray:
44
+ vec = np.zeros(2 * self.k, dtype=np.float32)
45
+ idx_a = (hash(name_a) % self.k)
46
+ idx_b = (hash(name_b) % self.k)
47
+ vec[idx_a] = 1.0
48
+ vec[self.k + idx_b] = 1.0
49
+ return vec
50
+
51
+ def reset(self, **kwargs):
52
+ seed = kwargs.get('seed', None)
53
+ mode = kwargs.get('mode', None)
54
+ text_obs = self.env.reset(seed=seed, mode=mode)
55
+ name_a, name_b = self._parse_names(text_obs)
56
+ return self._names_to_vector(name_a, name_b), {}
57
+
58
+ def step(self, action):
59
+ ragen_action = int(action) + 1
60
+ text_obs, reward, done, info = self.env.step(ragen_action)
61
+ name_a, name_b = self._parse_names(text_obs)
62
+ terminated = bool(done)
63
+ truncated = False
64
+ return self._names_to_vector(name_a, name_b), reward, terminated, truncated, info
65
+
66
+
67
+ class FrozenLakeWrapper(gym.Wrapper):
68
+ """
69
+ Wrapper for RAGEN FrozenLake environment.
70
+ Converts grid-based text observations to numerical state representation.
71
+ """
72
+ def __init__(self, env):
73
+ super().__init__(env)
74
+ # Bootstrap an observation to determine grid size from text only
75
+ bootstrap_text = self.env.reset()
76
+ flat, _ = self._parse_observation_and_meta(bootstrap_text)
77
+ self.observation_space = gym.spaces.Box(low=0, high=1, shape=(flat.shape[0],), dtype=np.float32)
78
+ self.action_space = gym.spaces.Discrete(4)
79
+ # Serve the bootstrapped obs on first reset without calling env.reset again
80
+ self._bootstrap_obs = flat
81
+ self._bootstrap_ready = True
82
+
83
+ def _parse_observation_and_meta(self, text_obs: str) -> Tuple[np.ndarray, Tuple[int, int]]:
84
+ """Parse text observation into numerical state (one-hot grid + player pos)."""
85
+ lines = text_obs.strip().split('\n')
86
+ grid = []
87
+ player_pos = None
88
+ rows = len(lines)
89
+ cols = max(len(line) for line in lines) if rows > 0 else 0
90
+ # Parse grid
91
+ for i, line in enumerate(lines):
92
+ row = []
93
+ for j, char in enumerate(line):
94
+ if char == 'P': # Player
95
+ row.append(0)
96
+ player_pos = (i, j)
97
+ elif char == '_': # Frozen
98
+ row.append(1)
99
+ elif char == 'O': # Hole
100
+ row.append(2)
101
+ elif char == 'G': # Goal
102
+ row.append(3)
103
+ elif char == 'X': # Player in hole
104
+ row.append(2)
105
+ player_pos = (i, j)
106
+ elif char == '√': # Player on goal
107
+ row.append(3)
108
+ player_pos = (i, j)
109
+ else:
110
+ row.append(1) # Default to frozen
111
+ grid.append(row)
112
+ # Pad ragged rows if needed
113
+ grid = np.array([r + [1] * (cols - len(r)) for r in grid], dtype=np.int32)
114
+ grid_size = (rows, cols)
115
+ # One-hot encode grid over 4 cell types
116
+ # One-hot encode grid
117
+ one_hot_grid = np.zeros((rows, cols, 4), dtype=np.float32)
118
+ for i in range(rows):
119
+ for j in range(cols):
120
+ cell_type = grid[i, j]
121
+ one_hot_grid[i, j, cell_type] = 1.0
122
+ # Flatten grid
123
+ flat_grid = one_hot_grid.flatten()
124
+ # Add normalized player position
125
+ if player_pos is None:
126
+ player_pos = (0, 0)
127
+ player_pos_norm = np.array([
128
+ 0.0 if rows <= 1 else player_pos[0] / max(1, rows - 1),
129
+ 0.0 if cols <= 1 else player_pos[1] / max(1, cols - 1),
130
+ ], dtype=np.float32)
131
+ flat = np.concatenate([flat_grid, player_pos_norm])
132
+ return flat, grid_size
133
+
134
+ def reset(self, **kwargs):
135
+ # Filter out 'options' parameter that gymnasium passes but RAGEN doesn't support
136
+ if self._bootstrap_ready:
137
+ # First call returns the bootstrapped observation to avoid double reset
138
+ self._bootstrap_ready = False
139
+ return self._bootstrap_obs.copy(), {}
140
+ seed = kwargs.get('seed', None)
141
+ mode = kwargs.get('mode', None)
142
+ text_obs = self.env.reset(seed=seed, mode=mode)
143
+ state, _ = self._parse_observation_and_meta(text_obs)
144
+ return state, {}
145
+
146
+ def step(self, action):
147
+ # Map action from 0,1,2,3 to 1,2,3,4 (RAGEN uses 1-indexed actions)
148
+ ragen_action = action + 1
149
+ text_obs, reward, done, info = self.env.step(ragen_action)
150
+ state, _ = self._parse_observation_and_meta(text_obs)
151
+
152
+ terminated = done
153
+ truncated = False
154
+
155
+ return state, reward, terminated, truncated, info
156
+
157
+
158
+ class SokobanWrapper(gym.Wrapper):
159
+ """
160
+ Wrapper for RAGEN Sokoban environment.
161
+ Converts grid-based text observations to numerical state representation.
162
+ Note: Does not inherit from gym.Wrapper due to old gym vs gymnasium compatibility.
163
+ """
164
+ def __init__(self, env):
165
+ super().__init__(env)
166
+ # Bootstrap an observation to determine room size from text only
167
+ bootstrap_text = self.env.reset()
168
+ flat, rows, cols = self._parse_observation_and_meta(bootstrap_text)
169
+ self.observation_space = gym.spaces.Box(low=0, high=1, shape=(flat.shape[0],), dtype=np.float32)
170
+ self.action_space = gym.spaces.Discrete(4)
171
+ self.metadata = getattr(env, 'metadata', {})
172
+ self._bootstrap_obs = flat
173
+ self._bootstrap_ready = True
174
+
175
+ def _parse_observation_and_meta(self, text_obs: str) -> Tuple[np.ndarray, int, int]:
176
+ """Parse text observation into numerical state and return dims."""
177
+ lines = text_obs.strip().split('\n')
178
+ grid = []
179
+ rows = len(lines)
180
+ cols = max(len(line) for line in lines) if rows > 0 else 0
181
+ # Mapping from characters to cell types
182
+ char_to_type = {
183
+ '#': 0, # wall
184
+ '_': 1, # empty
185
+ 'O': 2, # target
186
+ '√': 3, # box on target
187
+ 'X': 4, # box
188
+ 'P': 5, # player
189
+ 'S': 6, # player on target
190
+ }
191
+
192
+ for line in lines:
193
+ row = []
194
+ for char in line:
195
+ row.append(char_to_type.get(char, 1)) # Default to empty
196
+ grid.append(row)
197
+ # Pad ragged rows
198
+ grid = np.array([r + [1] * (cols - len(r)) for r in grid], dtype=np.int32)
199
+ # One-hot encode grid
200
+ one_hot_grid = np.zeros((rows, cols, 7), dtype=np.float32)
201
+ for i in range(rows):
202
+ for j in range(cols):
203
+ cell_type = grid[i, j]
204
+ one_hot_grid[i, j, cell_type] = 1.0
205
+ return one_hot_grid.flatten(), rows, cols
206
+
207
+ def reset(self, **kwargs):
208
+ if self._bootstrap_ready:
209
+ self._bootstrap_ready = False
210
+ return self._bootstrap_obs.copy(), {}
211
+ seed = kwargs.get('seed', None)
212
+ mode = kwargs.get('mode', None)
213
+ text_obs = self.env.reset(seed=seed, mode=mode)
214
+ state, _, _ = self._parse_observation_and_meta(text_obs)
215
+ return state, {}
216
+
217
+ def step(self, action):
218
+ # Map action from 0,1,2,3 to 1,2,3,4 (RAGEN uses 1-indexed actions)
219
+ ragen_action = action + 1
220
+ text_obs, reward, done, info = self.env.step(ragen_action)
221
+ state, _, _ = self._parse_observation_and_meta(text_obs)
222
+
223
+ terminated = done
224
+ truncated = False
225
+
226
+ return state, reward, terminated, truncated, info
227
+
228
+ def close(self):
229
+ if hasattr(self.env, 'close'):
230
+ self.env.close()
231
+
232
+ def render(self):
233
+ if hasattr(self.env, 'render'):
234
+ return self.env.render()
235
+ return None
cleanrl/cleanrl/scout_ppo/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/scout_ppo/ppo_bandit_small.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ episode_successes = []
171
+
172
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes, step_tag):
173
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
174
+ out_dir.mkdir(parents=True, exist_ok=True)
175
+ out_path = out_dir / "trajectories.jsonl"
176
+ env = make_env_fn()
177
+ collected = 0
178
+ summary_returns = []
179
+ summary_success = []
180
+ with out_path.open("w") as f:
181
+ while collected < n_episodes:
182
+ state, _ = env.reset(seed=args.seed + 200000 + collected)
183
+ traj_rewards = []
184
+ done = False
185
+ while not done:
186
+ with torch.no_grad():
187
+ logits = agent_model.actor(torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0))
188
+ action = int(torch.argmax(logits, dim=1).item())
189
+ next_state, reward, terminated, truncated, info = env.step(action)
190
+ traj_rewards.append(float(reward))
191
+ done = bool(terminated) or bool(truncated)
192
+ state = next_state
193
+ ep_ret = float(sum(traj_rewards))
194
+ succ = False
195
+ try:
196
+ succ = bool((info or {}).get('success', False))
197
+ except Exception:
198
+ pass
199
+ f.write(json.dumps({"episode_return": ep_ret, "success": succ}) + "\n")
200
+ summary_returns.append(ep_ret)
201
+ summary_success.append(1.0 if succ else 0.0)
202
+ collected += 1
203
+ env.close()
204
+ try:
205
+ metrics = {
206
+ "global_step": int(step_tag),
207
+ "episodes": int(n_episodes),
208
+ "success_rate": float(np.mean(summary_success)) if len(summary_success) else 0.0,
209
+ "avg_return": float(np.mean(summary_returns)) if len(summary_returns) else 0.0,
210
+ "std_return": float(np.std(summary_returns)) if len(summary_returns) else 0.0,
211
+ }
212
+ with (out_dir / "metrics.json").open("w") as mf:
213
+ json.dump(metrics, mf)
214
+ except Exception as e:
215
+ print(f"Warning: failed to write eval metrics: {e}")
216
+
217
+ eval_splits = 2
218
+ eval_episodes = 4000
219
+ eval_every_iters = max(1, (args.total_timesteps // args.batch_size) // eval_splits)
220
+
221
+ for iteration in range(1, args.num_iterations + 1):
222
+ # Anneal LR
223
+ if args.anneal_lr:
224
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
225
+ lrnow = frac * args.learning_rate
226
+ optimizer.param_groups[0]["lr"] = lrnow
227
+
228
+ for step in range(0, args.num_steps):
229
+ global_step += args.num_envs
230
+ obs[step] = next_obs
231
+ dones[step] = next_done
232
+
233
+ with torch.no_grad():
234
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
235
+ values[step] = value.flatten()
236
+ actions[step] = action
237
+ logprobs[step] = logprob
238
+
239
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
240
+ next_done = np.logical_or(terminations, truncations)
241
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
242
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
243
+ # Episode stats logging: compute success and success_rate_100 if available
244
+ try:
245
+ mask = None
246
+ if isinstance(infos, dict):
247
+ if "_episode" in infos:
248
+ mask = np.asarray(infos["_episode"]).astype(bool)
249
+ elif "episode" in infos and isinstance(infos["episode"], dict) and "_l" in infos["episode"]:
250
+ mask = np.asarray(infos["episode"]["_l"]).astype(bool)
251
+ if mask is not None and np.any(mask):
252
+ r_arr = np.asarray(infos.get("episode", {}).get("r", np.zeros_like(mask, dtype=float)))
253
+ l_arr = np.asarray(infos.get("episode", {}).get("l", np.zeros_like(mask, dtype=int)))
254
+ if "success" in infos:
255
+ succ_arr = np.asarray(infos.get("success", np.zeros_like(mask, dtype=bool))).astype(float)
256
+ else:
257
+ try:
258
+ succ_arr = (np.asarray(r_arr) > 0).astype(float)
259
+ except Exception:
260
+ succ_arr = np.zeros_like(mask, dtype=float)
261
+ for s in np.asarray(succ_arr)[mask]:
262
+ episode_successes.append(float(s))
263
+ if args.track:
264
+ try:
265
+ import wandb
266
+ log_dict = {
267
+ "global_step": int(global_step),
268
+ "rollout/ep_rew_mean": float(np.mean(r_arr[mask])) if np.any(mask) else None,
269
+ "rollout/ep_len_mean": float(np.mean(l_arr[mask])) if np.any(mask) else None,
270
+ "rollout/success_rate": float(np.mean(succ_arr[mask])) if np.any(mask) else None,
271
+ }
272
+ if np.any(mask):
273
+ last_idx = np.where(mask)[0][-1]
274
+ log_dict.update({
275
+ "train/episodic_return": float(r_arr[last_idx]),
276
+ "train/episodic_length": int(l_arr[last_idx]),
277
+ "train/success": float(succ_arr[last_idx]),
278
+ "train/success_rate_100": float(np.mean(episode_successes[-100:])) if len(episode_successes) >= 1 else None,
279
+ })
280
+ wandb.log(log_dict, step=global_step)
281
+ except Exception:
282
+ pass
283
+ except Exception:
284
+ pass
285
+
286
+ # Since gamma=0 for bandit, GAE simplifies but we keep general code
287
+ with torch.no_grad():
288
+ next_value = agent.get_value(next_obs).reshape(1, -1)
289
+ advantages = torch.zeros_like(rewards).to(device)
290
+ lastgaelam = 0
291
+ for t in reversed(range(args.num_steps)):
292
+ if t == args.num_steps - 1:
293
+ nextnonterminal = 1.0 - next_done
294
+ nextvalues = next_value
295
+ else:
296
+ nextnonterminal = 1.0 - dones[t + 1]
297
+ nextvalues = values[t + 1]
298
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
299
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
300
+ returns = advantages + values
301
+
302
+ # flatten batch
303
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
304
+ b_logprobs = logprobs.reshape(-1)
305
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
306
+ b_advantages = advantages.reshape(-1)
307
+ b_returns = returns.reshape(-1)
308
+ b_values = values.reshape(-1)
309
+
310
+ # update
311
+ b_inds = np.arange(args.batch_size)
312
+ for epoch in range(args.update_epochs):
313
+ np.random.shuffle(b_inds)
314
+ for start in range(0, args.batch_size, args.minibatch_size):
315
+ end = start + args.minibatch_size
316
+ mb_inds = b_inds[start:end]
317
+
318
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
319
+ logratio = newlogprob - b_logprobs[mb_inds]
320
+ ratio = logratio.exp()
321
+
322
+ with torch.no_grad():
323
+ old_approx_kl = (-logratio).mean()
324
+ approx_kl = ((ratio - 1) - logratio).mean()
325
+
326
+ mb_advantages = b_advantages[mb_inds]
327
+ if args.norm_adv:
328
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
329
+
330
+ pg_loss1 = -mb_advantages * ratio
331
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
332
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
333
+
334
+ newvalue = newvalue.view(-1)
335
+ if args.clip_vloss:
336
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
337
+ v_clipped = b_values[mb_inds] + torch.clamp(
338
+ newvalue - b_values[mb_inds], -args.clip_coef, args.clip_coef,
339
+ )
340
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
341
+ v_loss = 0.5 * torch.max(v_loss_unclipped, v_loss_clipped).mean()
342
+ else:
343
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
344
+
345
+ entropy_loss = entropy.mean()
346
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
347
+
348
+ optimizer.zero_grad()
349
+ loss.backward()
350
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
351
+ optimizer.step()
352
+
353
+ if args.target_kl is not None and approx_kl > args.target_kl:
354
+ break
355
+
356
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
357
+ var_y = np.var(y_true)
358
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
359
+
360
+ sps = int(global_step / (time.time() - start_time))
361
+ progress = 100 * iteration / args.num_iterations
362
+ print(f"[{progress:5.1f}%] Iter {iteration:4d}/{args.num_iterations} | "
363
+ f"SPS: {sps:5d} | "
364
+ f"Reward: {rewards.mean().item():6.3f} | "
365
+ f"Value: {values.mean().item():6.3f} | "
366
+ f"VLoss: {v_loss.item():.4f} | "
367
+ f"PLoss: {pg_loss.item():.4f} | "
368
+ f"Ent: {entropy_loss.item():.4f}")
369
+ if args.track:
370
+ try:
371
+ import wandb
372
+ wandb.log({
373
+ "global_step": int(global_step),
374
+ "train/value_loss": float(v_loss.item()),
375
+ "train/policy_loss": float(pg_loss.item()),
376
+ "train/entropy": float(entropy_loss.item()),
377
+ "losses/explained_variance": float(explained_var),
378
+ "charts/avg_reward": float(rewards.mean().item()),
379
+ "charts/avg_value": float(values.mean().item()),
380
+ "perf/SPS": int(sps),
381
+ "train/learning_rate": float(optimizer.param_groups[0]["lr"]),
382
+ }, step=global_step)
383
+ except Exception:
384
+ pass
385
+
386
+ # periodic evaluation collection
387
+ if iteration % eval_every_iters == 0:
388
+ try:
389
+ eval_thunk = make_env(0, run_name, args.seed + 9999, args.feature_dim_per_name, False)
390
+ collect_eval_trajectories(agent, eval_thunk, n_episodes=eval_episodes, step_tag=global_step)
391
+ if args.track:
392
+ try:
393
+ import json as _json
394
+ from pathlib import Path as _Path
395
+ mpath = _Path(f"runs/{run_name}/trajectories/step_{global_step}/metrics.json")
396
+ if mpath.exists():
397
+ with mpath.open("r") as mf:
398
+ metrics = _json.load(mf)
399
+ wandb.log({
400
+ "eval/success_rate": metrics.get("success_rate"),
401
+ "eval/avg_return": metrics.get("avg_return"),
402
+ "eval/std_return": metrics.get("std_return"),
403
+ "eval/episodes": metrics.get("episodes"),
404
+ }, step=global_step)
405
+ except Exception:
406
+ pass
407
+ except Exception as e:
408
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
409
+
410
+ envs.close()
cleanrl/cleanrl/scout_ppo/ppo_sokoban.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import time
4
+ from dataclasses import dataclass
5
+ from typing import Dict, Any, Tuple
6
+ from pathlib import Path
7
+ import json
8
+
9
+ import gymnasium as gym
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.optim as optim
14
+ from torch.distributions.categorical import Categorical
15
+ import tyro
16
+
17
+ import sys
18
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../'))
19
+
20
+ from ragen.env.sokoban.env import SokobanEnv
21
+ from ragen.env.sokoban.config import SokobanEnvConfig
22
+
23
+
24
+ class SokobanWrapper(gym.Env):
25
+ metadata = {"render_modes": ["rgb_array", "human", "ansi", "text"]}
26
+
27
+ def __init__(self, env: SokobanEnv):
28
+ super().__init__()
29
+ self._env = env
30
+ self._h = int(self._env.dim_room[0])
31
+ self._w = int(self._env.dim_room[1])
32
+ self._tokens = ['#', '_', 'O', '√', 'X', 'P', 'S']
33
+ self._token_to_idx = {t: i for i, t in enumerate(self._tokens)}
34
+ self._c = len(self._tokens)
35
+ self.observation_space = gym.spaces.Box(low=0.0, high=1.0, shape=(self._c, self._h, self._w), dtype=np.float32)
36
+ self.action_space = gym.spaces.Discrete(4)
37
+
38
+ def _encode_obs(self, text_obs: str) -> np.ndarray:
39
+ rows = text_obs.split('\n')
40
+ rows = [list(r) for r in rows if len(r) > 0]
41
+ h = len(rows)
42
+ w = len(rows[0]) if h > 0 else self._w
43
+ grid = np.zeros((self._c, self._h, self._w), dtype=np.float32)
44
+ for i in range(min(h, self._h)):
45
+ for j in range(min(w, self._w)):
46
+ ch = rows[i][j]
47
+ idx = self._token_to_idx.get(ch, 0)
48
+ grid[idx, i, j] = 1.0
49
+ return grid
50
+
51
+ def reset(self, *, seed: int | None = None, options: Dict[str, Any] | None = None):
52
+ text_obs = self._env.reset(seed=seed)
53
+ obs = self._encode_obs(text_obs)
54
+ return obs, {}
55
+
56
+ def step(self, action: int):
57
+ mapped = int(action) + 1
58
+ text_obs, reward, done, info = self._env.step(mapped)
59
+ obs = self._encode_obs(text_obs)
60
+ terminated = bool(done)
61
+ truncated = False
62
+ return obs, float(reward), terminated, truncated, info or {}
63
+
64
+ def render(self):
65
+ return self._env.render()
66
+
67
+ def close(self):
68
+ self._env.close()
69
+
70
+
71
+ @dataclass
72
+ class Args:
73
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
74
+ seed: int = 1
75
+ torch_deterministic: bool = True
76
+ cuda: bool = True
77
+ track: bool = True
78
+ wandb_project_name: str = "cleanRL"
79
+ wandb_entity: str | None = None
80
+ capture_video: bool = False
81
+
82
+ env_id: str = "Sokoban"
83
+ total_timesteps: int = 10_000_000
84
+ learning_rate: float = 2.5e-4
85
+ num_envs: int = 8
86
+ num_steps: int = 128
87
+ anneal_lr: bool = True
88
+ gamma: float = 0.99
89
+ gae_lambda: float = 0.95
90
+ num_minibatches: int = 4
91
+ update_epochs: int = 4
92
+ norm_adv: bool = True
93
+ clip_coef: float = 0.2
94
+ clip_vloss: bool = True
95
+ ent_coef: float = 0.05
96
+ vf_coef: float = 0.5
97
+ max_grad_norm: float = 0.5
98
+ target_kl: float | None = None
99
+
100
+ grid_h: int = 6
101
+ grid_w: int = 6
102
+ num_boxes: int = 2
103
+ max_steps_env: int = 150
104
+ search_depth: int = 500
105
+
106
+ batch_size: int = 0
107
+ minibatch_size: int = 0
108
+ num_iterations: int = 0
109
+ # eval config to mirror reference script
110
+ eval_splits: int = 20
111
+ eval_episodes: int = 400
112
+
113
+
114
+ def make_env(idx: int, run_name: str, seed: int, args: Args, capture_video=False):
115
+ def thunk():
116
+ cfg = SokobanEnvConfig(
117
+ dim_room=(args.grid_h, args.grid_w),
118
+ max_steps=args.max_steps_env,
119
+ num_boxes=args.num_boxes,
120
+ search_depth=args.search_depth,
121
+ render_mode='text',
122
+ observation_format='grid',
123
+ )
124
+ env = SokobanEnv(cfg)
125
+ env = SokobanWrapper(env)
126
+ env = gym.wrappers.RecordEpisodeStatistics(env)
127
+ if capture_video and idx == 0:
128
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
129
+ return env
130
+ return thunk
131
+
132
+
133
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
134
+ nn.init.orthogonal_(layer.weight, std)
135
+ nn.init.constant_(layer.bias, bias_const)
136
+ return layer
137
+
138
+
139
+ class Agent(nn.Module):
140
+ def __init__(self, envs):
141
+ super().__init__()
142
+ c, h, w = envs.single_observation_space.shape
143
+ hidden = 1024
144
+ self.net = nn.Sequential(
145
+ layer_init(nn.Conv2d(c, 64, kernel_size=3, stride=1, padding=1)),
146
+ nn.ReLU(),
147
+ layer_init(nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)),
148
+ nn.ReLU(),
149
+ layer_init(nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1)),
150
+ nn.ReLU(),
151
+ nn.Flatten(),
152
+ layer_init(nn.Linear(128 * h * w, hidden)),
153
+ nn.ReLU(),
154
+ )
155
+ # twin critics (double value heads)
156
+ self.critic1 = layer_init(nn.Linear(hidden, 1), std=1.0)
157
+ self.critic2 = layer_init(nn.Linear(hidden, 1), std=1.0)
158
+ self.actor = layer_init(nn.Linear(hidden, envs.single_action_space.n), std=0.01)
159
+
160
+ def get_values(self, x):
161
+ x = self.net(x)
162
+ return self.critic1(x), self.critic2(x)
163
+
164
+ def get_action_and_value(self, x, action=None):
165
+ x = self.net(x)
166
+ logits = self.actor(x)
167
+ probs = Categorical(logits=logits)
168
+ if action is None:
169
+ action = probs.sample()
170
+ v1 = self.critic1(x)
171
+ v2 = self.critic2(x)
172
+ return action, probs.log_prob(action), probs.entropy(), v1, v2
173
+
174
+
175
+ if __name__ == "__main__":
176
+ args = tyro.cli(Args)
177
+ args.batch_size = int(args.num_envs * args.num_steps)
178
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
179
+ args.num_iterations = args.total_timesteps // args.batch_size
180
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
181
+
182
+ if args.track:
183
+ import wandb
184
+ wandb.init(
185
+ project=args.wandb_project_name,
186
+ entity=args.wandb_entity,
187
+ config=vars(args),
188
+ name=run_name,
189
+ monitor_gym=True,
190
+ save_code=True,
191
+ )
192
+ try:
193
+ wandb.define_metric("global_step")
194
+ for prefix in ["train/*", "rollout/*", "eval/*", "losses/*", "charts/*", "perf/*"]:
195
+ wandb.define_metric(prefix, step_metric="global_step")
196
+ except Exception:
197
+ pass
198
+
199
+ random.seed(args.seed)
200
+ np.random.seed(args.seed)
201
+ torch.manual_seed(args.seed)
202
+ torch.backends.cudnn.deterministic = args.torch_deterministic
203
+
204
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
205
+
206
+ envs = gym.vector.SyncVectorEnv([
207
+ make_env(i, run_name, args.seed, args, args.capture_video) for i in range(args.num_envs)
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
+ values1 = torch.zeros((args.num_steps, args.num_envs)).to(device)
220
+ values2 = torch.zeros((args.num_steps, args.num_envs)).to(device)
221
+
222
+ global_step = 0
223
+ start_time = time.time()
224
+ next_obs, _ = envs.reset(seed=args.seed)
225
+ next_obs = torch.tensor(next_obs, dtype=torch.float32).to(device)
226
+ next_done = torch.zeros(args.num_envs).to(device)
227
+
228
+ episode_returns = []
229
+ episode_steps = []
230
+ episode_successes = []
231
+
232
+ # Eval helper mirroring reference implementation
233
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes, step_tag):
234
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
235
+ out_dir.mkdir(parents=True, exist_ok=True)
236
+ out_path = out_dir / "trajectories.jsonl"
237
+ env = make_env_fn()
238
+ collected = 0
239
+ summary_returns = []
240
+ summary_success = []
241
+ with out_path.open("w") as f:
242
+ while collected < n_episodes:
243
+ state, _ = env.reset(seed=args.seed + 100000 + collected)
244
+ traj_states = [np.asarray(state).tolist()]
245
+ traj_actions = []
246
+ traj_rewards = []
247
+ traj_dones = []
248
+ traj_success = []
249
+ done = False
250
+ step_count = 0
251
+ # rely on env internal max steps; add a safety cap
252
+ max_eval_steps = getattr(env, '_max_episode_steps', None) or (args.grid_h * args.grid_w * 6)
253
+ while not done:
254
+ with torch.no_grad():
255
+ logits = agent_model.actor(agent_model.net(torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0)))
256
+ action = int(torch.argmax(logits, dim=1).item())
257
+ next_state, reward, terminated, truncated, info = env.step(action)
258
+ traj_actions.append(int(action))
259
+ traj_rewards.append(float(reward))
260
+ step_count += 1
261
+ d = bool(terminated) or bool(truncated) or (step_count >= max_eval_steps)
262
+ traj_dones.append(d)
263
+ traj_success.append(bool((info or {}).get('success', False)))
264
+ state = next_state
265
+ traj_states.append(np.asarray(state).tolist())
266
+ done = d
267
+ ep_ret = float(sum(traj_rewards))
268
+ ep_succ = bool(any(traj_success))
269
+ record = {
270
+ "states": traj_states,
271
+ "actions": traj_actions,
272
+ "rewards": traj_rewards,
273
+ "dones": traj_dones,
274
+ "success": traj_success,
275
+ "episode_return": ep_ret,
276
+ "episode_success": ep_succ,
277
+ }
278
+ f.write(json.dumps(record) + "\n")
279
+ collected += 1
280
+ summary_returns.append(ep_ret)
281
+ summary_success.append(1.0 if ep_succ else 0.0)
282
+ env.close()
283
+ try:
284
+ metrics = {
285
+ "global_step": int(step_tag),
286
+ "episodes": int(n_episodes),
287
+ "success_rate": float(np.mean(summary_success)) if len(summary_success) else 0.0,
288
+ "avg_return": float(np.mean(summary_returns)) if len(summary_returns) else 0.0,
289
+ "std_return": float(np.std(summary_returns)) if len(summary_returns) else 0.0,
290
+ }
291
+ with (out_dir / "metrics.json").open("w") as mf:
292
+ json.dump(metrics, mf)
293
+ except Exception as e:
294
+ print(f"Warning: failed to write eval metrics: {e}")
295
+
296
+ # Eval cadence identical to reference style
297
+ eval_every_iters = max(1, args.num_iterations // args.eval_splits)
298
+
299
+ for iteration in range(1, args.num_iterations + 1):
300
+ if args.anneal_lr:
301
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
302
+ lrnow = frac * args.learning_rate
303
+ optimizer.param_groups[0]["lr"] = lrnow
304
+
305
+ for step in range(0, args.num_steps):
306
+ global_step += args.num_envs
307
+ obs[step] = next_obs
308
+ dones[step] = next_done
309
+
310
+ with torch.no_grad():
311
+ action, logprob, _, v1, v2 = agent.get_action_and_value(next_obs)
312
+ values1[step] = v1.flatten()
313
+ values2[step] = v2.flatten()
314
+ actions[step] = action
315
+ logprobs[step] = logprob
316
+
317
+ next_obs_np, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
318
+ next_done = np.logical_or(terminations, truncations)
319
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
320
+ next_obs = torch.tensor(next_obs_np, dtype=torch.float32).to(device)
321
+ next_done = torch.tensor(next_done, dtype=torch.float32).to(device)
322
+
323
+ # Episode stats logging using Gymnasium vector env final_info
324
+ try:
325
+ if isinstance(infos, dict) and "final_info" in infos and infos["final_info"] is not None:
326
+ finals = infos["final_info"]
327
+ for fi in finals:
328
+ if fi is None:
329
+ continue
330
+ ep_r = float(fi.get("episode", {}).get("r", 0.0)) if isinstance(fi.get("episode"), dict) else float(fi.get("reward", 0.0))
331
+ ep_l = int(fi.get("episode", {}).get("l", 0)) if isinstance(fi.get("episode"), dict) else int(fi.get("length", 0))
332
+ # infer success from positive episodic return if the env doesn't set it
333
+ ep_succ = float(fi.get("success", 1.0 if ep_r > 0.0 else 0.0))
334
+ episode_returns.append(ep_r)
335
+ episode_steps.append(global_step)
336
+ episode_successes.append(ep_succ)
337
+ if args.track:
338
+ try:
339
+ import wandb
340
+ wandb.log({
341
+ "global_step": int(global_step),
342
+ # DQN-aligned episodic keys
343
+ "rollout/episodic_return": float(ep_r),
344
+ "rollout/episodic_length": int(ep_l),
345
+ "rollout/success": float(ep_succ),
346
+ "rollout/success_rate_100": float(np.mean(episode_successes[-100:])) if len(episode_successes) >= 100 else None,
347
+ # duplicate train-prefixed keys as in DQN
348
+ "train/episodic_return": float(ep_r),
349
+ "train/episodic_length": int(ep_l),
350
+ "train/success": float(ep_succ),
351
+ "train/success_rate_100": float(np.mean(episode_successes[-100:])) if len(episode_successes) >= 100 else None,
352
+ }, step=global_step)
353
+ except Exception:
354
+ pass
355
+ except Exception:
356
+ pass
357
+
358
+ with torch.no_grad():
359
+ nv1, nv2 = agent.get_values(next_obs)
360
+ next_value_min = torch.minimum(nv1, nv2).reshape(1, -1)
361
+ advantages = torch.zeros_like(rewards).to(device)
362
+ lastgaelam = 0
363
+ for t in reversed(range(args.num_steps)):
364
+ if t == args.num_steps - 1:
365
+ nextnonterminal = 1.0 - next_done
366
+ nextvalues_min = next_value_min
367
+ else:
368
+ nextnonterminal = 1.0 - dones[t + 1]
369
+ nextvalues_min = torch.minimum(values1[t + 1], values2[t + 1])
370
+ values_min_t = torch.minimum(values1[t], values2[t])
371
+ delta = rewards[t] + args.gamma * nextvalues_min * nextnonterminal - values_min_t
372
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
373
+ values_min = torch.minimum(values1, values2)
374
+ returns = advantages + values_min
375
+
376
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
377
+ b_logprobs = logprobs.reshape(-1)
378
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
379
+ b_advantages = advantages.reshape(-1)
380
+ b_returns = returns.reshape(-1)
381
+ b_values1 = values1.reshape(-1)
382
+ b_values2 = values2.reshape(-1)
383
+ b_values_min = torch.minimum(b_values1, b_values2)
384
+
385
+ b_inds = np.arange(args.batch_size)
386
+ clipfracs = []
387
+ for epoch in range(args.update_epochs):
388
+ np.random.shuffle(b_inds)
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
+
393
+ _, newlogprob, entropy, newvalue1, newvalue2 = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
394
+ logratio = newlogprob - b_logprobs[mb_inds]
395
+ ratio = logratio.exp()
396
+
397
+ with torch.no_grad():
398
+ old_approx_kl = (-logratio).mean()
399
+ approx_kl = ((ratio - 1) - logratio).mean()
400
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
401
+
402
+ mb_advantages = b_advantages[mb_inds]
403
+ if args.norm_adv:
404
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
405
+
406
+ pg_loss1 = -mb_advantages * ratio
407
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
408
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
409
+
410
+ newvalue1 = newvalue1.view(-1)
411
+ newvalue2 = newvalue2.view(-1)
412
+ if args.clip_vloss:
413
+ # head 1
414
+ v1_unclipped = (newvalue1 - b_returns[mb_inds]) ** 2
415
+ v1_clipped_old = b_values1[mb_inds]
416
+ v1_clipped = v1_clipped_old + torch.clamp(newvalue1 - v1_clipped_old, -args.clip_coef, args.clip_coef)
417
+ v1_loss = torch.max(v1_unclipped, (v1_clipped - b_returns[mb_inds]) ** 2).mean()
418
+ # head 2
419
+ v2_unclipped = (newvalue2 - b_returns[mb_inds]) ** 2
420
+ v2_clipped_old = b_values2[mb_inds]
421
+ v2_clipped = v2_clipped_old + torch.clamp(newvalue2 - v2_clipped_old, -args.clip_coef, args.clip_coef)
422
+ v2_loss = torch.max(v2_unclipped, (v2_clipped - b_returns[mb_inds]) ** 2).mean()
423
+ v_loss = 0.5 * (v1_loss + v2_loss)
424
+ else:
425
+ v1_loss = ((newvalue1 - b_returns[mb_inds]) ** 2).mean()
426
+ v2_loss = ((newvalue2 - b_returns[mb_inds]) ** 2).mean()
427
+ v_loss = 0.5 * (v1_loss + v2_loss)
428
+
429
+ entropy_loss = entropy.mean()
430
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
431
+
432
+ optimizer.zero_grad()
433
+ loss.backward()
434
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
435
+ optimizer.step()
436
+
437
+ if args.target_kl is not None and approx_kl > args.target_kl:
438
+ break
439
+
440
+ y_pred, y_true = b_values_min.detach().cpu().numpy(), b_returns.detach().cpu().numpy()
441
+ var_y = np.var(y_true)
442
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
443
+
444
+ sps = int(global_step / (time.time() - start_time))
445
+ progress = 100 * iteration / args.num_iterations
446
+ print(f"[{progress:5.1f}%] Iter {iteration:4d}/{args.num_iterations} | "
447
+ f"SPS: {sps:5d} | "
448
+ f"Reward: {rewards.mean().item():6.3f} | "
449
+ f"Value(min): {b_values_min.mean().item():6.3f} | "
450
+ f"VLoss: {v_loss.item():.4f} | "
451
+ f"PLoss: {pg_loss.item():.4f} | "
452
+ f"Ent: {entropy_loss.item():.4f}")
453
+ if args.track:
454
+ try:
455
+ import wandb
456
+ wandb.log({
457
+ "global_step": int(global_step),
458
+ "train/loss": float(loss.item()),
459
+ "charts/epsilon": None,
460
+ "perf/SPS": int(sps),
461
+ "train/value_loss": float(v_loss.item()),
462
+ "train/policy_loss": float(pg_loss.item()),
463
+ "train/entropy": float(entropy_loss.item()),
464
+ "losses/explained_variance": float(explained_var),
465
+ "charts/avg_reward": float(rewards.mean().item()),
466
+ "charts/avg_value": float(b_values_min.mean().item()),
467
+ "train/learning_rate": float(optimizer.param_groups[0]["lr"]),
468
+ # training success rate over all finished episodes so far
469
+ "train/success_rate": float(np.mean(episode_successes)) if len(episode_successes) > 0 else None,
470
+ # keep a short-horizon success rate to monitor recent progress
471
+ "train/success_rate_100": float(np.mean(episode_successes[-100:])) if len(episode_successes) > 0 else None,
472
+ }, step=global_step)
473
+ except Exception:
474
+ pass
475
+
476
+ # periodic evaluation collection and logging
477
+ if iteration % eval_every_iters == 0:
478
+ try:
479
+ def eval_thunk():
480
+ # reuse same config and wrapper as training, but single env
481
+ return make_env(0, run_name, args.seed + 9999, args, False)()
482
+ collect_eval_trajectories(agent, eval_thunk, n_episodes=args.eval_episodes, step_tag=global_step)
483
+ if args.track:
484
+ try:
485
+ mpath = Path(f"runs/{run_name}/trajectories/step_{global_step}/metrics.json")
486
+ if mpath.exists():
487
+ with mpath.open("r") as mf:
488
+ metrics = json.load(mf)
489
+ wandb.log({
490
+ "eval/success_rate": metrics.get("success_rate"),
491
+ "eval/avg_return": metrics.get("avg_return"),
492
+ "eval/std_return": metrics.get("std_return"),
493
+ "eval/episodes": metrics.get("episodes"),
494
+ }, step=global_step)
495
+ except Exception:
496
+ pass
497
+ print(f"Collected {args.eval_episodes} eval trajectories at global_step {global_step}")
498
+ except Exception as e:
499
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
500
+
501
+ envs.close()
cleanrl/cleanrl/scout_ppo/ppo_sudoku_actionmask.py ADDED
@@ -0,0 +1,588 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PPO with Action Masking for RAGEN Sudoku (4x4, max_step=20)
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
+
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
+ # 假设 ragen 库在两级目录之上,请根据实际情况调整
20
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../'))
21
+
22
+ from ragen.env.sudoku.env import SudokuEnv
23
+ from ragen.env.sudoku.config import SudokuEnvConfig
24
+
25
+
26
+ class SudokuWrapper(gym.Env):
27
+ """
28
+ Adapter to use ragen SudokuEnv with Gymnasium vector API.
29
+ Improvements: Returns a Dict observation with 'action_mask' to prevent
30
+ the agent from modifying cells that are already filled.
31
+ """
32
+ metadata = {"render_modes": ["rgb_array", "human", "ansi"]}
33
+
34
+ def __init__(self, env: SudokuEnv, grid_size: int):
35
+ super().__init__()
36
+ self._env = env
37
+ self._size = grid_size
38
+ # 0 denotes empty, 1..grid_size denote values
39
+ self._val_dim = self._size + 1
40
+
41
+ # Actions: (row, col, num) -> Flattened
42
+ self._act_n = self._size * self._size * self._size
43
+ self.action_space = gym.spaces.Discrete(self._act_n)
44
+
45
+ # Observation: Dict with mask
46
+ self.observation_space = gym.spaces.Dict({
47
+ "observation": gym.spaces.Box(low=0.0, high=1.0, shape=(self._size * self._size * self._val_dim,), dtype=np.float32),
48
+ "action_mask": gym.spaces.Box(low=0.0, high=1.0, shape=(self._act_n,), dtype=np.float32)
49
+ })
50
+
51
+ def _encode_obs(self, text_obs: str) -> Dict[str, np.ndarray]:
52
+ # Parse the 'simple' grid format
53
+ vals: List[int] = []
54
+ for line in text_obs.splitlines():
55
+ ls = line.strip()
56
+ if len(ls) == 0: continue
57
+ if set(ls) <= {'-'}: continue
58
+ tokens = [t for t in ls.split() if t != '|']
59
+ if len(tokens) == 0: continue
60
+ for t in tokens:
61
+ if t == '.': vals.append(0)
62
+ else:
63
+ try: v = int(t)
64
+ except ValueError: v = 0
65
+ vals.append(v)
66
+
67
+ target = self._size * self._size
68
+ if len(vals) < target: vals.extend([0] * (target - len(vals)))
69
+ if len(vals) > target: vals = vals[:target]
70
+
71
+ # One-hot encode grid
72
+ grid = np.zeros((target, self._val_dim), dtype=np.float32)
73
+ # Initialize mask (1.0 = valid, 0.0 = invalid)
74
+ mask = np.ones(self._act_n, dtype=np.float32)
75
+
76
+ for i, v in enumerate(vals):
77
+ v_clamped = int(v)
78
+ if v_clamped < 0 or v_clamped > self._size:
79
+ v_clamped = 0
80
+ grid[i, v_clamped] = 1.0
81
+
82
+ # If a cell is NOT empty (v_clamped != 0), mask all actions for this cell.
83
+ # Agent should not overwrite existing numbers.
84
+ if v_clamped != 0:
85
+ start_idx = i * self._size
86
+ end_idx = start_idx + self._size
87
+ mask[start_idx:end_idx] = 0.0
88
+
89
+ return {
90
+ "observation": grid.reshape(-1),
91
+ "action_mask": mask
92
+ }
93
+
94
+ @staticmethod
95
+ def _decode_action(action_id: int, grid_size: int) -> Tuple[int, int, int]:
96
+ g = grid_size
97
+ row = action_id // (g * g)
98
+ rem = action_id % (g * g)
99
+ col = rem // g
100
+ num = (rem % g) + 1
101
+ return row, col, num
102
+
103
+ def reset(self, *, seed: int | None = None, options: Dict[str, Any] | None = None):
104
+ text_obs = self._env.reset(seed=seed)
105
+ obs = self._encode_obs(text_obs)
106
+ return obs, {}
107
+
108
+ def step(self, action: int):
109
+ row, col, num = self._decode_action(int(action), self._size)
110
+ act_str = f"{row+1},{col+1},{num}"
111
+ text_obs, reward, done, info = self._env.step(act_str)
112
+ obs = self._encode_obs(text_obs)
113
+ terminated = bool(done)
114
+ truncated = False
115
+ return obs, float(reward), terminated, truncated, info or {}
116
+
117
+ def render(self):
118
+ return self._env.render()
119
+
120
+ def close(self):
121
+ self._env.close()
122
+
123
+
124
+ @dataclass
125
+ class Args:
126
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
127
+ seed: int = 1
128
+ torch_deterministic: bool = True
129
+ cuda: bool = True
130
+ track: bool = True
131
+ wandb_project_name: str = "cleanRL"
132
+ wandb_entity: str | None = None
133
+ capture_video: bool = False
134
+
135
+ # Algorithm
136
+ env_id: str = "Sudoku"
137
+ total_timesteps: int = 10000_000
138
+ learning_rate: float = 3e-4
139
+ num_envs: int = 8
140
+ num_steps: int = 128
141
+ anneal_lr: bool = True
142
+ gamma: float = 0.99
143
+ gae_lambda: float = 0.95
144
+ num_minibatches: int = 4
145
+ update_epochs: int = 4
146
+ norm_adv: bool = True
147
+ clip_coef: float = 0.2
148
+ clip_vloss: bool = True
149
+ ent_coef: float = 0.01
150
+ vf_coef: float = 0.5
151
+ max_grad_norm: float = 0.5
152
+ target_kl: float | None = None
153
+
154
+ # Sudoku specific
155
+ grid_size: int = 4
156
+ difficulty: str = "easy"
157
+
158
+ # runtime filled
159
+ batch_size: int = 0
160
+ minibatch_size: int = 0
161
+ num_iterations: int = 0
162
+
163
+ # eval
164
+ eval_splits: int = 2
165
+ eval_episodes: int = 4000
166
+
167
+
168
+ def make_env(idx, run_name, seed, grid_size, difficulty, capture_video=False):
169
+ def thunk():
170
+ config = SudokuEnvConfig(
171
+ grid_size=grid_size,
172
+ difficulty=difficulty,
173
+ render_mode='text',
174
+ render_format='simple',
175
+ )
176
+ env = SudokuEnv(config)
177
+ env = SudokuWrapper(env, grid_size)
178
+ # Use env's own max_steps default if available, otherwise a sane cap
179
+ # Keeping your request for strict step limit logic, although wrapper enforces logic
180
+ max_steps = 81
181
+ # max_steps = int(grid_size * grid_size * 6)
182
+ env = gym.wrappers.TimeLimit(env, max_episode_steps=max_steps)
183
+ env = gym.wrappers.RecordEpisodeStatistics(env)
184
+ if capture_video and idx == 0:
185
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
186
+ return env
187
+ return thunk
188
+
189
+
190
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
191
+ torch.nn.init.orthogonal_(layer.weight, std)
192
+ torch.nn.init.constant_(layer.bias, bias_const)
193
+ return layer
194
+
195
+
196
+ class Agent(nn.Module):
197
+ def __init__(self, envs):
198
+ super().__init__()
199
+ # Accessing the shape from the Dict space
200
+ obs_shape = int(np.array(envs.single_observation_space['observation'].shape).prod())
201
+ hidden = 256 # Increased hidden size slightly for better capacity
202
+
203
+ self.critic = nn.Sequential(
204
+ layer_init(nn.Linear(obs_shape, hidden)),
205
+ nn.Tanh(),
206
+ layer_init(nn.Linear(hidden, hidden)),
207
+ nn.Tanh(),
208
+ layer_init(nn.Linear(hidden, 1), std=1.0),
209
+ )
210
+ self.actor = nn.Sequential(
211
+ layer_init(nn.Linear(obs_shape, hidden)),
212
+ nn.Tanh(),
213
+ layer_init(nn.Linear(hidden, hidden)),
214
+ nn.Tanh(),
215
+ layer_init(nn.Linear(hidden, envs.single_action_space.n), std=0.01),
216
+ )
217
+
218
+ def get_value(self, x):
219
+ return self.critic(x)
220
+
221
+ def get_action_and_value(self, x, action=None, action_mask=None):
222
+ logits = self.actor(x)
223
+
224
+ # Apply Action Masking
225
+ if action_mask is not None:
226
+ # Set logits of invalid actions to a very large negative number
227
+ logits = logits + (action_mask - 1.0) * 1e8
228
+
229
+ probs = Categorical(logits=logits)
230
+ if action is None:
231
+ action = probs.sample()
232
+ return action, probs.log_prob(action), probs.entropy(), self.critic(x)
233
+
234
+
235
+ if __name__ == "__main__":
236
+ args = tyro.cli(Args)
237
+ args.batch_size = int(args.num_envs * args.num_steps)
238
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
239
+ args.num_iterations = args.total_timesteps // args.batch_size
240
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
241
+
242
+ if args.track:
243
+ import wandb
244
+ wandb.init(
245
+ project=args.wandb_project_name,
246
+ entity=args.wandb_entity,
247
+ config=vars(args),
248
+ name=run_name,
249
+ monitor_gym=True,
250
+ save_code=True,
251
+ )
252
+ try:
253
+ wandb.define_metric("global_step")
254
+ for prefix in ["train/*", "rollout/*", "eval/*", "losses/*", "charts/*", "perf/*"]:
255
+ wandb.define_metric(prefix, step_metric="global_step")
256
+ except Exception:
257
+ pass
258
+
259
+ # seeding
260
+ random.seed(args.seed)
261
+ np.random.seed(args.seed)
262
+ torch.manual_seed(args.seed)
263
+ torch.backends.cudnn.deterministic = args.torch_deterministic
264
+
265
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
266
+
267
+ # envs
268
+ envs = gym.vector.SyncVectorEnv([
269
+ make_env(i, run_name, args.seed, args.grid_size, args.difficulty, args.capture_video)
270
+ for i in range(args.num_envs)
271
+ ])
272
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete)
273
+
274
+ agent = Agent(envs).to(device)
275
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
276
+
277
+ # storage
278
+ # Note: obs storage now only stores the flattened grid part
279
+ obs_shape = envs.single_observation_space['observation'].shape
280
+ mask_shape = envs.single_observation_space['action_mask'].shape
281
+
282
+ obs = torch.zeros((args.num_steps, args.num_envs) + obs_shape).to(device)
283
+ masks = torch.zeros((args.num_steps, args.num_envs) + mask_shape).to(device) # Storage for masks
284
+
285
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
286
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
287
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
288
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
289
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
290
+
291
+ # start
292
+ global_step = 0
293
+ start_time = time.time()
294
+
295
+ # envs.reset() returns a Dict of stacked arrays
296
+ next_obs_dict, _ = envs.reset(seed=args.seed)
297
+ next_obs = torch.Tensor(next_obs_dict['observation']).to(device)
298
+ next_mask = torch.Tensor(next_obs_dict['action_mask']).to(device)
299
+ next_done = torch.zeros(args.num_envs).to(device)
300
+
301
+ episode_returns = []
302
+ episode_steps = []
303
+ episode_successes = []
304
+
305
+ # Eval helper
306
+ def collect_eval_trajectories(agent_model, make_env_fn, n_episodes, step_tag):
307
+ out_dir = Path(f"runs/{run_name}/trajectories/step_{step_tag}")
308
+ out_dir.mkdir(parents=True, exist_ok=True)
309
+ out_path = out_dir / "trajectories.jsonl"
310
+ env = make_env_fn()
311
+ collected = 0
312
+ summary_returns = []
313
+ summary_success = []
314
+ with out_path.open("w") as f:
315
+ while collected < n_episodes:
316
+ obs_dict, _ = env.reset(seed=args.seed + collected)
317
+ # Handle single env dict unpacking
318
+ state = obs_dict['observation']
319
+ mask = obs_dict['action_mask']
320
+
321
+ traj_states = [state.tolist()]
322
+ traj_actions = []
323
+ traj_rewards = []
324
+ traj_dones = []
325
+ traj_success = []
326
+ done = False
327
+ step_count = 0
328
+ max_eval_steps = getattr(env, '_max_episode_steps', None) or int(args.grid_size * args.grid_size * 6)
329
+
330
+ # Eval loop
331
+ current_obs = torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0)
332
+ current_mask = torch.tensor(mask, dtype=torch.float32, device=device).unsqueeze(0)
333
+
334
+ while not done:
335
+ with torch.no_grad():
336
+ # Pass mask to actor during eval
337
+ action, _, _, _ = agent_model.get_action_and_value(current_obs, action_mask=current_mask)
338
+ action_item = int(action.item())
339
+
340
+ next_obs_dict, reward, terminated, truncated, info = env.step(action_item)
341
+
342
+ traj_actions.append(action_item)
343
+ traj_rewards.append(float(reward))
344
+ step_count += 1
345
+ d = bool(terminated) or bool(truncated) or (step_count >= max_eval_steps)
346
+ traj_dones.append(d)
347
+ traj_success.append(bool(info.get('success', False)))
348
+
349
+ state = next_obs_dict['observation']
350
+ mask = next_obs_dict['action_mask']
351
+ current_obs = torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0)
352
+ current_mask = torch.tensor(mask, dtype=torch.float32, device=device).unsqueeze(0)
353
+
354
+ traj_states.append(state.tolist())
355
+ done = d
356
+
357
+ ep_ret = float(sum(traj_rewards))
358
+ ep_succ = bool(any(traj_success))
359
+ record = {
360
+ "states": traj_states,
361
+ "actions": traj_actions,
362
+ "rewards": traj_rewards,
363
+ "dones": traj_dones,
364
+ "success": traj_success,
365
+ "episode_return": ep_ret,
366
+ "episode_success": ep_succ,
367
+ }
368
+ f.write(json.dumps(record) + "\n")
369
+ collected += 1
370
+ summary_returns.append(ep_ret)
371
+ summary_success.append(1.0 if ep_succ else 0.0)
372
+ env.close()
373
+ try:
374
+ metrics = {
375
+ "global_step": int(step_tag),
376
+ "episodes": int(n_episodes),
377
+ "success_rate": float(np.mean(summary_success)) if len(summary_success) else 0.0,
378
+ "avg_return": float(np.mean(summary_returns)) if len(summary_returns) else 0.0,
379
+ "std_return": float(np.std(summary_returns)) if len(summary_returns) else 0.0,
380
+ }
381
+ with (out_dir / "metrics.json").open("w") as mf:
382
+ json.dump(metrics, mf)
383
+ except Exception as e:
384
+ print(f"Warning: failed to write eval metrics: {e}")
385
+
386
+ eval_every_iters = max(1, args.num_iterations // args.eval_splits)
387
+
388
+ # training loop
389
+ for iteration in range(1, args.num_iterations + 1):
390
+ if args.anneal_lr:
391
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
392
+ optimizer.param_groups[0]["lr"] = frac * args.learning_rate
393
+
394
+ for step in range(0, args.num_steps):
395
+ global_step += args.num_envs
396
+ obs[step] = next_obs
397
+ masks[step] = next_mask # Store mask
398
+ dones[step] = next_done
399
+
400
+ with torch.no_grad():
401
+ # PASS MASK HERE
402
+ action, logprob, _, value = agent.get_action_and_value(next_obs, action_mask=next_mask)
403
+ values[step] = value.flatten()
404
+ actions[step] = action
405
+ logprobs[step] = logprob
406
+
407
+ next_obs_dict, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
408
+ next_done = np.logical_or(terminations, truncations)
409
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
410
+
411
+ # Unpack dict again
412
+ next_obs = torch.Tensor(next_obs_dict['observation']).to(device)
413
+ next_mask = torch.Tensor(next_obs_dict['action_mask']).to(device)
414
+ next_done = torch.Tensor(next_done).to(device)
415
+
416
+ try:
417
+ mask = None
418
+ if isinstance(infos, dict):
419
+ if "_episode" in infos:
420
+ mask = np.asarray(infos["_episode"]).astype(bool)
421
+ elif "episode" in infos and isinstance(infos["episode"], dict) and "_l" in infos["episode"]:
422
+ mask = np.asarray(infos["episode"]["_l"]).astype(bool)
423
+ if mask is not None and np.any(mask):
424
+ r_arr = np.asarray(infos.get("episode", {}).get("r", np.zeros_like(mask, dtype=float)))
425
+ l_arr = np.asarray(infos.get("episode", {}).get("l", np.zeros_like(mask, dtype=int)))
426
+ succ_arr = np.asarray(infos.get("success", np.zeros_like(mask, dtype=bool))).astype(float)
427
+ for i in np.where(mask)[0]:
428
+ episode_returns.append(float(r_arr[i]))
429
+ episode_steps.append(global_step)
430
+ episode_successes.append(float(succ_arr[i]))
431
+ if args.track:
432
+ try:
433
+ import wandb
434
+ log_dict = {
435
+ "global_step": int(global_step),
436
+ "rollout/ep_rew_mean": float(np.mean(r_arr[mask])) if np.any(mask) else None,
437
+ "rollout/ep_len_mean": float(np.mean(l_arr[mask])) if np.any(mask) else None,
438
+ "rollout/success_rate": float(np.mean(succ_arr[mask])) if np.any(mask) else None,
439
+ }
440
+ if np.any(mask):
441
+ last_idx = np.where(mask)[0][-1]
442
+ log_dict.update({
443
+ "train/episodic_return": float(r_arr[last_idx]),
444
+ "train/episodic_length": int(l_arr[last_idx]),
445
+ "train/success": float(succ_arr[last_idx]),
446
+ "train/success_rate_100": float(np.mean(episode_successes[-100:])) if len(episode_successes) >= 100 else None,
447
+ })
448
+ wandb.log(log_dict, step=global_step)
449
+ except Exception:
450
+ pass
451
+ except Exception:
452
+ pass
453
+
454
+ # GAE
455
+ with torch.no_grad():
456
+ next_value = agent.get_value(next_obs).reshape(1, -1)
457
+ advantages = torch.zeros_like(rewards).to(device)
458
+ lastgaelam = 0
459
+ for t in reversed(range(args.num_steps)):
460
+ if t == args.num_steps - 1:
461
+ nextnonterminal = 1.0 - next_done
462
+ nextvalues = next_value
463
+ else:
464
+ nextnonterminal = 1.0 - dones[t + 1]
465
+ nextvalues = values[t + 1]
466
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
467
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
468
+ returns = advantages + values
469
+
470
+ # flatten batch
471
+ b_obs = obs.reshape((-1,) + obs_shape)
472
+ b_masks = masks.reshape((-1,) + mask_shape) # Flatten masks
473
+ b_logprobs = logprobs.reshape(-1)
474
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
475
+ b_advantages = advantages.reshape(-1)
476
+ b_returns = returns.reshape(-1)
477
+ b_values = values.reshape(-1)
478
+
479
+ # update
480
+ b_inds = np.arange(args.batch_size)
481
+ for epoch in range(args.update_epochs):
482
+ np.random.shuffle(b_inds)
483
+ for start in range(0, args.batch_size, args.minibatch_size):
484
+ end = start + args.minibatch_size
485
+ mb_inds = b_inds[start:end]
486
+
487
+ # PASS MASK HERE
488
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(
489
+ b_obs[mb_inds],
490
+ action=b_actions.long()[mb_inds],
491
+ action_mask=b_masks[mb_inds]
492
+ )
493
+
494
+ logratio = newlogprob - b_logprobs[mb_inds]
495
+ ratio = logratio.exp()
496
+
497
+ with torch.no_grad():
498
+ old_approx_kl = (-logratio).mean()
499
+ approx_kl = ((ratio - 1) - logratio).mean()
500
+
501
+ mb_advantages = b_advantages[mb_inds]
502
+ if args.norm_adv:
503
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
504
+
505
+ pg_loss1 = -mb_advantages * ratio
506
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
507
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
508
+
509
+ newvalue = newvalue.view(-1)
510
+ if args.clip_vloss:
511
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
512
+ v_clipped = b_values[mb_inds] + torch.clamp(
513
+ newvalue - b_values[mb_inds], -args.clip_coef, args.clip_coef,
514
+ )
515
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
516
+ v_loss = 0.5 * torch.max(v_loss_unclipped, v_loss_clipped).mean()
517
+ else:
518
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
519
+
520
+ entropy_loss = entropy.mean()
521
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
522
+
523
+ optimizer.zero_grad()
524
+ loss.backward()
525
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
526
+ optimizer.step()
527
+
528
+ if args.target_kl is not None and approx_kl > args.target_kl:
529
+ break
530
+
531
+ # logging
532
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
533
+ var_y = np.var(y_true)
534
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
535
+
536
+ sps = int(global_step / (time.time() - start_time))
537
+ progress = 100 * iteration / args.num_iterations
538
+ print(f"[{progress:5.1f}%] Iter {iteration:4d}/{args.num_iterations} | "
539
+ f"SPS: {sps:5d} | "
540
+ f"Reward: {rewards.mean().item():6.3f} | "
541
+ f"Val: {values.mean().item():6.3f} | "
542
+ f"VLoss: {v_loss.item():.4f} | "
543
+ f"PLoss: {pg_loss.item():.4f} | "
544
+ f"Ent: {entropy_loss.item():.4f}")
545
+ if args.track:
546
+ try:
547
+ import wandb
548
+ wandb.log({
549
+ "global_step": int(global_step),
550
+ "train/value_loss": float(v_loss.item()),
551
+ "train/policy_loss": float(pg_loss.item()),
552
+ "train/entropy": float(entropy_loss.item()),
553
+ "train/old_approx_kl": float(old_approx_kl.item()),
554
+ "train/approx_kl": float(approx_kl.item()),
555
+ "losses/explained_variance": float(explained_var),
556
+ "charts/avg_reward": float(rewards.mean().item()),
557
+ "charts/avg_value": float(values.mean().item()),
558
+ "perf/SPS": int(sps),
559
+ "train/learning_rate": float(optimizer.param_groups[0]["lr"]),
560
+ }, step=global_step)
561
+ except Exception:
562
+ pass
563
+
564
+ if iteration % eval_every_iters == 0:
565
+ try:
566
+ eval_thunk = make_env(0, run_name, args.seed + 9999, args.grid_size, args.difficulty, False)
567
+ collect_eval_trajectories(agent, eval_thunk, n_episodes=args.eval_episodes, step_tag=global_step)
568
+ if args.track:
569
+ try:
570
+ import json as _json
571
+ from pathlib import Path as _Path
572
+ mpath = _Path(f"runs/{run_name}/trajectories/step_{global_step}/metrics.json")
573
+ if mpath.exists():
574
+ with mpath.open("r") as mf:
575
+ metrics = _json.load(mf)
576
+ wandb.log({
577
+ "eval/success_rate": metrics.get("success_rate"),
578
+ "eval/avg_return": metrics.get("avg_return"),
579
+ "eval/std_return": metrics.get("std_return"),
580
+ "eval/episodes": metrics.get("episodes"),
581
+ }, step=global_step)
582
+ except Exception:
583
+ pass
584
+ print(f"Collected {args.eval_episodes} eval trajectories at global_step {global_step}")
585
+ except Exception as e:
586
+ print(f"Warning: eval trajectory collection failed at step {global_step}: {e}")
587
+
588
+ envs.close()
cleanrl/cleanrl/scout_ppo/ragen_wrappers.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gymnasium-compatible wrappers for RAGEN environments to enable traditional RL training.
3
+ These wrappers convert text-based observations to numerical representations suitable for MLP networks.
4
+ """
5
+ import gymnasium as gym
6
+ import numpy as np
7
+ from typing import Any, Dict, Tuple
8
+
9
+
10
+ class BanditWrapper(gym.Wrapper):
11
+ """
12
+ Wrapper for RAGEN Bandit that uses only observable text.
13
+ Converts text observations to a fixed-size one-hot hash vector.
14
+ Does not alter episode semantics and does not inspect env internals.
15
+ """
16
+ def __init__(self, env, feature_dim_per_name: int = 16):
17
+ super().__init__(env)
18
+ # Two name slots (first/second), each hashed to one-hot of size K
19
+ self.k = feature_dim_per_name
20
+ self.observation_space = gym.spaces.Box(low=0, high=1, shape=(2 * self.k,), dtype=np.float32)
21
+ self.action_space = gym.spaces.Discrete(2)
22
+
23
+ def _parse_names(self, text_obs: str):
24
+ """Extract the two arm names from the prompt text purely via regex/string ops."""
25
+ # Heuristic: look for the segment after "named " and split by " and "
26
+ try:
27
+ anchor = "named "
28
+ if anchor in text_obs:
29
+ segment = text_obs.split(anchor, 1)[1]
30
+ # Cut at newline if present
31
+ segment = segment.split("\n", 1)[0]
32
+ # Now split by " and " to get two names; also strip punctuation
33
+ parts = segment.split(" and ")
34
+ if len(parts) >= 2:
35
+ name_a = parts[0].strip().strip(' .!?,')
36
+ name_b = parts[1].strip().strip(' .!?,')
37
+ return name_a, name_b
38
+ except Exception:
39
+ pass
40
+ # Fallback: no names found
41
+ return "", ""
42
+
43
+ def _names_to_vector(self, name_a: str, name_b: str) -> np.ndarray:
44
+ vec = np.zeros(2 * self.k, dtype=np.float32)
45
+ idx_a = (hash(name_a) % self.k)
46
+ idx_b = (hash(name_b) % self.k)
47
+ vec[idx_a] = 1.0
48
+ vec[self.k + idx_b] = 1.0
49
+ return vec
50
+
51
+ def reset(self, **kwargs):
52
+ seed = kwargs.get('seed', None)
53
+ mode = kwargs.get('mode', None)
54
+ text_obs = self.env.reset(seed=seed, mode=mode)
55
+ name_a, name_b = self._parse_names(text_obs)
56
+ return self._names_to_vector(name_a, name_b), {}
57
+
58
+ def step(self, action):
59
+ ragen_action = int(action) + 1
60
+ text_obs, reward, done, info = self.env.step(ragen_action)
61
+ name_a, name_b = self._parse_names(text_obs)
62
+ terminated = bool(done)
63
+ truncated = False
64
+ return self._names_to_vector(name_a, name_b), reward, terminated, truncated, info
65
+
66
+
67
+ class FrozenLakeWrapper(gym.Wrapper):
68
+ """
69
+ Wrapper for RAGEN FrozenLake environment.
70
+ Converts grid-based text observations to numerical state representation.
71
+ """
72
+ def __init__(self, env):
73
+ super().__init__(env)
74
+ # Bootstrap an observation to determine grid size from text only
75
+ bootstrap_text = self.env.reset()
76
+ flat, _ = self._parse_observation_and_meta(bootstrap_text)
77
+ self.observation_space = gym.spaces.Box(low=0, high=1, shape=(flat.shape[0],), dtype=np.float32)
78
+ self.action_space = gym.spaces.Discrete(4)
79
+ # Serve the bootstrapped obs on first reset without calling env.reset again
80
+ self._bootstrap_obs = flat
81
+ self._bootstrap_ready = True
82
+
83
+ def _parse_observation_and_meta(self, text_obs: str) -> Tuple[np.ndarray, Tuple[int, int]]:
84
+ """Parse text observation into numerical state (one-hot grid + player pos)."""
85
+ lines = text_obs.strip().split('\n')
86
+ grid = []
87
+ player_pos = None
88
+ rows = len(lines)
89
+ cols = max(len(line) for line in lines) if rows > 0 else 0
90
+ # Parse grid
91
+ for i, line in enumerate(lines):
92
+ row = []
93
+ for j, char in enumerate(line):
94
+ if char == 'P': # Player
95
+ row.append(0)
96
+ player_pos = (i, j)
97
+ elif char == '_': # Frozen
98
+ row.append(1)
99
+ elif char == 'O': # Hole
100
+ row.append(2)
101
+ elif char == 'G': # Goal
102
+ row.append(3)
103
+ elif char == 'X': # Player in hole
104
+ row.append(2)
105
+ player_pos = (i, j)
106
+ elif char == '√': # Player on goal
107
+ row.append(3)
108
+ player_pos = (i, j)
109
+ else:
110
+ row.append(1) # Default to frozen
111
+ grid.append(row)
112
+ # Pad ragged rows if needed
113
+ grid = np.array([r + [1] * (cols - len(r)) for r in grid], dtype=np.int32)
114
+ grid_size = (rows, cols)
115
+ # One-hot encode grid over 4 cell types
116
+ # One-hot encode grid
117
+ one_hot_grid = np.zeros((rows, cols, 4), dtype=np.float32)
118
+ for i in range(rows):
119
+ for j in range(cols):
120
+ cell_type = grid[i, j]
121
+ one_hot_grid[i, j, cell_type] = 1.0
122
+ # Flatten grid
123
+ flat_grid = one_hot_grid.flatten()
124
+ # Add normalized player position
125
+ if player_pos is None:
126
+ player_pos = (0, 0)
127
+ player_pos_norm = np.array([
128
+ 0.0 if rows <= 1 else player_pos[0] / max(1, rows - 1),
129
+ 0.0 if cols <= 1 else player_pos[1] / max(1, cols - 1),
130
+ ], dtype=np.float32)
131
+ flat = np.concatenate([flat_grid, player_pos_norm])
132
+ return flat, grid_size
133
+
134
+ def reset(self, **kwargs):
135
+ # Filter out 'options' parameter that gymnasium passes but RAGEN doesn't support
136
+ if self._bootstrap_ready:
137
+ # First call returns the bootstrapped observation to avoid double reset
138
+ self._bootstrap_ready = False
139
+ return self._bootstrap_obs.copy(), {}
140
+ seed = kwargs.get('seed', None)
141
+ mode = kwargs.get('mode', None)
142
+ text_obs = self.env.reset(seed=seed, mode=mode)
143
+ state, _ = self._parse_observation_and_meta(text_obs)
144
+ return state, {}
145
+
146
+ def step(self, action):
147
+ # Map action from 0,1,2,3 to 1,2,3,4 (RAGEN uses 1-indexed actions)
148
+ ragen_action = action + 1
149
+ text_obs, reward, done, info = self.env.step(ragen_action)
150
+ state, _ = self._parse_observation_and_meta(text_obs)
151
+
152
+ terminated = done
153
+ truncated = False
154
+
155
+ return state, reward, terminated, truncated, info
156
+
157
+
158
+ class SokobanWrapper(gym.Wrapper):
159
+ """
160
+ Wrapper for RAGEN Sokoban environment.
161
+ Converts grid-based text observations to numerical state representation.
162
+ Note: Does not inherit from gym.Wrapper due to old gym vs gymnasium compatibility.
163
+ """
164
+ def __init__(self, env):
165
+ super().__init__(env)
166
+ # Bootstrap an observation to determine room size from text only
167
+ bootstrap_text = self.env.reset()
168
+ flat, rows, cols = self._parse_observation_and_meta(bootstrap_text)
169
+ self.observation_space = gym.spaces.Box(low=0, high=1, shape=(flat.shape[0],), dtype=np.float32)
170
+ self.action_space = gym.spaces.Discrete(4)
171
+ self.metadata = getattr(env, 'metadata', {})
172
+ self._bootstrap_obs = flat
173
+ self._bootstrap_ready = True
174
+
175
+ def _parse_observation_and_meta(self, text_obs: str) -> Tuple[np.ndarray, int, int]:
176
+ """Parse text observation into numerical state and return dims."""
177
+ lines = text_obs.strip().split('\n')
178
+ grid = []
179
+ rows = len(lines)
180
+ cols = max(len(line) for line in lines) if rows > 0 else 0
181
+ # Mapping from characters to cell types
182
+ char_to_type = {
183
+ '#': 0, # wall
184
+ '_': 1, # empty
185
+ 'O': 2, # target
186
+ '√': 3, # box on target
187
+ 'X': 4, # box
188
+ 'P': 5, # player
189
+ 'S': 6, # player on target
190
+ }
191
+
192
+ for line in lines:
193
+ row = []
194
+ for char in line:
195
+ row.append(char_to_type.get(char, 1)) # Default to empty
196
+ grid.append(row)
197
+ # Pad ragged rows
198
+ grid = np.array([r + [1] * (cols - len(r)) for r in grid], dtype=np.int32)
199
+ # One-hot encode grid
200
+ one_hot_grid = np.zeros((rows, cols, 7), dtype=np.float32)
201
+ for i in range(rows):
202
+ for j in range(cols):
203
+ cell_type = grid[i, j]
204
+ one_hot_grid[i, j, cell_type] = 1.0
205
+ return one_hot_grid.flatten(), rows, cols
206
+
207
+ def reset(self, **kwargs):
208
+ if self._bootstrap_ready:
209
+ self._bootstrap_ready = False
210
+ return self._bootstrap_obs.copy(), {}
211
+ seed = kwargs.get('seed', None)
212
+ mode = kwargs.get('mode', None)
213
+ text_obs = self.env.reset(seed=seed, mode=mode)
214
+ state, _, _ = self._parse_observation_and_meta(text_obs)
215
+ return state, {}
216
+
217
+ def step(self, action):
218
+ # Map action from 0,1,2,3 to 1,2,3,4 (RAGEN uses 1-indexed actions)
219
+ ragen_action = action + 1
220
+ text_obs, reward, done, info = self.env.step(ragen_action)
221
+ state, _, _ = self._parse_observation_and_meta(text_obs)
222
+
223
+ terminated = done
224
+ truncated = False
225
+
226
+ return state, reward, terminated, truncated, info
227
+
228
+ def close(self):
229
+ if hasattr(self.env, 'close'):
230
+ self.env.close()
231
+
232
+ def render(self):
233
+ if hasattr(self.env, 'render'):
234
+ return self.env.render()
235
+ return None
cleanrl/cleanrl/td3_continuous_action.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/td3/#td3_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.nn.functional as F
12
+ import torch.optim as optim
13
+ import tyro
14
+ from torch.utils.tensorboard import SummaryWriter
15
+
16
+ from cleanrl_utils.buffers import ReplayBuffer
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
+ save_model: bool = False
38
+ """whether to save model into the `runs/{run_name}` folder"""
39
+ upload_model: bool = False
40
+ """whether to upload the saved model to huggingface"""
41
+ hf_entity: str = ""
42
+ """the user or org name of the model repository from the Hugging Face Hub"""
43
+
44
+ # Algorithm specific arguments
45
+ env_id: str = "Hopper-v4"
46
+ """the id of the environment"""
47
+ total_timesteps: int = 1000000
48
+ """total timesteps of the experiments"""
49
+ learning_rate: float = 3e-4
50
+ """the learning rate of the optimizer"""
51
+ num_envs: int = 1
52
+ """the number of parallel game environments"""
53
+ buffer_size: int = int(1e6)
54
+ """the replay memory buffer size"""
55
+ gamma: float = 0.99
56
+ """the discount factor gamma"""
57
+ tau: float = 0.005
58
+ """target smoothing coefficient (default: 0.005)"""
59
+ batch_size: int = 256
60
+ """the batch size of sample from the reply memory"""
61
+ policy_noise: float = 0.2
62
+ """the scale of policy noise"""
63
+ exploration_noise: float = 0.1
64
+ """the scale of exploration noise"""
65
+ learning_starts: int = 25e3
66
+ """timestep to start learning"""
67
+ policy_frequency: int = 2
68
+ """the frequency of training policy (delayed)"""
69
+ noise_clip: float = 0.5
70
+ """noise clip parameter of the Target Policy Smoothing Regularization"""
71
+
72
+
73
+ def make_env(env_id, seed, idx, capture_video, run_name):
74
+ def thunk():
75
+ if capture_video and idx == 0:
76
+ env = gym.make(env_id, render_mode="rgb_array")
77
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
78
+ else:
79
+ env = gym.make(env_id)
80
+ env = gym.wrappers.RecordEpisodeStatistics(env)
81
+ env.action_space.seed(seed)
82
+ return env
83
+
84
+ return thunk
85
+
86
+
87
+ # ALGO LOGIC: initialize agent here:
88
+ class QNetwork(nn.Module):
89
+ def __init__(self, env):
90
+ super().__init__()
91
+ self.fc1 = nn.Linear(
92
+ np.array(env.single_observation_space.shape).prod() + np.prod(env.single_action_space.shape),
93
+ 256,
94
+ )
95
+ self.fc2 = nn.Linear(256, 256)
96
+ self.fc3 = nn.Linear(256, 1)
97
+
98
+ def forward(self, x, a):
99
+ x = torch.cat([x, a], 1)
100
+ x = F.relu(self.fc1(x))
101
+ x = F.relu(self.fc2(x))
102
+ x = self.fc3(x)
103
+ return x
104
+
105
+
106
+ class Actor(nn.Module):
107
+ def __init__(self, env):
108
+ super().__init__()
109
+ self.fc1 = nn.Linear(np.array(env.single_observation_space.shape).prod(), 256)
110
+ self.fc2 = nn.Linear(256, 256)
111
+ self.fc_mu = nn.Linear(256, np.prod(env.single_action_space.shape))
112
+ # action rescaling
113
+ self.register_buffer(
114
+ "action_scale",
115
+ torch.tensor(
116
+ (env.single_action_space.high - env.single_action_space.low) / 2.0,
117
+ dtype=torch.float32,
118
+ ),
119
+ )
120
+ self.register_buffer(
121
+ "action_bias",
122
+ torch.tensor(
123
+ (env.single_action_space.high + env.single_action_space.low) / 2.0,
124
+ dtype=torch.float32,
125
+ ),
126
+ )
127
+
128
+ def forward(self, x):
129
+ x = F.relu(self.fc1(x))
130
+ x = F.relu(self.fc2(x))
131
+ x = torch.tanh(self.fc_mu(x))
132
+ return x * self.action_scale + self.action_bias
133
+
134
+
135
+ if __name__ == "__main__":
136
+
137
+ args = tyro.cli(Args)
138
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
139
+ if args.track:
140
+ import wandb
141
+
142
+ wandb.init(
143
+ project=args.wandb_project_name,
144
+ entity=args.wandb_entity,
145
+ sync_tensorboard=True,
146
+ config=vars(args),
147
+ name=run_name,
148
+ monitor_gym=True,
149
+ save_code=True,
150
+ )
151
+ writer = SummaryWriter(f"runs/{run_name}")
152
+ writer.add_text(
153
+ "hyperparameters",
154
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
155
+ )
156
+
157
+ # TRY NOT TO MODIFY: seeding
158
+ random.seed(args.seed)
159
+ np.random.seed(args.seed)
160
+ torch.manual_seed(args.seed)
161
+ torch.backends.cudnn.deterministic = args.torch_deterministic
162
+
163
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
164
+
165
+ # env setup
166
+ envs = gym.vector.SyncVectorEnv(
167
+ [make_env(args.env_id, args.seed + i, i, args.capture_video, run_name) for i in range(args.num_envs)]
168
+ )
169
+ assert isinstance(envs.single_action_space, gym.spaces.Box), "only continuous action space is supported"
170
+
171
+ actor = Actor(envs).to(device)
172
+ qf1 = QNetwork(envs).to(device)
173
+ qf2 = QNetwork(envs).to(device)
174
+ qf1_target = QNetwork(envs).to(device)
175
+ qf2_target = QNetwork(envs).to(device)
176
+ target_actor = Actor(envs).to(device)
177
+ target_actor.load_state_dict(actor.state_dict())
178
+ qf1_target.load_state_dict(qf1.state_dict())
179
+ qf2_target.load_state_dict(qf2.state_dict())
180
+ q_optimizer = optim.Adam(list(qf1.parameters()) + list(qf2.parameters()), lr=args.learning_rate)
181
+ actor_optimizer = optim.Adam(list(actor.parameters()), lr=args.learning_rate)
182
+
183
+ envs.single_observation_space.dtype = np.float32
184
+ rb = ReplayBuffer(
185
+ args.buffer_size,
186
+ envs.single_observation_space,
187
+ envs.single_action_space,
188
+ device,
189
+ n_envs=args.num_envs,
190
+ handle_timeout_termination=False,
191
+ )
192
+ start_time = time.time()
193
+
194
+ # TRY NOT TO MODIFY: start the game
195
+ obs, _ = envs.reset(seed=args.seed)
196
+ for global_step in range(args.total_timesteps):
197
+ # ALGO LOGIC: put action logic here
198
+ if global_step < args.learning_starts:
199
+ actions = np.array([envs.single_action_space.sample() for _ in range(envs.num_envs)])
200
+ else:
201
+ with torch.no_grad():
202
+ actions = actor(torch.Tensor(obs).to(device))
203
+ actions += torch.normal(0, actor.action_scale * args.exploration_noise)
204
+ actions = actions.cpu().numpy().clip(envs.single_action_space.low, envs.single_action_space.high)
205
+
206
+ # TRY NOT TO MODIFY: execute the game and log data.
207
+ next_obs, rewards, terminations, truncations, infos = envs.step(actions)
208
+
209
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
210
+ if "final_info" in infos:
211
+ for info in infos["final_info"]:
212
+ if info is not None:
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
+ break
217
+
218
+ # TRY NOT TO MODIFY: save data to reply buffer; handle `final_observation`
219
+ real_next_obs = next_obs.copy()
220
+ for idx, trunc in enumerate(truncations):
221
+ if trunc:
222
+ real_next_obs[idx] = infos["final_observation"][idx]
223
+ rb.add(obs, real_next_obs, actions, rewards, terminations, infos)
224
+
225
+ # TRY NOT TO MODIFY: CRUCIAL step easy to overlook
226
+ obs = next_obs
227
+
228
+ # ALGO LOGIC: training.
229
+ if global_step > args.learning_starts:
230
+ data = rb.sample(args.batch_size)
231
+ with torch.no_grad():
232
+ clipped_noise = (torch.randn_like(data.actions, device=device) * args.policy_noise).clamp(
233
+ -args.noise_clip, args.noise_clip
234
+ ) * target_actor.action_scale
235
+
236
+ next_state_actions = (target_actor(data.next_observations) + clipped_noise).clamp(
237
+ envs.single_action_space.low[0], envs.single_action_space.high[0]
238
+ )
239
+ qf1_next_target = qf1_target(data.next_observations, next_state_actions)
240
+ qf2_next_target = qf2_target(data.next_observations, next_state_actions)
241
+ min_qf_next_target = torch.min(qf1_next_target, qf2_next_target)
242
+ next_q_value = data.rewards.flatten() + (1 - data.dones.flatten()) * args.gamma * (min_qf_next_target).view(-1)
243
+
244
+ qf1_a_values = qf1(data.observations, data.actions).view(-1)
245
+ qf2_a_values = qf2(data.observations, data.actions).view(-1)
246
+ qf1_loss = F.mse_loss(qf1_a_values, next_q_value)
247
+ qf2_loss = F.mse_loss(qf2_a_values, next_q_value)
248
+ qf_loss = qf1_loss + qf2_loss
249
+
250
+ # optimize the model
251
+ q_optimizer.zero_grad()
252
+ qf_loss.backward()
253
+ q_optimizer.step()
254
+
255
+ if global_step % args.policy_frequency == 0:
256
+ actor_loss = -qf1(data.observations, actor(data.observations)).mean()
257
+ actor_optimizer.zero_grad()
258
+ actor_loss.backward()
259
+ actor_optimizer.step()
260
+
261
+ # update the target network
262
+ for param, target_param in zip(actor.parameters(), target_actor.parameters()):
263
+ target_param.data.copy_(args.tau * param.data + (1 - args.tau) * target_param.data)
264
+ for param, target_param in zip(qf1.parameters(), qf1_target.parameters()):
265
+ target_param.data.copy_(args.tau * param.data + (1 - args.tau) * target_param.data)
266
+ for param, target_param in zip(qf2.parameters(), qf2_target.parameters()):
267
+ target_param.data.copy_(args.tau * param.data + (1 - args.tau) * target_param.data)
268
+
269
+ if global_step % 100 == 0:
270
+ writer.add_scalar("losses/qf1_values", qf1_a_values.mean().item(), global_step)
271
+ writer.add_scalar("losses/qf2_values", qf2_a_values.mean().item(), global_step)
272
+ writer.add_scalar("losses/qf1_loss", qf1_loss.item(), global_step)
273
+ writer.add_scalar("losses/qf2_loss", qf2_loss.item(), global_step)
274
+ writer.add_scalar("losses/qf_loss", qf_loss.item() / 2.0, global_step)
275
+ writer.add_scalar("losses/actor_loss", actor_loss.item(), global_step)
276
+ print("SPS:", int(global_step / (time.time() - start_time)))
277
+ writer.add_scalar(
278
+ "charts/SPS",
279
+ int(global_step / (time.time() - start_time)),
280
+ global_step,
281
+ )
282
+
283
+ if args.save_model:
284
+ model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
285
+ torch.save((actor.state_dict(), qf1.state_dict(), qf2.state_dict()), model_path)
286
+ print(f"model saved to {model_path}")
287
+ from cleanrl_utils.evals.td3_eval import evaluate
288
+
289
+ episodic_returns = evaluate(
290
+ model_path,
291
+ make_env,
292
+ args.env_id,
293
+ eval_episodes=10,
294
+ run_name=f"{run_name}-eval",
295
+ Model=(Actor, QNetwork),
296
+ device=device,
297
+ exploration_noise=args.exploration_noise,
298
+ )
299
+ for idx, episodic_return in enumerate(episodic_returns):
300
+ writer.add_scalar("eval/episodic_return", episodic_return, idx)
301
+
302
+ if args.upload_model:
303
+ from cleanrl_utils.huggingface import push_to_hub
304
+
305
+ repo_name = f"{args.env_id}-{args.exp_name}-seed{args.seed}"
306
+ repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
307
+ push_to_hub(
308
+ args,
309
+ episodic_returns,
310
+ repo_id,
311
+ "TD3",
312
+ f"runs/{run_name}",
313
+ f"videos/{run_name}-eval",
314
+ )
315
+
316
+ envs.close()
317
+ writer.close()
cleanrl/cleanrl/td3_continuous_action_jax.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/td3/#td3_continuous_action_jaxpy
2
+ import os
3
+ import random
4
+ import time
5
+ from dataclasses import dataclass
6
+
7
+ import flax
8
+ import flax.linen as nn
9
+ import gymnasium as gym
10
+ import jax
11
+ import jax.numpy as jnp
12
+ import numpy as np
13
+ import optax
14
+ import tyro
15
+ from flax.training.train_state import TrainState
16
+ from torch.utils.tensorboard import SummaryWriter
17
+
18
+ from cleanrl_utils.buffers import ReplayBuffer
19
+
20
+
21
+ @dataclass
22
+ class Args:
23
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
24
+ """the name of this experiment"""
25
+ seed: int = 1
26
+ """seed of the experiment"""
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 = "Hopper-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
+ buffer_size: int = int(1e6)
50
+ """the replay memory buffer size"""
51
+ gamma: float = 0.99
52
+ """the discount factor gamma"""
53
+ tau: float = 0.005
54
+ """target smoothing coefficient (default: 0.005)"""
55
+ batch_size: int = 256
56
+ """the batch size of sample from the reply memory"""
57
+ policy_noise: float = 0.2
58
+ """the scale of policy noise"""
59
+ exploration_noise: float = 0.1
60
+ """the scale of exploration noise"""
61
+ learning_starts: int = 25e3
62
+ """timestep to start learning"""
63
+ policy_frequency: int = 2
64
+ """the frequency of training policy (delayed)"""
65
+ noise_clip: float = 0.5
66
+ """noise clip parameter of the Target Policy Smoothing Regularization"""
67
+
68
+
69
+ def make_env(env_id, seed, idx, capture_video, run_name):
70
+ def thunk():
71
+ if capture_video and idx == 0:
72
+ env = gym.make(env_id, render_mode="rgb_array")
73
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
74
+ else:
75
+ env = gym.make(env_id)
76
+ env = gym.wrappers.RecordEpisodeStatistics(env)
77
+ env.action_space.seed(seed)
78
+ return env
79
+
80
+ return thunk
81
+
82
+
83
+ # ALGO LOGIC: initialize agent here:
84
+ class QNetwork(nn.Module):
85
+ @nn.compact
86
+ def __call__(self, x: jnp.ndarray, a: jnp.ndarray):
87
+ x = jnp.concatenate([x, a], -1)
88
+ x = nn.Dense(256)(x)
89
+ x = nn.relu(x)
90
+ x = nn.Dense(256)(x)
91
+ x = nn.relu(x)
92
+ x = nn.Dense(1)(x)
93
+ return x
94
+
95
+
96
+ class Actor(nn.Module):
97
+ action_dim: int
98
+ action_scale: jnp.ndarray
99
+ action_bias: jnp.ndarray
100
+
101
+ @nn.compact
102
+ def __call__(self, x):
103
+ x = nn.Dense(256)(x)
104
+ x = nn.relu(x)
105
+ x = nn.Dense(256)(x)
106
+ x = nn.relu(x)
107
+ x = nn.Dense(self.action_dim)(x)
108
+ x = nn.tanh(x)
109
+ x = x * self.action_scale + self.action_bias
110
+ return x
111
+
112
+
113
+ class TrainState(TrainState):
114
+ target_params: flax.core.FrozenDict
115
+
116
+
117
+ if __name__ == "__main__":
118
+ args = tyro.cli(Args)
119
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
120
+ if args.track:
121
+ import wandb
122
+
123
+ wandb.init(
124
+ project=args.wandb_project_name,
125
+ entity=args.wandb_entity,
126
+ sync_tensorboard=True,
127
+ config=vars(args),
128
+ name=run_name,
129
+ monitor_gym=True,
130
+ save_code=True,
131
+ )
132
+ writer = SummaryWriter(f"runs/{run_name}")
133
+ writer.add_text(
134
+ "hyperparameters",
135
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
136
+ )
137
+
138
+ # TRY NOT TO MODIFY: seeding
139
+ random.seed(args.seed)
140
+ np.random.seed(args.seed)
141
+ key = jax.random.PRNGKey(args.seed)
142
+ key, actor_key, qf1_key, qf2_key = jax.random.split(key, 4)
143
+
144
+ # env setup
145
+ envs = gym.vector.SyncVectorEnv([make_env(args.env_id, args.seed, 0, args.capture_video, run_name)])
146
+ assert isinstance(envs.single_action_space, gym.spaces.Box), "only continuous action space is supported"
147
+
148
+ max_action = float(envs.single_action_space.high[0])
149
+ envs.single_observation_space.dtype = np.float32
150
+ rb = ReplayBuffer(
151
+ args.buffer_size,
152
+ envs.single_observation_space,
153
+ envs.single_action_space,
154
+ device="cpu",
155
+ handle_timeout_termination=False,
156
+ )
157
+
158
+ # TRY NOT TO MODIFY: start the game
159
+ obs, _ = envs.reset(seed=args.seed)
160
+
161
+ actor = Actor(
162
+ action_dim=np.prod(envs.single_action_space.shape),
163
+ action_scale=jnp.array((envs.action_space.high - envs.action_space.low) / 2.0),
164
+ action_bias=jnp.array((envs.action_space.high + envs.action_space.low) / 2.0),
165
+ )
166
+ actor_state = TrainState.create(
167
+ apply_fn=actor.apply,
168
+ params=actor.init(actor_key, obs),
169
+ target_params=actor.init(actor_key, obs),
170
+ tx=optax.adam(learning_rate=args.learning_rate),
171
+ )
172
+ qf = QNetwork()
173
+ qf1_state = TrainState.create(
174
+ apply_fn=qf.apply,
175
+ params=qf.init(qf1_key, obs, envs.action_space.sample()),
176
+ target_params=qf.init(qf1_key, obs, envs.action_space.sample()),
177
+ tx=optax.adam(learning_rate=args.learning_rate),
178
+ )
179
+ qf2_state = TrainState.create(
180
+ apply_fn=qf.apply,
181
+ params=qf.init(qf2_key, obs, envs.action_space.sample()),
182
+ target_params=qf.init(qf2_key, obs, envs.action_space.sample()),
183
+ tx=optax.adam(learning_rate=args.learning_rate),
184
+ )
185
+ actor.apply = jax.jit(actor.apply)
186
+ qf.apply = jax.jit(qf.apply)
187
+
188
+ @jax.jit
189
+ def update_critic(
190
+ actor_state: TrainState,
191
+ qf1_state: TrainState,
192
+ qf2_state: TrainState,
193
+ observations: np.ndarray,
194
+ actions: np.ndarray,
195
+ next_observations: np.ndarray,
196
+ rewards: np.ndarray,
197
+ terminations: np.ndarray,
198
+ key: jnp.ndarray,
199
+ ):
200
+ # TODO Maybe pre-generate a lot of random keys
201
+ # also check https://jax.readthedocs.io/en/latest/jax.random.html
202
+ key, noise_key = jax.random.split(key, 2)
203
+ clipped_noise = (
204
+ jnp.clip(
205
+ (jax.random.normal(noise_key, actions.shape) * args.policy_noise),
206
+ -args.noise_clip,
207
+ args.noise_clip,
208
+ )
209
+ * actor.action_scale
210
+ )
211
+ next_state_actions = jnp.clip(
212
+ actor.apply(actor_state.target_params, next_observations) + clipped_noise,
213
+ envs.single_action_space.low,
214
+ envs.single_action_space.high,
215
+ )
216
+ qf1_next_target = qf.apply(qf1_state.target_params, next_observations, next_state_actions).reshape(-1)
217
+ qf2_next_target = qf.apply(qf2_state.target_params, next_observations, next_state_actions).reshape(-1)
218
+ min_qf_next_target = jnp.minimum(qf1_next_target, qf2_next_target)
219
+ next_q_value = (rewards + (1 - terminations) * args.gamma * (min_qf_next_target)).reshape(-1)
220
+
221
+ def mse_loss(params):
222
+ qf_a_values = qf.apply(params, observations, actions).squeeze()
223
+ return ((qf_a_values - next_q_value) ** 2).mean(), qf_a_values.mean()
224
+
225
+ (qf1_loss_value, qf1_a_values), grads1 = jax.value_and_grad(mse_loss, has_aux=True)(qf1_state.params)
226
+ (qf2_loss_value, qf2_a_values), grads2 = jax.value_and_grad(mse_loss, has_aux=True)(qf2_state.params)
227
+ qf1_state = qf1_state.apply_gradients(grads=grads1)
228
+ qf2_state = qf2_state.apply_gradients(grads=grads2)
229
+
230
+ return (qf1_state, qf2_state), (qf1_loss_value, qf2_loss_value), (qf1_a_values, qf2_a_values), key
231
+
232
+ @jax.jit
233
+ def update_actor(
234
+ actor_state: TrainState,
235
+ qf1_state: TrainState,
236
+ qf2_state: TrainState,
237
+ observations: np.ndarray,
238
+ ):
239
+ def actor_loss(params):
240
+ return -qf.apply(qf1_state.params, observations, actor.apply(params, observations)).mean()
241
+
242
+ actor_loss_value, grads = jax.value_and_grad(actor_loss)(actor_state.params)
243
+ actor_state = actor_state.apply_gradients(grads=grads)
244
+ actor_state = actor_state.replace(
245
+ target_params=optax.incremental_update(actor_state.params, actor_state.target_params, args.tau)
246
+ )
247
+
248
+ qf1_state = qf1_state.replace(
249
+ target_params=optax.incremental_update(qf1_state.params, qf1_state.target_params, args.tau)
250
+ )
251
+ qf2_state = qf2_state.replace(
252
+ target_params=optax.incremental_update(qf2_state.params, qf2_state.target_params, args.tau)
253
+ )
254
+ return actor_state, (qf1_state, qf2_state), actor_loss_value
255
+
256
+ start_time = time.time()
257
+ for global_step in range(args.total_timesteps):
258
+ # ALGO LOGIC: put action logic here
259
+ if global_step < args.learning_starts:
260
+ actions = np.array([envs.single_action_space.sample() for _ in range(envs.num_envs)])
261
+ else:
262
+ actions = actor.apply(actor_state.params, obs)
263
+ actions = np.array(
264
+ [
265
+ (
266
+ jax.device_get(actions)[0]
267
+ + np.random.normal(0, max_action * args.exploration_noise, size=envs.single_action_space.shape)
268
+ ).clip(envs.single_action_space.low, envs.single_action_space.high)
269
+ ]
270
+ )
271
+
272
+ # TRY NOT TO MODIFY: execute the game and log data.
273
+ next_obs, rewards, terminations, truncations, infos = envs.step(actions)
274
+
275
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
276
+ if "final_info" in infos:
277
+ for info in infos["final_info"]:
278
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
279
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
280
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
281
+ break
282
+
283
+ # TRY NOT TO MODIFY: save data to replay buffer; handle `final_observation`
284
+ real_next_obs = next_obs.copy()
285
+ for idx, trunc in enumerate(truncations):
286
+ if trunc:
287
+ real_next_obs[idx] = infos["final_observation"][idx]
288
+ rb.add(obs, real_next_obs, actions, rewards, terminations, infos)
289
+
290
+ # TRY NOT TO MODIFY: CRUCIAL step easy to overlook
291
+ obs = next_obs
292
+
293
+ # ALGO LOGIC: training.
294
+ if global_step > args.learning_starts:
295
+ data = rb.sample(args.batch_size)
296
+
297
+ (qf1_state, qf2_state), (qf1_loss_value, qf2_loss_value), (qf1_a_values, qf2_a_values), key = update_critic(
298
+ actor_state,
299
+ qf1_state,
300
+ qf2_state,
301
+ data.observations.numpy(),
302
+ data.actions.numpy(),
303
+ data.next_observations.numpy(),
304
+ data.rewards.flatten().numpy(),
305
+ data.dones.flatten().numpy(),
306
+ key,
307
+ )
308
+
309
+ if global_step % args.policy_frequency == 0:
310
+ actor_state, (qf1_state, qf2_state), actor_loss_value = update_actor(
311
+ actor_state,
312
+ qf1_state,
313
+ qf2_state,
314
+ data.observations.numpy(),
315
+ )
316
+
317
+ if global_step % 100 == 0:
318
+ writer.add_scalar("losses/qf1_loss", qf1_loss_value.item(), global_step)
319
+ writer.add_scalar("losses/qf2_loss", qf2_loss_value.item(), global_step)
320
+ writer.add_scalar("losses/qf1_values", qf1_a_values.item(), global_step)
321
+ writer.add_scalar("losses/qf2_values", qf2_a_values.item(), global_step)
322
+ writer.add_scalar("losses/actor_loss", actor_loss_value.item(), 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
+ with open(model_path, "wb") as f:
329
+ f.write(
330
+ flax.serialization.to_bytes(
331
+ [
332
+ actor_state.params,
333
+ qf1_state.params,
334
+ qf2_state.params,
335
+ ]
336
+ )
337
+ )
338
+ print(f"model saved to {model_path}")
339
+ from cleanrl_utils.evals.td3_jax_eval import evaluate
340
+
341
+ episodic_returns = evaluate(
342
+ model_path,
343
+ make_env,
344
+ args.env_id,
345
+ eval_episodes=10,
346
+ run_name=f"{run_name}-eval",
347
+ Model=(Actor, QNetwork),
348
+ exploration_noise=args.exploration_noise,
349
+ )
350
+ for idx, episodic_return in enumerate(episodic_returns):
351
+ writer.add_scalar("eval/episodic_return", episodic_return, idx)
352
+
353
+ if args.upload_model:
354
+ from cleanrl_utils.huggingface import push_to_hub
355
+
356
+ repo_name = f"{args.env_id}-{args.exp_name}-seed{args.seed}"
357
+ repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
358
+ push_to_hub(args, episodic_returns, repo_id, "TD3", f"runs/{run_name}", f"videos/{run_name}-eval")
359
+
360
+ envs.close()
361
+ writer.close()
cleanrl/cleanrl/wandb/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/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/run-20251107_102633-lu2iu68t/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
+ 6ymqnqubvr99vvj2hajaxngee30bwzdk:
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: "30509887488"
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:26:33.725426Z"
76
+ writerId: 6ymqnqubvr99vvj2hajaxngee30bwzdk
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: 610
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: 10000000
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_102633-lu2iu68t/files/wandb-summary.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"losses/value_loss":0.044632442,"charts/min_reward":0,"losses/old_approx_kl":-1.379085e-07,"charts/avg_reward":0.089166254,"_wandb":{"runtime":353},"losses/clipfrac":0,"global_step":9994240,"losses/policy_loss":-2.789311e-07,"_step":7929,"_runtime":353,"losses/approx_kl":3.2465323e-08,"losses/explained_variance":5.1021576e-05,"charts/max_reward":1,"losses/entropy":0.69236815,"_timestamp":1.7624827486915712e+09,"charts/SPS":28390,"charts/learning_rate":4.0983608e-07,"charts/avg_value":0.17397192}
cleanrl/cleanrl/wandb/run-20251107_103331-e2e7wd2b/files/code/cleanrl/ppo_frozenlake.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PPO implementation for RAGEN FrozenLake 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.frozen_lake.env import FrozenLakeEnv
20
+ from ragen.env.frozen_lake.config import FrozenLakeEnvConfig
21
+ from ragen_wrappers import FrozenLakeWrapper
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 = "FrozenLake"
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 = 8
51
+ """the number of parallel game environments"""
52
+ num_steps: int = 128
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
+ # FrozenLake specific
80
+ grid_size: int = 4
81
+ """size of the frozen lake grid"""
82
+ is_slippery: bool = True
83
+ """whether the ice is slippery"""
84
+
85
+ # to be filled in runtime
86
+ batch_size: int = 0
87
+ """the batch size (computed in runtime)"""
88
+ minibatch_size: int = 0
89
+ """the mini-batch size (computed in runtime)"""
90
+ num_iterations: int = 0
91
+ """the number of iterations (computed in runtime)"""
92
+
93
+
94
+ def make_env(env_id, idx, capture_video, run_name, seed, grid_size, is_slippery):
95
+ def thunk():
96
+ config = FrozenLakeEnvConfig(
97
+ size=grid_size,
98
+ p=0.8,
99
+ is_slippery=is_slippery,
100
+ map_seed=seed + idx
101
+ )
102
+ env = FrozenLakeEnv(config)
103
+ env = FrozenLakeWrapper(env)
104
+ env = gym.wrappers.RecordEpisodeStatistics(env)
105
+ if capture_video and idx == 0:
106
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
107
+ return env
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
+ obs_shape = np.array(envs.single_observation_space.shape).prod()
121
+ self.critic = nn.Sequential(
122
+ layer_init(nn.Linear(obs_shape, 128)),
123
+ nn.Tanh(),
124
+ layer_init(nn.Linear(128, 128)),
125
+ nn.Tanh(),
126
+ layer_init(nn.Linear(128, 1), std=1.0),
127
+ )
128
+ self.actor = nn.Sequential(
129
+ layer_init(nn.Linear(obs_shape, 128)),
130
+ nn.Tanh(),
131
+ layer_init(nn.Linear(128, 128)),
132
+ nn.Tanh(),
133
+ layer_init(nn.Linear(128, envs.single_action_space.n), std=0.01),
134
+ )
135
+
136
+ def get_value(self, x):
137
+ return self.critic(x)
138
+
139
+ def get_action_and_value(self, x, action=None):
140
+ logits = self.actor(x)
141
+ probs = Categorical(logits=logits)
142
+ if action is None:
143
+ action = probs.sample()
144
+ return action, probs.log_prob(action), probs.entropy(), self.critic(x)
145
+
146
+
147
+ if __name__ == "__main__":
148
+ args = tyro.cli(Args)
149
+ args.batch_size = int(args.num_envs * args.num_steps)
150
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
151
+ args.num_iterations = args.total_timesteps // args.batch_size
152
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
153
+ if args.track:
154
+ import wandb
155
+
156
+ wandb.init(
157
+ project=args.wandb_project_name,
158
+ entity=args.wandb_entity,
159
+ sync_tensorboard=True,
160
+ config=vars(args),
161
+ name=run_name,
162
+ monitor_gym=True,
163
+ save_code=True,
164
+ )
165
+ writer = SummaryWriter(f"runs/{run_name}")
166
+ writer.add_text(
167
+ "hyperparameters",
168
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
169
+ )
170
+
171
+ # TRY NOT TO MODIFY: seeding
172
+ random.seed(args.seed)
173
+ np.random.seed(args.seed)
174
+ torch.manual_seed(args.seed)
175
+ torch.backends.cudnn.deterministic = args.torch_deterministic
176
+
177
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
178
+
179
+ # env setup
180
+ envs = gym.vector.SyncVectorEnv(
181
+ [make_env(args.env_id, i, args.capture_video, run_name, args.seed, args.grid_size, args.is_slippery)
182
+ for i in range(args.num_envs)],
183
+ )
184
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
185
+
186
+ agent = Agent(envs).to(device)
187
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
188
+
189
+ # ALGO Logic: Storage setup
190
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
191
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
192
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
193
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
194
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
195
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
196
+
197
+ # TRY NOT TO MODIFY: start the game
198
+ global_step = 0
199
+ start_time = time.time()
200
+ next_obs, _ = envs.reset(seed=args.seed)
201
+ next_obs = torch.Tensor(next_obs).to(device)
202
+ next_done = torch.zeros(args.num_envs).to(device)
203
+
204
+ for iteration in range(1, args.num_iterations + 1):
205
+ # Annealing the rate if instructed to do so.
206
+ if args.anneal_lr:
207
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
208
+ lrnow = frac * args.learning_rate
209
+ optimizer.param_groups[0]["lr"] = lrnow
210
+
211
+ for step in range(0, args.num_steps):
212
+ global_step += args.num_envs
213
+ obs[step] = next_obs
214
+ dones[step] = next_done
215
+
216
+ # ALGO LOGIC: action logic
217
+ with torch.no_grad():
218
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
219
+ values[step] = value.flatten()
220
+ actions[step] = action
221
+ logprobs[step] = logprob
222
+
223
+ # TRY NOT TO MODIFY: execute the game and log data.
224
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
225
+ next_done = np.logical_or(terminations, truncations)
226
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
227
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
228
+
229
+ if "final_info" in infos:
230
+ for info in infos["final_info"]:
231
+ if info and "episode" in info:
232
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
233
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
234
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
235
+
236
+ # bootstrap value if not done
237
+ with torch.no_grad():
238
+ next_value = agent.get_value(next_obs).reshape(1, -1)
239
+ advantages = torch.zeros_like(rewards).to(device)
240
+ lastgaelam = 0
241
+ for t in reversed(range(args.num_steps)):
242
+ if t == args.num_steps - 1:
243
+ nextnonterminal = 1.0 - next_done
244
+ nextvalues = next_value
245
+ else:
246
+ nextnonterminal = 1.0 - dones[t + 1]
247
+ nextvalues = values[t + 1]
248
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
249
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
250
+ returns = advantages + values
251
+
252
+ # flatten the batch
253
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
254
+ b_logprobs = logprobs.reshape(-1)
255
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
256
+ b_advantages = advantages.reshape(-1)
257
+ b_returns = returns.reshape(-1)
258
+ b_values = values.reshape(-1)
259
+
260
+ # Optimizing the policy and value network
261
+ b_inds = np.arange(args.batch_size)
262
+ clipfracs = []
263
+ for epoch in range(args.update_epochs):
264
+ np.random.shuffle(b_inds)
265
+ for start in range(0, args.batch_size, args.minibatch_size):
266
+ end = start + args.minibatch_size
267
+ mb_inds = b_inds[start:end]
268
+
269
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
270
+ logratio = newlogprob - b_logprobs[mb_inds]
271
+ ratio = logratio.exp()
272
+
273
+ with torch.no_grad():
274
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
275
+ old_approx_kl = (-logratio).mean()
276
+ approx_kl = ((ratio - 1) - logratio).mean()
277
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
278
+
279
+ mb_advantages = b_advantages[mb_inds]
280
+ if args.norm_adv:
281
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
282
+
283
+ # Policy loss
284
+ pg_loss1 = -mb_advantages * ratio
285
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
286
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
287
+
288
+ # Value loss
289
+ newvalue = newvalue.view(-1)
290
+ if args.clip_vloss:
291
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
292
+ v_clipped = b_values[mb_inds] + torch.clamp(
293
+ newvalue - b_values[mb_inds],
294
+ -args.clip_coef,
295
+ args.clip_coef,
296
+ )
297
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
298
+ v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped)
299
+ v_loss = 0.5 * v_loss_max.mean()
300
+ else:
301
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
302
+
303
+ entropy_loss = entropy.mean()
304
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
305
+
306
+ optimizer.zero_grad()
307
+ loss.backward()
308
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
309
+ optimizer.step()
310
+
311
+ if args.target_kl is not None and approx_kl > args.target_kl:
312
+ break
313
+
314
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
315
+ var_y = np.var(y_true)
316
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
317
+
318
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
319
+ writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step)
320
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
321
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
322
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
323
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
324
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
325
+ writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step)
326
+ writer.add_scalar("losses/explained_variance", explained_var, global_step)
327
+
328
+ # Additional useful metrics
329
+ writer.add_scalar("charts/avg_reward", rewards.mean().item(), global_step)
330
+ writer.add_scalar("charts/avg_value", values.mean().item(), global_step)
331
+ writer.add_scalar("charts/max_reward", rewards.max().item(), global_step)
332
+ writer.add_scalar("charts/min_reward", rewards.min().item(), global_step)
333
+
334
+ # Console output with key metrics
335
+ sps = int(global_step / (time.time() - start_time))
336
+ progress = 100 * iteration / args.num_iterations
337
+ print(f"[{progress:5.1f}%] Iter {iteration:4d}/{args.num_iterations} | "
338
+ f"SPS: {sps:5d} | "
339
+ f"Reward: {rewards.mean().item():6.3f} | "
340
+ f"Value: {values.mean().item():6.3f} | "
341
+ f"VLoss: {v_loss.item():.4f} | "
342
+ f"PLoss: {pg_loss.item():.4f} | "
343
+ f"Ent: {entropy_loss.item():.4f}")
344
+ writer.add_scalar("charts/SPS", sps, global_step)
345
+
346
+ envs.close()
347
+ writer.close()
cleanrl/cleanrl/wandb/run-20251107_103331-e2e7wd2b/files/config.yaml ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _wandb:
2
+ value:
3
+ cli_version: 0.22.3
4
+ code_path: code/cleanrl/ppo_frozenlake.py
5
+ e:
6
+ e26crksekquh3exjmxygxro2irogd3e1:
7
+ args:
8
+ - --track
9
+ - --wandb-project-name
10
+ - ragen-bandit
11
+ codePath: cleanrl/ppo_frozenlake.py
12
+ codePathLocal: ppo_frozenlake.py
13
+ cpu_count: 64
14
+ cpu_count_logical: 128
15
+ cudaVersion: "12.4"
16
+ disk:
17
+ /:
18
+ total: "5153960755200"
19
+ used: "30509891584"
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_frozenlake.py
73
+ python: CPython 3.12.12
74
+ root: /mnt/general/wanghy/RAGEN/cleanrl/cleanrl
75
+ startedAt: "2025-11-07T02:33:31.320641Z"
76
+ writerId: e26crksekquh3exjmxygxro2irogd3e1
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: 1024
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: FrozenLake
114
+ exp_name:
115
+ value: ppo_frozenlake
116
+ gae_lambda:
117
+ value: 0.95
118
+ gamma:
119
+ value: 0.99
120
+ grid_size:
121
+ value: 4
122
+ is_slippery:
123
+ value: true
124
+ learning_rate:
125
+ value: 0.00025
126
+ max_grad_norm:
127
+ value: 0.5
128
+ minibatch_size:
129
+ value: 256
130
+ norm_adv:
131
+ value: true
132
+ num_envs:
133
+ value: 8
134
+ num_iterations:
135
+ value: 976
136
+ num_minibatches:
137
+ value: 4
138
+ num_steps:
139
+ value: 128
140
+ seed:
141
+ value: 1
142
+ target_kl:
143
+ value: null
144
+ torch_deterministic:
145
+ value: true
146
+ total_timesteps:
147
+ value: 1000000
148
+ track:
149
+ value: true
150
+ update_epochs:
151
+ value: 4
152
+ vf_coef:
153
+ value: 0.5
154
+ wandb_entity:
155
+ value: null
156
+ wandb_project_name:
157
+ value: ragen-bandit
cleanrl/cleanrl/wandb/run-20251107_103331-e2e7wd2b/files/output.log ADDED
The diff for this file is too large to render. See raw diff
 
cleanrl/cleanrl/wandb/run-20251107_103331-e2e7wd2b/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:33:31.320641Z",
5
+ "args": [
6
+ "--track",
7
+ "--wandb-project-name",
8
+ "ragen-bandit"
9
+ ],
10
+ "program": "/mnt/general/wanghy/RAGEN/cleanrl/cleanrl/ppo_frozenlake.py",
11
+ "codePath": "cleanrl/ppo_frozenlake.py",
12
+ "codePathLocal": "ppo_frozenlake.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": "30509891584"
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": "e26crksekquh3exjmxygxro2irogd3e1"
94
+ }
cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/files/code/cleanrl/ppo_sokoban.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PPO implementation for RAGEN Sokoban 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.sokoban.env import SokobanEnv
20
+ from ragen.env.sokoban.config import SokobanEnvConfig
21
+ from ragen_wrappers import SokobanWrapper
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 = "Sokoban"
45
+ """the id of the environment"""
46
+ total_timesteps: int = 5000000
47
+ """total timesteps of the experiments"""
48
+ learning_rate: float = 2.5e-4
49
+ """the learning rate of the optimizer"""
50
+ num_envs: int = 8
51
+ """the number of parallel game environments"""
52
+ num_steps: int = 128
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
+ # Sokoban specific
80
+ dim_room: tuple = (6, 6)
81
+ """dimensions of the sokoban room"""
82
+ num_boxes: int = 1
83
+ """number of boxes in sokoban"""
84
+ max_steps: int = 100
85
+ """maximum steps per episode"""
86
+ search_depth: int = 100
87
+ """search depth for sokoban level generation"""
88
+
89
+ # to be filled in runtime
90
+ batch_size: int = 0
91
+ """the batch size (computed in runtime)"""
92
+ minibatch_size: int = 0
93
+ """the mini-batch size (computed in runtime)"""
94
+ num_iterations: int = 0
95
+ """the number of iterations (computed in runtime)"""
96
+
97
+
98
+ def make_env(env_id, idx, capture_video, run_name, seed, dim_room, num_boxes, max_steps, search_depth):
99
+ def thunk():
100
+ config = SokobanEnvConfig(
101
+ dim_room=dim_room,
102
+ num_boxes=num_boxes,
103
+ max_steps=max_steps,
104
+ search_depth=search_depth
105
+ )
106
+ env = SokobanEnv(config)
107
+ env = SokobanWrapper(env)
108
+ env = gym.wrappers.RecordEpisodeStatistics(env)
109
+ if capture_video and idx == 0:
110
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
111
+ return env
112
+ return thunk
113
+
114
+
115
+ def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
116
+ torch.nn.init.orthogonal_(layer.weight, std)
117
+ torch.nn.init.constant_(layer.bias, bias_const)
118
+ return layer
119
+
120
+
121
+ class Agent(nn.Module):
122
+ def __init__(self, envs):
123
+ super().__init__()
124
+ obs_shape = np.array(envs.single_observation_space.shape).prod()
125
+ self.critic = nn.Sequential(
126
+ layer_init(nn.Linear(obs_shape, 256)),
127
+ nn.Tanh(),
128
+ layer_init(nn.Linear(256, 256)),
129
+ nn.Tanh(),
130
+ layer_init(nn.Linear(256, 1), std=1.0),
131
+ )
132
+ self.actor = nn.Sequential(
133
+ layer_init(nn.Linear(obs_shape, 256)),
134
+ nn.Tanh(),
135
+ layer_init(nn.Linear(256, 256)),
136
+ nn.Tanh(),
137
+ layer_init(nn.Linear(256, envs.single_action_space.n), std=0.01),
138
+ )
139
+
140
+ def get_value(self, x):
141
+ return self.critic(x)
142
+
143
+ def get_action_and_value(self, x, action=None):
144
+ logits = self.actor(x)
145
+ probs = Categorical(logits=logits)
146
+ if action is None:
147
+ action = probs.sample()
148
+ return action, probs.log_prob(action), probs.entropy(), self.critic(x)
149
+
150
+
151
+ if __name__ == "__main__":
152
+ args = tyro.cli(Args)
153
+ args.batch_size = int(args.num_envs * args.num_steps)
154
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
155
+ args.num_iterations = args.total_timesteps // args.batch_size
156
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
157
+ if args.track:
158
+ import wandb
159
+
160
+ wandb.init(
161
+ project=args.wandb_project_name,
162
+ entity=args.wandb_entity,
163
+ sync_tensorboard=True,
164
+ config=vars(args),
165
+ name=run_name,
166
+ monitor_gym=True,
167
+ save_code=True,
168
+ )
169
+ writer = SummaryWriter(f"runs/{run_name}")
170
+ writer.add_text(
171
+ "hyperparameters",
172
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
173
+ )
174
+
175
+ # TRY NOT TO MODIFY: seeding
176
+ random.seed(args.seed)
177
+ np.random.seed(args.seed)
178
+ torch.manual_seed(args.seed)
179
+ torch.backends.cudnn.deterministic = args.torch_deterministic
180
+
181
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
182
+
183
+ # env setup
184
+ envs = gym.vector.SyncVectorEnv(
185
+ [make_env(args.env_id, i, args.capture_video, run_name, args.seed,
186
+ args.dim_room, args.num_boxes, args.max_steps, args.search_depth)
187
+ for i in range(args.num_envs)],
188
+ )
189
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
190
+
191
+ agent = Agent(envs).to(device)
192
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
193
+
194
+ # ALGO Logic: Storage setup
195
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
196
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
197
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
198
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
199
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
200
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
201
+
202
+ # TRY NOT TO MODIFY: start the game
203
+ global_step = 0
204
+ start_time = time.time()
205
+ next_obs, _ = envs.reset(seed=args.seed)
206
+ next_obs = torch.Tensor(next_obs).to(device)
207
+ next_done = torch.zeros(args.num_envs).to(device)
208
+
209
+ for iteration in range(1, args.num_iterations + 1):
210
+ # Annealing the rate if instructed to do so.
211
+ if args.anneal_lr:
212
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
213
+ lrnow = frac * args.learning_rate
214
+ optimizer.param_groups[0]["lr"] = lrnow
215
+
216
+ for step in range(0, args.num_steps):
217
+ global_step += args.num_envs
218
+ obs[step] = next_obs
219
+ dones[step] = next_done
220
+
221
+ # ALGO LOGIC: action logic
222
+ with torch.no_grad():
223
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
224
+ values[step] = value.flatten()
225
+ actions[step] = action
226
+ logprobs[step] = logprob
227
+
228
+ # TRY NOT TO MODIFY: execute the game and log data.
229
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
230
+ next_done = np.logical_or(terminations, truncations)
231
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
232
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
233
+
234
+ if "final_info" in infos:
235
+ for info in infos["final_info"]:
236
+ if info and "episode" in info:
237
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
238
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
239
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
240
+
241
+ # bootstrap value if not done
242
+ with torch.no_grad():
243
+ next_value = agent.get_value(next_obs).reshape(1, -1)
244
+ advantages = torch.zeros_like(rewards).to(device)
245
+ lastgaelam = 0
246
+ for t in reversed(range(args.num_steps)):
247
+ if t == args.num_steps - 1:
248
+ nextnonterminal = 1.0 - next_done
249
+ nextvalues = next_value
250
+ else:
251
+ nextnonterminal = 1.0 - dones[t + 1]
252
+ nextvalues = values[t + 1]
253
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
254
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
255
+ returns = advantages + values
256
+
257
+ # flatten the batch
258
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
259
+ b_logprobs = logprobs.reshape(-1)
260
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
261
+ b_advantages = advantages.reshape(-1)
262
+ b_returns = returns.reshape(-1)
263
+ b_values = values.reshape(-1)
264
+
265
+ # Optimizing the policy and value network
266
+ b_inds = np.arange(args.batch_size)
267
+ clipfracs = []
268
+ for epoch in range(args.update_epochs):
269
+ np.random.shuffle(b_inds)
270
+ for start in range(0, args.batch_size, args.minibatch_size):
271
+ end = start + args.minibatch_size
272
+ mb_inds = b_inds[start:end]
273
+
274
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
275
+ logratio = newlogprob - b_logprobs[mb_inds]
276
+ ratio = logratio.exp()
277
+
278
+ with torch.no_grad():
279
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
280
+ old_approx_kl = (-logratio).mean()
281
+ approx_kl = ((ratio - 1) - logratio).mean()
282
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
283
+
284
+ mb_advantages = b_advantages[mb_inds]
285
+ if args.norm_adv:
286
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
287
+
288
+ # Policy loss
289
+ pg_loss1 = -mb_advantages * ratio
290
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
291
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
292
+
293
+ # Value loss
294
+ newvalue = newvalue.view(-1)
295
+ if args.clip_vloss:
296
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
297
+ v_clipped = b_values[mb_inds] + torch.clamp(
298
+ newvalue - b_values[mb_inds],
299
+ -args.clip_coef,
300
+ args.clip_coef,
301
+ )
302
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
303
+ v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped)
304
+ v_loss = 0.5 * v_loss_max.mean()
305
+ else:
306
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
307
+
308
+ entropy_loss = entropy.mean()
309
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
310
+
311
+ optimizer.zero_grad()
312
+ loss.backward()
313
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
314
+ optimizer.step()
315
+
316
+ if args.target_kl is not None and approx_kl > args.target_kl:
317
+ break
318
+
319
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
320
+ var_y = np.var(y_true)
321
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
322
+
323
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
324
+ writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step)
325
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
326
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
327
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
328
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
329
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
330
+ writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step)
331
+ writer.add_scalar("losses/explained_variance", explained_var, global_step)
332
+
333
+ # Additional useful metrics
334
+ writer.add_scalar("charts/avg_reward", rewards.mean().item(), global_step)
335
+ writer.add_scalar("charts/avg_value", values.mean().item(), global_step)
336
+ writer.add_scalar("charts/max_reward", rewards.max().item(), global_step)
337
+ writer.add_scalar("charts/min_reward", rewards.min().item(), global_step)
338
+
339
+ # Console output with key metrics
340
+ sps = int(global_step / (time.time() - start_time))
341
+ progress = 100 * iteration / args.num_iterations
342
+ print(f"[{progress:5.1f}%] Iter {iteration:4d}/{args.num_iterations} | "
343
+ f"SPS: {sps:5d} | "
344
+ f"Reward: {rewards.mean().item():6.3f} | "
345
+ f"Value: {values.mean().item():6.3f} | "
346
+ f"VLoss: {v_loss.item():.4f} | "
347
+ f"PLoss: {pg_loss.item():.4f} | "
348
+ f"Ent: {entropy_loss.item():.4f}")
349
+ writer.add_scalar("charts/SPS", sps, global_step)
350
+
351
+ envs.close()
352
+ writer.close()
cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/files/config.yaml ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _wandb:
2
+ value:
3
+ cli_version: 0.22.3
4
+ code_path: code/cleanrl/ppo_sokoban.py
5
+ e:
6
+ z96hq3pus2sxc7xhydj92rmnpv0sy2t0:
7
+ args:
8
+ - --track
9
+ - --wandb-project-name
10
+ - ragen-sokoban
11
+ codePath: cleanrl/ppo_sokoban.py
12
+ codePathLocal: ppo_sokoban.py
13
+ cpu_count: 64
14
+ cpu_count_logical: 128
15
+ cudaVersion: "12.4"
16
+ disk:
17
+ /:
18
+ total: "5153960755200"
19
+ used: "31672418304"
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_sokoban.py
73
+ python: CPython 3.12.12
74
+ root: /mnt/general/wanghy/RAGEN/cleanrl/cleanrl
75
+ startedAt: "2025-11-07T03:26:47.139012Z"
76
+ writerId: z96hq3pus2sxc7xhydj92rmnpv0sy2t0
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: 1024
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
+ dim_room:
111
+ value:
112
+ - 6
113
+ - 6
114
+ ent_coef:
115
+ value: 0.01
116
+ env_id:
117
+ value: Sokoban
118
+ exp_name:
119
+ value: ppo_sokoban
120
+ gae_lambda:
121
+ value: 0.95
122
+ gamma:
123
+ value: 0.99
124
+ learning_rate:
125
+ value: 0.00025
126
+ max_grad_norm:
127
+ value: 0.5
128
+ max_steps:
129
+ value: 100
130
+ minibatch_size:
131
+ value: 256
132
+ norm_adv:
133
+ value: true
134
+ num_boxes:
135
+ value: 1
136
+ num_envs:
137
+ value: 8
138
+ num_iterations:
139
+ value: 4882
140
+ num_minibatches:
141
+ value: 4
142
+ num_steps:
143
+ value: 128
144
+ search_depth:
145
+ value: 100
146
+ seed:
147
+ value: 1
148
+ target_kl:
149
+ value: null
150
+ torch_deterministic:
151
+ value: true
152
+ total_timesteps:
153
+ value: 5000000
154
+ track:
155
+ value: true
156
+ update_epochs:
157
+ value: 4
158
+ vf_coef:
159
+ value: 0.5
160
+ wandb_entity:
161
+ value: null
162
+ wandb_project_name:
163
+ value: ragen-sokoban
cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/files/output.log ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Traceback (most recent call last):
2
+ File "/mnt/general/wanghy/RAGEN/cleanrl/cleanrl/ppo_sokoban.py", line 184, in <module>
3
+ envs = gym.vector.SyncVectorEnv(
4
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
5
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/gymnasium/vector/sync_vector_env.py", line 97, in __init__
6
+ self.envs = [env_fn() for env_fn in env_fns]
7
+ ^^^^^^^^
8
+ File "/mnt/general/wanghy/RAGEN/cleanrl/cleanrl/ppo_sokoban.py", line 108, in thunk
9
+ env = gym.wrappers.RecordEpisodeStatistics(env)
10
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
11
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/gymnasium/wrappers/common.py", line 496, in __init__
12
+ gym.Wrapper.__init__(self, env)
13
+ File "/root/local/miniconda3/envs/ragen/lib/python3.12/site-packages/gymnasium/core.py", line 313, in __init__
14
+ assert isinstance(
15
+ ^^^^^^^^^^^
16
+ AssertionError: Expected env to be a `gymnasium.Env` but got <class 'ragen_wrappers.SokobanWrapper'>
cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/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_112647-9utis4xx/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-07T03:26:47.139012Z",
5
+ "args": [
6
+ "--track",
7
+ "--wandb-project-name",
8
+ "ragen-sokoban"
9
+ ],
10
+ "program": "/mnt/general/wanghy/RAGEN/cleanrl/cleanrl/ppo_sokoban.py",
11
+ "codePath": "cleanrl/ppo_sokoban.py",
12
+ "codePathLocal": "ppo_sokoban.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": "31672418304"
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": "z96hq3pus2sxc7xhydj92rmnpv0sy2t0"
94
+ }
cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/logs/debug.log ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2025-11-07 11:26:47,186 INFO MainThread:212707 [wandb_setup.py:_flush():81] Current SDK version is 0.22.3
2
+ 2025-11-07 11:26:47,186 INFO MainThread:212707 [wandb_setup.py:_flush():81] Configure stats pid to 212707
3
+ 2025-11-07 11:26:47,186 INFO MainThread:212707 [wandb_setup.py:_flush():81] Loading settings from /root/.config/wandb/settings
4
+ 2025-11-07 11:26:47,186 INFO MainThread:212707 [wandb_setup.py:_flush():81] Loading settings from /mnt/general/wanghy/RAGEN/cleanrl/cleanrl/wandb/settings
5
+ 2025-11-07 11:26:47,187 INFO MainThread:212707 [wandb_setup.py:_flush():81] Loading settings from environment variables
6
+ 2025-11-07 11:26:47,187 INFO MainThread:212707 [wandb_init.py:setup_run_log_directory():706] Logging user logs to /mnt/general/wanghy/RAGEN/cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/logs/debug.log
7
+ 2025-11-07 11:26:47,187 INFO MainThread:212707 [wandb_init.py:setup_run_log_directory():707] Logging internal logs to /mnt/general/wanghy/RAGEN/cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/logs/debug-internal.log
8
+ 2025-11-07 11:26:47,189 INFO MainThread:212707 [wandb_init.py:init():833] calling init triggers
9
+ 2025-11-07 11:26:47,189 INFO MainThread:212707 [wandb_init.py:init():838] wandb.init called with sweep_config: {}
10
+ config: {'exp_name': 'ppo_sokoban', 'seed': 1, 'torch_deterministic': True, 'cuda': True, 'track': True, 'wandb_project_name': 'ragen-sokoban', 'wandb_entity': None, 'capture_video': False, 'env_id': 'Sokoban', 'total_timesteps': 5000000, 'learning_rate': 0.00025, 'num_envs': 8, 'num_steps': 128, '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, 'dim_room': (6, 6), 'num_boxes': 1, 'max_steps': 100, 'search_depth': 100, 'batch_size': 1024, 'minibatch_size': 256, 'num_iterations': 4882, '_wandb': {'code_path': 'code/cleanrl/ppo_sokoban.py'}}
11
+ 2025-11-07 11:26:47,189 INFO MainThread:212707 [wandb_init.py:init():881] starting backend
12
+ 2025-11-07 11:26:47,395 INFO MainThread:212707 [wandb_init.py:init():884] sending inform_init request
13
+ 2025-11-07 11:26:47,406 INFO MainThread:212707 [wandb_init.py:init():892] backend started and connected
14
+ 2025-11-07 11:26:47,407 INFO MainThread:212707 [wandb_init.py:init():962] updated telemetry
15
+ 2025-11-07 11:26:47,441 INFO MainThread:212707 [wandb_init.py:init():986] communicating run to backend with 90.0 second timeout
16
+ 2025-11-07 11:26:48,271 INFO MainThread:212707 [wandb_init.py:init():1033] starting run threads in backend
17
+ 2025-11-07 11:26:48,414 INFO MainThread:212707 [wandb_run.py:_console_start():2506] atexit reg
18
+ 2025-11-07 11:26:48,414 INFO MainThread:212707 [wandb_run.py:_redirect():2354] redirect: wrap_raw
19
+ 2025-11-07 11:26:48,415 INFO MainThread:212707 [wandb_run.py:_redirect():2423] Wrapping output streams.
20
+ 2025-11-07 11:26:48,415 INFO MainThread:212707 [wandb_run.py:_redirect():2446] Redirects installed.
21
+ 2025-11-07 11:26:48,417 INFO MainThread:212707 [wandb_init.py:init():1073] run started, returning control to user process
22
+ 2025-11-07 11:26:48,417 INFO MainThread:212707 [wandb_run.py:_tensorboard_callback():1598] tensorboard callback: runs/Sokoban__ppo_sokoban__1__1762486000, True
23
+ 2025-11-07 11:26:48,527 INFO wandb-AsyncioManager-main:212707 [service_client.py:_forward_responses():80] Reached EOF.
24
+ 2025-11-07 11:26:48,527 INFO wandb-AsyncioManager-main:212707 [mailbox.py:close():137] Closing mailbox, abandoning 2 handles.
cleanrl/cleanrl/wandb/run-20251107_112647-9utis4xx/run-9utis4xx.wandb ADDED
Binary file (4.68 kB). View file
 
cleanrl/cleanrl/wandb/run-20251107_112903-8xop3upl/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-07T03:29:03.539841Z",
5
+ "args": [
6
+ "--track",
7
+ "--wandb-project-name",
8
+ "ragen-bandit"
9
+ ],
10
+ "program": "/mnt/general/wanghy/RAGEN/cleanrl/cleanrl/ppo_frozenlake.py",
11
+ "codePath": "cleanrl/ppo_frozenlake.py",
12
+ "codePathLocal": "ppo_frozenlake.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": "31673995264"
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": "27m01iw4c1djia38oq0povle1209kj1y"
94
+ }
cleanrl/cleanrl/wandb/run-20251107_113856-k31oio6c/files/code/cleanrl/ppo_frozenlake.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PPO implementation for RAGEN FrozenLake 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.frozen_lake.env import FrozenLakeEnv
20
+ from ragen.env.frozen_lake.config import FrozenLakeEnvConfig
21
+ from ragen_wrappers import FrozenLakeWrapper
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 = "FrozenLake"
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 = 8
51
+ """the number of parallel game environments"""
52
+ num_steps: int = 128
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
+ # FrozenLake specific
80
+ grid_size: int = 4
81
+ """size of the frozen lake grid"""
82
+ is_slippery: bool = True
83
+ """whether the ice is slippery"""
84
+
85
+ # to be filled in runtime
86
+ batch_size: int = 0
87
+ """the batch size (computed in runtime)"""
88
+ minibatch_size: int = 0
89
+ """the mini-batch size (computed in runtime)"""
90
+ num_iterations: int = 0
91
+ """the number of iterations (computed in runtime)"""
92
+
93
+
94
+ def make_env(env_id, idx, capture_video, run_name, seed, grid_size, is_slippery):
95
+ def thunk():
96
+ config = FrozenLakeEnvConfig(
97
+ size=grid_size,
98
+ p=0.8,
99
+ is_slippery=is_slippery,
100
+ map_seed=seed + idx
101
+ )
102
+ env = FrozenLakeEnv(config)
103
+ env = FrozenLakeWrapper(env)
104
+ env = gym.wrappers.RecordEpisodeStatistics(env)
105
+ if capture_video and idx == 0:
106
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
107
+ return env
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
+ obs_shape = np.array(envs.single_observation_space.shape).prod()
121
+ self.critic = nn.Sequential(
122
+ layer_init(nn.Linear(obs_shape, 128)),
123
+ nn.Tanh(),
124
+ layer_init(nn.Linear(128, 128)),
125
+ nn.Tanh(),
126
+ layer_init(nn.Linear(128, 1), std=1.0),
127
+ )
128
+ self.actor = nn.Sequential(
129
+ layer_init(nn.Linear(obs_shape, 128)),
130
+ nn.Tanh(),
131
+ layer_init(nn.Linear(128, 128)),
132
+ nn.Tanh(),
133
+ layer_init(nn.Linear(128, envs.single_action_space.n), std=0.01),
134
+ )
135
+
136
+ def get_value(self, x):
137
+ return self.critic(x)
138
+
139
+ def get_action_and_value(self, x, action=None):
140
+ logits = self.actor(x)
141
+ probs = Categorical(logits=logits)
142
+ if action is None:
143
+ action = probs.sample()
144
+ return action, probs.log_prob(action), probs.entropy(), self.critic(x)
145
+
146
+
147
+ if __name__ == "__main__":
148
+ args = tyro.cli(Args)
149
+ args.batch_size = int(args.num_envs * args.num_steps)
150
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
151
+ args.num_iterations = args.total_timesteps // args.batch_size
152
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
153
+ if args.track:
154
+ import wandb
155
+
156
+ wandb.init(
157
+ project=args.wandb_project_name,
158
+ entity=args.wandb_entity,
159
+ sync_tensorboard=True,
160
+ config=vars(args),
161
+ name=run_name,
162
+ monitor_gym=True,
163
+ save_code=True,
164
+ )
165
+ writer = SummaryWriter(f"runs/{run_name}")
166
+ writer.add_text(
167
+ "hyperparameters",
168
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
169
+ )
170
+
171
+ # TRY NOT TO MODIFY: seeding
172
+ random.seed(args.seed)
173
+ np.random.seed(args.seed)
174
+ torch.manual_seed(args.seed)
175
+ torch.backends.cudnn.deterministic = args.torch_deterministic
176
+
177
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
178
+
179
+ # env setup
180
+ envs = gym.vector.SyncVectorEnv(
181
+ [make_env(args.env_id, i, args.capture_video, run_name, args.seed, args.grid_size, args.is_slippery)
182
+ for i in range(args.num_envs)],
183
+ )
184
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
185
+
186
+ agent = Agent(envs).to(device)
187
+ optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)
188
+
189
+ # ALGO Logic: Storage setup
190
+ obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
191
+ actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
192
+ logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device)
193
+ rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
194
+ dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
195
+ values = torch.zeros((args.num_steps, args.num_envs)).to(device)
196
+
197
+ # TRY NOT TO MODIFY: start the game
198
+ global_step = 0
199
+ start_time = time.time()
200
+ next_obs, _ = envs.reset(seed=args.seed)
201
+ next_obs = torch.Tensor(next_obs).to(device)
202
+ next_done = torch.zeros(args.num_envs).to(device)
203
+
204
+ for iteration in range(1, args.num_iterations + 1):
205
+ # Annealing the rate if instructed to do so.
206
+ if args.anneal_lr:
207
+ frac = 1.0 - (iteration - 1.0) / args.num_iterations
208
+ lrnow = frac * args.learning_rate
209
+ optimizer.param_groups[0]["lr"] = lrnow
210
+
211
+ for step in range(0, args.num_steps):
212
+ global_step += args.num_envs
213
+ obs[step] = next_obs
214
+ dones[step] = next_done
215
+
216
+ # ALGO LOGIC: action logic
217
+ with torch.no_grad():
218
+ action, logprob, _, value = agent.get_action_and_value(next_obs)
219
+ values[step] = value.flatten()
220
+ actions[step] = action
221
+ logprobs[step] = logprob
222
+
223
+ # TRY NOT TO MODIFY: execute the game and log data.
224
+ next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
225
+ next_done = np.logical_or(terminations, truncations)
226
+ rewards[step] = torch.tensor(reward).to(device).view(-1)
227
+ next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(next_done).to(device)
228
+
229
+ if "final_info" in infos:
230
+ for info in infos["final_info"]:
231
+ if info and "episode" in info:
232
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
233
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
234
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
235
+
236
+ # bootstrap value if not done
237
+ with torch.no_grad():
238
+ next_value = agent.get_value(next_obs).reshape(1, -1)
239
+ advantages = torch.zeros_like(rewards).to(device)
240
+ lastgaelam = 0
241
+ for t in reversed(range(args.num_steps)):
242
+ if t == args.num_steps - 1:
243
+ nextnonterminal = 1.0 - next_done
244
+ nextvalues = next_value
245
+ else:
246
+ nextnonterminal = 1.0 - dones[t + 1]
247
+ nextvalues = values[t + 1]
248
+ delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
249
+ advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
250
+ returns = advantages + values
251
+
252
+ # flatten the batch
253
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
254
+ b_logprobs = logprobs.reshape(-1)
255
+ b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
256
+ b_advantages = advantages.reshape(-1)
257
+ b_returns = returns.reshape(-1)
258
+ b_values = values.reshape(-1)
259
+
260
+ # Optimizing the policy and value network
261
+ b_inds = np.arange(args.batch_size)
262
+ clipfracs = []
263
+ for epoch in range(args.update_epochs):
264
+ np.random.shuffle(b_inds)
265
+ for start in range(0, args.batch_size, args.minibatch_size):
266
+ end = start + args.minibatch_size
267
+ mb_inds = b_inds[start:end]
268
+
269
+ _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds])
270
+ logratio = newlogprob - b_logprobs[mb_inds]
271
+ ratio = logratio.exp()
272
+
273
+ with torch.no_grad():
274
+ # calculate approx_kl http://joschu.net/blog/kl-approx.html
275
+ old_approx_kl = (-logratio).mean()
276
+ approx_kl = ((ratio - 1) - logratio).mean()
277
+ clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()]
278
+
279
+ mb_advantages = b_advantages[mb_inds]
280
+ if args.norm_adv:
281
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
282
+
283
+ # Policy loss
284
+ pg_loss1 = -mb_advantages * ratio
285
+ pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
286
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
287
+
288
+ # Value loss
289
+ newvalue = newvalue.view(-1)
290
+ if args.clip_vloss:
291
+ v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
292
+ v_clipped = b_values[mb_inds] + torch.clamp(
293
+ newvalue - b_values[mb_inds],
294
+ -args.clip_coef,
295
+ args.clip_coef,
296
+ )
297
+ v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
298
+ v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped)
299
+ v_loss = 0.5 * v_loss_max.mean()
300
+ else:
301
+ v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()
302
+
303
+ entropy_loss = entropy.mean()
304
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
305
+
306
+ optimizer.zero_grad()
307
+ loss.backward()
308
+ nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
309
+ optimizer.step()
310
+
311
+ if args.target_kl is not None and approx_kl > args.target_kl:
312
+ break
313
+
314
+ y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy()
315
+ var_y = np.var(y_true)
316
+ explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y
317
+
318
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
319
+ writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step)
320
+ writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
321
+ writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
322
+ writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
323
+ writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
324
+ writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
325
+ writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step)
326
+ writer.add_scalar("losses/explained_variance", explained_var, global_step)
327
+
328
+ # Additional useful metrics
329
+ writer.add_scalar("charts/avg_reward", rewards.mean().item(), global_step)
330
+ writer.add_scalar("charts/avg_value", values.mean().item(), global_step)
331
+ writer.add_scalar("charts/max_reward", rewards.max().item(), global_step)
332
+ writer.add_scalar("charts/min_reward", rewards.min().item(), global_step)
333
+
334
+ # Console output with key metrics
335
+ sps = int(global_step / (time.time() - start_time))
336
+ progress = 100 * iteration / args.num_iterations
337
+ print(f"[{progress:5.1f}%] Iter {iteration:4d}/{args.num_iterations} | "
338
+ f"SPS: {sps:5d} | "
339
+ f"Reward: {rewards.mean().item():6.3f} | "
340
+ f"Value: {values.mean().item():6.3f} | "
341
+ f"VLoss: {v_loss.item():.4f} | "
342
+ f"PLoss: {pg_loss.item():.4f} | "
343
+ f"Ent: {entropy_loss.item():.4f}")
344
+ writer.add_scalar("charts/SPS", sps, global_step)
345
+
346
+ envs.close()
347
+ writer.close()
cleanrl/cleanrl/wandb/run-20251107_113856-k31oio6c/files/output.log ADDED
The diff for this file is too large to render. See raw diff
 
cleanrl/cleanrl/wandb/run-20251107_113856-k31oio6c/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-07T03:38:56.139668Z",
5
+ "args": [
6
+ "--track",
7
+ "--wandb-project-name",
8
+ "ragen-bandit"
9
+ ],
10
+ "program": "/mnt/general/wanghy/RAGEN/cleanrl/cleanrl/ppo_frozenlake.py",
11
+ "codePath": "cleanrl/ppo_frozenlake.py",
12
+ "codePathLocal": "ppo_frozenlake.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": "31684485120"
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": "qcnee8s40otwmmxavjc9wsiwf1cq85oc"
94
+ }
cleanrl/cleanrl/wandb/run-20251107_113856-k31oio6c/logs/debug-internal.log ADDED
The diff for this file is too large to render. See raw diff
 
cleanrl/cleanrl/wandb/run-20251107_113856-k31oio6c/logs/debug.log ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2025-11-07 11:38:56,186 INFO MainThread:214168 [wandb_setup.py:_flush():81] Current SDK version is 0.22.3
2
+ 2025-11-07 11:38:56,186 INFO MainThread:214168 [wandb_setup.py:_flush():81] Configure stats pid to 214168
3
+ 2025-11-07 11:38:56,186 INFO MainThread:214168 [wandb_setup.py:_flush():81] Loading settings from /root/.config/wandb/settings
4
+ 2025-11-07 11:38:56,186 INFO MainThread:214168 [wandb_setup.py:_flush():81] Loading settings from /mnt/general/wanghy/RAGEN/cleanrl/cleanrl/wandb/settings
5
+ 2025-11-07 11:38:56,186 INFO MainThread:214168 [wandb_setup.py:_flush():81] Loading settings from environment variables
6
+ 2025-11-07 11:38:56,187 INFO MainThread:214168 [wandb_init.py:setup_run_log_directory():706] Logging user logs to /mnt/general/wanghy/RAGEN/cleanrl/cleanrl/wandb/run-20251107_113856-k31oio6c/logs/debug.log
7
+ 2025-11-07 11:38:56,187 INFO MainThread:214168 [wandb_init.py:setup_run_log_directory():707] Logging internal logs to /mnt/general/wanghy/RAGEN/cleanrl/cleanrl/wandb/run-20251107_113856-k31oio6c/logs/debug-internal.log
8
+ 2025-11-07 11:38:56,188 INFO MainThread:214168 [wandb_init.py:init():833] calling init triggers
9
+ 2025-11-07 11:38:56,188 INFO MainThread:214168 [wandb_init.py:init():838] wandb.init called with sweep_config: {}
10
+ config: {'exp_name': 'ppo_frozenlake', 'seed': 1, 'torch_deterministic': True, 'cuda': True, 'track': True, 'wandb_project_name': 'ragen-bandit', 'wandb_entity': None, 'capture_video': False, 'env_id': 'FrozenLake', 'total_timesteps': 10000000, 'learning_rate': 0.00025, 'num_envs': 8, 'num_steps': 128, '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, 'grid_size': 4, 'is_slippery': True, 'batch_size': 1024, 'minibatch_size': 256, 'num_iterations': 9765, '_wandb': {'code_path': 'code/cleanrl/ppo_frozenlake.py'}}
11
+ 2025-11-07 11:38:56,188 INFO MainThread:214168 [wandb_init.py:init():881] starting backend
12
+ 2025-11-07 11:38:56,395 INFO MainThread:214168 [wandb_init.py:init():884] sending inform_init request
13
+ 2025-11-07 11:38:56,406 INFO MainThread:214168 [wandb_init.py:init():892] backend started and connected
14
+ 2025-11-07 11:38:56,408 INFO MainThread:214168 [wandb_init.py:init():962] updated telemetry
15
+ 2025-11-07 11:38:56,438 INFO MainThread:214168 [wandb_init.py:init():986] communicating run to backend with 90.0 second timeout
16
+ 2025-11-07 11:38:57,166 INFO MainThread:214168 [wandb_init.py:init():1033] starting run threads in backend
17
+ 2025-11-07 11:38:57,309 INFO MainThread:214168 [wandb_run.py:_console_start():2506] atexit reg
18
+ 2025-11-07 11:38:57,310 INFO MainThread:214168 [wandb_run.py:_redirect():2354] redirect: wrap_raw
19
+ 2025-11-07 11:38:57,310 INFO MainThread:214168 [wandb_run.py:_redirect():2423] Wrapping output streams.
20
+ 2025-11-07 11:38:57,310 INFO MainThread:214168 [wandb_run.py:_redirect():2446] Redirects installed.
21
+ 2025-11-07 11:38:57,312 INFO MainThread:214168 [wandb_init.py:init():1073] run started, returning control to user process
22
+ 2025-11-07 11:38:57,312 INFO MainThread:214168 [wandb_run.py:_tensorboard_callback():1598] tensorboard callback: runs/FrozenLake__ppo_frozenlake__1__1762486729, True
23
+ 2025-11-07 12:38:45,543 INFO wandb-AsyncioManager-main:214168 [service_client.py:_forward_responses():80] Reached EOF.
24
+ 2025-11-07 12:38:45,543 INFO wandb-AsyncioManager-main:214168 [mailbox.py:close():137] Closing mailbox, abandoning 1 handles.
cleanrl/cleanrl/wandb/run-20251107_125210-py6fnjml/files/code/cleanrl/dqn_bandit.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from ragen_wrappers import BanditWrapper
24
+
25
+
26
+ @dataclass
27
+ class Args:
28
+ exp_name: str = os.path.basename(__file__)[: -len(".py")]
29
+ """the name of this experiment"""
30
+ seed: int = 1
31
+ """seed of the experiment"""
32
+ torch_deterministic: bool = True
33
+ """if toggled, `torch.backends.cudnn.deterministic=False`"""
34
+ cuda: bool = True
35
+ """if toggled, cuda will be enabled by default"""
36
+ track: bool = False
37
+ """if toggled, this experiment will be tracked with Weights and Biases"""
38
+ wandb_project_name: str = "cleanRL"
39
+ """the wandb's project name"""
40
+ wandb_entity: str = None
41
+ """the entity (team) of wandb's project"""
42
+ capture_video: bool = False
43
+ """whether to capture videos of the agent performances (check out `videos` folder)"""
44
+ save_model: bool = False
45
+ """whether to save model into the `runs/{run_name}` folder"""
46
+
47
+ # Algorithm specific arguments
48
+ env_id: str = "Bandit"
49
+ """the id of the environment"""
50
+ total_timesteps: int = 100000
51
+ """total timesteps of the experiments"""
52
+ learning_rate: float = 1e-3
53
+ """the learning rate of the optimizer"""
54
+ num_envs: int = 1
55
+ """the number of parallel game environments (DQN typically uses 1)"""
56
+ buffer_size: int = 10000
57
+ """the replay memory buffer size"""
58
+ gamma: float = 0.0
59
+ """the discount factor gamma (0 for bandit since it's single-step)"""
60
+ tau: float = 1.0
61
+ """the target network update rate"""
62
+ target_network_frequency: int = 500
63
+ """the timesteps it takes to update the target network"""
64
+ batch_size: int = 32
65
+ """the batch size of sample from the reply memory"""
66
+ start_e: float = 1.0
67
+ """the starting epsilon for exploration"""
68
+ end_e: float = 0.05
69
+ """the ending epsilon for exploration"""
70
+ exploration_fraction: float = 0.5
71
+ """the fraction of `total-timesteps` it takes from start-e to go end-e"""
72
+ learning_starts: int = 1000
73
+ """timestep to start learning"""
74
+ train_frequency: int = 1
75
+ """the frequency of training"""
76
+ steps_per_episode: int = 10
77
+ """number of steps per episode for multi-step bandit"""
78
+
79
+
80
+ def make_env(env_id, idx, capture_video, run_name, seed, steps_per_episode):
81
+ def thunk():
82
+ config = BanditEnvConfig()
83
+ env = BanditEnv(config)
84
+ env = BanditWrapper(env, steps_per_episode=steps_per_episode)
85
+ env = gym.wrappers.RecordEpisodeStatistics(env)
86
+ if capture_video and idx == 0:
87
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
88
+ return env
89
+ return thunk
90
+
91
+
92
+ # ALGO LOGIC: initialize agent here:
93
+ class QNetwork(nn.Module):
94
+ """
95
+ Q-Network for Bandit environment.
96
+ Input: [arm0_pulls, arm0_avg_reward, arm1_pulls, arm1_avg_reward]
97
+ Output: Q-values for each arm
98
+ """
99
+ def __init__(self, env):
100
+ super().__init__()
101
+ obs_shape = np.array(env.single_observation_space.shape).prod()
102
+ self.network = nn.Sequential(
103
+ nn.Linear(obs_shape, 128),
104
+ nn.ReLU(),
105
+ nn.Linear(128, 128),
106
+ nn.ReLU(),
107
+ nn.Linear(128, env.single_action_space.n),
108
+ )
109
+
110
+ def forward(self, x):
111
+ return self.network(x)
112
+
113
+
114
+ def linear_schedule(start_e: float, end_e: float, duration: int, t: int):
115
+ slope = (end_e - start_e) / duration
116
+ return max(slope * t + start_e, end_e)
117
+
118
+
119
+ if __name__ == "__main__":
120
+ args = tyro.cli(Args)
121
+ assert args.num_envs == 1, "vectorized envs are not supported at the moment"
122
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
123
+
124
+ if args.track:
125
+ import wandb
126
+
127
+ wandb.init(
128
+ project=args.wandb_project_name,
129
+ entity=args.wandb_entity,
130
+ sync_tensorboard=True,
131
+ config=vars(args),
132
+ name=run_name,
133
+ monitor_gym=True,
134
+ save_code=True,
135
+ )
136
+ writer = SummaryWriter(f"runs/{run_name}")
137
+ writer.add_text(
138
+ "hyperparameters",
139
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
140
+ )
141
+
142
+ # TRY NOT TO MODIFY: seeding
143
+ random.seed(args.seed)
144
+ np.random.seed(args.seed)
145
+ torch.manual_seed(args.seed)
146
+ torch.backends.cudnn.deterministic = args.torch_deterministic
147
+
148
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
149
+
150
+ # env setup
151
+ envs = gym.vector.SyncVectorEnv(
152
+ [make_env(args.env_id, i, args.capture_video, run_name, args.seed + i, args.steps_per_episode)
153
+ for i in range(args.num_envs)]
154
+ )
155
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
156
+
157
+ q_network = QNetwork(envs).to(device)
158
+ optimizer = optim.Adam(q_network.parameters(), lr=args.learning_rate)
159
+ target_network = QNetwork(envs).to(device)
160
+ target_network.load_state_dict(q_network.state_dict())
161
+
162
+ # Use simple replay buffer (no special memory optimization needed for bandit)
163
+ from cleanrl_utils.buffers import ReplayBuffer
164
+ rb = ReplayBuffer(
165
+ args.buffer_size,
166
+ envs.single_observation_space,
167
+ envs.single_action_space,
168
+ device,
169
+ optimize_memory_usage=False,
170
+ handle_timeout_termination=False,
171
+ )
172
+
173
+ start_time = time.time()
174
+
175
+ # Track episode returns
176
+ episode_returns = []
177
+ recent_episode_returns = []
178
+
179
+ # TRY NOT TO MODIFY: start the game
180
+ obs, _ = envs.reset(seed=args.seed)
181
+ for global_step in range(args.total_timesteps):
182
+ # ALGO LOGIC: put action logic here
183
+ epsilon = linear_schedule(args.start_e, args.end_e, args.exploration_fraction * args.total_timesteps, global_step)
184
+ if random.random() < epsilon:
185
+ actions = np.array([envs.single_action_space.sample() for _ in range(envs.num_envs)])
186
+ else:
187
+ q_values = q_network(torch.Tensor(obs).to(device))
188
+ actions = torch.argmax(q_values, dim=1).cpu().numpy()
189
+
190
+ # TRY NOT TO MODIFY: execute the game and log data.
191
+ next_obs, rewards, terminations, truncations, infos = envs.step(actions)
192
+
193
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
194
+ if "final_info" in infos:
195
+ for info in infos["final_info"]:
196
+ if info and "episode" in info:
197
+ episode_return = info['episode']['r']
198
+ episode_length = info['episode']['l']
199
+ episode_returns.append(episode_return)
200
+ recent_episode_returns.append(episode_return)
201
+ if len(recent_episode_returns) > 10:
202
+ recent_episode_returns.pop(0)
203
+ writer.add_scalar("charts/episodic_return", episode_return, global_step)
204
+ writer.add_scalar("charts/episodic_length", episode_length, global_step)
205
+
206
+ # TRY NOT TO MODIFY: save data to reply buffer; handle `final_observation`
207
+ real_next_obs = next_obs.copy()
208
+ for idx, trunc in enumerate(truncations):
209
+ if trunc:
210
+ real_next_obs[idx] = infos["final_observation"][idx]
211
+ rb.add(obs, real_next_obs, actions, rewards, terminations, infos)
212
+
213
+ # TRY NOT TO MODIFY: CRUCIAL step easy to overlook
214
+ obs = next_obs
215
+
216
+ # ALGO LOGIC: training.
217
+ if global_step > args.learning_starts:
218
+ if global_step % args.train_frequency == 0:
219
+ data = rb.sample(args.batch_size)
220
+ with torch.no_grad():
221
+ target_max, _ = target_network(data.next_observations).max(dim=1)
222
+ td_target = data.rewards.flatten() + args.gamma * target_max * (1 - data.dones.flatten())
223
+ old_val = q_network(data.observations).gather(1, data.actions).squeeze()
224
+ loss = F.mse_loss(td_target, old_val)
225
+
226
+ if global_step % 100 == 0:
227
+ writer.add_scalar("losses/td_loss", loss, global_step)
228
+ writer.add_scalar("losses/q_values", old_val.mean().item(), global_step)
229
+ writer.add_scalar("charts/epsilon", epsilon, global_step)
230
+
231
+ # Console output with key metrics
232
+ sps = int(global_step / (time.time() - start_time))
233
+ progress = 100 * global_step / args.total_timesteps
234
+ avg_episode_return = np.mean(recent_episode_returns) if recent_episode_returns else 0.0
235
+
236
+ print(f"[{progress:5.1f}%] Step {global_step:6d}/{args.total_timesteps} | "
237
+ f"SPS: {sps:5d} | "
238
+ f"EpRet: {avg_episode_return:7.3f} | "
239
+ f"Loss: {loss.item():.4f} | "
240
+ f"Q-val: {old_val.mean().item():.4f} | "
241
+ f"Eps: {epsilon:.3f}")
242
+
243
+ writer.add_scalar("charts/SPS", sps, global_step)
244
+ if recent_episode_returns:
245
+ writer.add_scalar("charts/avg_episodic_return", avg_episode_return, global_step)
246
+
247
+ # optimize the model
248
+ optimizer.zero_grad()
249
+ loss.backward()
250
+ optimizer.step()
251
+
252
+ # update target network
253
+ if global_step % args.target_network_frequency == 0:
254
+ for target_network_param, q_network_param in zip(target_network.parameters(), q_network.parameters()):
255
+ target_network_param.data.copy_(
256
+ args.tau * q_network_param.data + (1.0 - args.tau) * target_network_param.data
257
+ )
258
+
259
+ if args.save_model:
260
+ model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
261
+ torch.save(q_network.state_dict(), model_path)
262
+ print(f"model saved to {model_path}")
263
+
264
+ envs.close()
265
+ writer.close()
266
+
267
+ print("\n" + "="*60)
268
+ print("Training Complete!")
269
+ print("="*60)
270
+ if episode_returns:
271
+ print(f"Final Average Episode Return (last 10): {np.mean(recent_episode_returns):.3f}")
272
+ print(f"Overall Average Episode Return: {np.mean(episode_returns):.3f}")
273
+ print(f"Best Episode Return: {max(episode_returns):.3f}")
274
+ print("="*60)
cleanrl/cleanrl/wandb/run-20251107_125210-py6fnjml/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
+ tkb6lq3xdk95jdrk8itil4tq7t5n4mli:
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: "31715360768"
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:52:10.930319Z"
76
+ writerId: tkb6lq3xdk95jdrk8itil4tq7t5n4mli
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
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