privateboss commited on
Commit
8ef51bf
·
verified ·
1 Parent(s): 9b3e70e

Upload 5 files

Browse files
Files changed (5) hide show
  1. Environment_Wrapper.py +74 -0
  2. PPO_Model.py +334 -0
  3. RaceCar.py +50 -0
  4. Train.py +96 -0
  5. Trained_Agent.py +83 -0
Environment_Wrapper.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #G
2
+ import gymnasium as gym
3
+ import numpy as np
4
+ from collections import deque
5
+ import cv2
6
+
7
+ class CarRacingEnvWrapper(gym.Wrapper):
8
+ def __init__(self, env, num_stack_frames=4, grayscale=True, resize_dim=(84, 84)):
9
+ super().__init__(env)
10
+ self.num_stack_frames = num_stack_frames
11
+ self.grayscale = grayscale
12
+ self.resize_dim = resize_dim
13
+
14
+ self.frames = deque(maxlen=num_stack_frames)
15
+
16
+ original_shape = self.env.observation_space.shape
17
+ if grayscale:
18
+
19
+ original_shape = original_shape[:-1]
20
+
21
+ if resize_dim:
22
+ self.observation_shape = (resize_dim[1], resize_dim[0])
23
+ else:
24
+ self.observation_shape = original_shape[:2]
25
+
26
+ self.observation_space = gym.spaces.Box(
27
+ low=0, high=255,
28
+ shape=(self.observation_shape[0], self.observation_shape[1], num_stack_frames),
29
+ dtype=np.uint8
30
+ )
31
+
32
+ self.OFF_TRACK_PENALTY_SCALE = 0.1
33
+ self.GRASS_COLOR_THRESHOLD = 180
34
+
35
+ def _preprocess_frame(self, frame):
36
+
37
+ if self.grayscale:
38
+ frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
39
+ if self.resize_dim:
40
+ frame = cv2.resize(frame, self.resize_dim, interpolation=cv2.INTER_AREA)
41
+ return frame
42
+
43
+ def reset(self, **kwargs):
44
+ observation, info = self.env.reset(**kwargs)
45
+ processed_frame = self._preprocess_frame(observation)
46
+
47
+ for _ in range(self.num_stack_frames):
48
+ self.frames.append(processed_frame)
49
+
50
+ stacked_frames = np.stack(self.frames, axis=-1)
51
+ return stacked_frames, info
52
+
53
+ def step(self, action):
54
+
55
+ observation, reward, terminated, truncated, info = self.env.step(action)
56
+
57
+ modified_reward = reward
58
+
59
+ is_on_grass = np.mean(observation[:, :, 1]) > self.GRASS_COLOR_THRESHOLD
60
+
61
+ if is_on_grass:
62
+ modified_reward -= self.OFF_TRACK_PENALTY_SCALE
63
+
64
+ info['is_on_grass'] = is_on_grass
65
+ info['original_reward'] = reward
66
+ info['modified_reward'] = modified_reward
67
+
68
+ processed_frame = self._preprocess_frame(observation)
69
+
70
+ self.frames.append(processed_frame)
71
+ stacked_frames = np.stack(self.frames, axis=-1)
72
+
73
+ return stacked_frames, modified_reward, terminated, truncated, info
74
+ #D
PPO_Model.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #O
2
+ import gymnasium as gym
3
+ import numpy as np
4
+ from collections import deque
5
+ import tensorflow as tf
6
+ from keras import optimizers
7
+ from keras.optimizers import Adam
8
+ import tensorflow_probability as tfp
9
+ import os
10
+ from datetime import datetime
11
+ import json
12
+ from RaceCar import ActorCritic
13
+ from Environment_Wrapper import CarRacingEnvWrapper
14
+
15
+ tfd = tfp.distributions
16
+
17
+ class PPOAgent:
18
+ def __init__(self, env_id="CarRacing-v3", num_envs=21,
19
+ gamma=0.99, lam=0.95, clip_epsilon=0.2,
20
+ actor_lr=3e-4, critic_lr=3e-4,
21
+ ppo_epochs=10, minibatches=4,
22
+ steps_per_batch=1024,
23
+ num_stack_frames=4, resize_dim=(84, 84), grayscale=True,
24
+ seed=42, log_dir="./ppo_logs",
25
+ entropy_coeff=0.001,
26
+ save_interval_timesteps=537600,
27
+ hidden_layer_sizes=[512, 512, 512]):
28
+
29
+ self.env_id = env_id
30
+ self.num_envs = num_envs
31
+ self.gamma = gamma
32
+ self.lam = lam
33
+ self.clip_epsilon = clip_epsilon
34
+ self.ppo_epochs = ppo_epochs
35
+ self.minibatches = minibatches
36
+ self.steps_per_batch = steps_per_batch
37
+ self.num_stack_frames = num_stack_frames
38
+ self.resize_dim = resize_dim
39
+ self.grayscale = grayscale
40
+ self.seed = seed
41
+ self.log_dir = log_dir
42
+ self.entropy_coeff = entropy_coeff
43
+ self.save_interval_timesteps = save_interval_timesteps
44
+ self.hidden_layer_sizes = hidden_layer_sizes
45
+
46
+ self.envs = self._make_vec_envs()
47
+ self.action_dim = self.envs.single_action_space.shape[0]
48
+ self.observation_shape = self.envs.single_observation_space.shape
49
+
50
+ self.model = ActorCritic(self.action_dim,
51
+ self.num_stack_frames,
52
+ self.resize_dim[1],
53
+ self.resize_dim[0],
54
+ hidden_layer_sizes=self.hidden_layer_sizes)
55
+ self.actor_optimizer = Adam(learning_rate=actor_lr)
56
+ self.critic_optimizer = Adam(learning_rate=critic_lr)
57
+
58
+ self.train_log_dir = None
59
+ self.summary_writer = None
60
+
61
+ tf.random.set_seed(self.seed)
62
+ np.random.seed(self.seed)
63
+
64
+ dummy_input = np.zeros((1, *self.observation_shape), dtype=np.uint8)
65
+ _ = self.model(dummy_input)
66
+
67
+ def _make_env(self):
68
+ env = gym.make(self.env_id, render_mode="rgb_array", continuous=True)
69
+ env = CarRacingEnvWrapper(env, num_stack_frames=self.num_stack_frames,
70
+ grayscale=self.grayscale, resize_dim=self.resize_dim)
71
+ return env
72
+
73
+ def _make_vec_envs(self):
74
+ return gym.vector.SyncVectorEnv([self._make_env for _ in range(self.num_envs)])
75
+
76
+ def _compute_returns_and_advantages(self, rewards, values, dones):
77
+ advantages = np.zeros_like(rewards, dtype=np.float32)
78
+ returns = np.zeros_like(rewards, dtype=np.float32)
79
+ last_gae_lam = np.zeros(self.num_envs, dtype=np.float32)
80
+
81
+ for t in reversed(range(self.steps_per_batch)):
82
+ next_non_terminal = 1.0 - dones[t]
83
+ delta = rewards[t] + self.gamma * values[t+1] * next_non_terminal - values[t]
84
+ last_gae_lam = delta + self.gamma * self.lam * next_non_terminal * last_gae_lam
85
+ advantages[t] = last_gae_lam
86
+
87
+ returns = advantages + values[:-1]
88
+
89
+ return advantages, returns
90
+
91
+ @tf.function
92
+ def _train_step(self, observations, actions, old_log_probs, advantages, returns):
93
+ with tf.GradientTape() as tape:
94
+ action_distribution, value_pred = self.model(observations)
95
+ value_pred = tf.squeeze(value_pred, axis=-1)
96
+
97
+ critic_loss = tf.reduce_mean(tf.square(returns - value_pred))
98
+
99
+ log_prob = action_distribution.log_prob(actions)
100
+ ratio = tf.exp(log_prob - old_log_probs)
101
+
102
+ ratio = tf.where(tf.math.is_nan(ratio), 1.0, ratio)
103
+ ratio = tf.where(tf.math.is_inf(ratio), tf.sign(ratio) * 1e5, ratio)
104
+
105
+ pg_loss1 = ratio * advantages
106
+ pg_loss2 = tf.clip_by_value(ratio, 1 - self.clip_epsilon, 1 + self.clip_epsilon) * advantages
107
+ actor_loss = -tf.reduce_mean(tf.minimum(pg_loss1, pg_loss2))
108
+
109
+ entropy = tf.reduce_mean(action_distribution.entropy())
110
+ entropy_loss = -self.entropy_coeff * entropy
111
+
112
+ total_loss = actor_loss + critic_loss + entropy_loss
113
+
114
+ grads = tape.gradient(total_loss, self.model.trainable_variables)
115
+ self.actor_optimizer.apply_gradients(zip(grads, self.model.trainable_variables))
116
+
117
+ return actor_loss, critic_loss, entropy, total_loss
118
+
119
+ def train(self, total_timesteps, resume_from_timestep=0, resume_model_path=None, run_log_dir=None):
120
+ global_timestep = resume_from_timestep
121
+ ep_rewards = deque(maxlen=100)
122
+ ep_modified_rewards = deque(maxlen=100)
123
+
124
+ resume_json_path = "resume_config.json"
125
+
126
+ if run_log_dir is None:
127
+ if os.path.exists(resume_json_path):
128
+ with open(resume_json_path, "r") as f:
129
+ resume_info = json.load(f)
130
+ self.train_log_dir = resume_info.get("run_log_directory")
131
+
132
+ if self.train_log_dir is None:
133
+ current_time = datetime.now().strftime("%Y%m%d-%H%M%S")
134
+ self.train_log_dir = os.path.join(self.log_dir, current_time)
135
+ else:
136
+ self.train_log_dir = run_log_dir
137
+
138
+ os.makedirs(os.path.join(self.train_log_dir, "checkpoints"), exist_ok=True)
139
+ self.summary_writer = tf.summary.create_file_writer(self.train_log_dir)
140
+
141
+ if resume_model_path and os.path.exists(resume_model_path):
142
+ self.model.load_weights(resume_model_path)
143
+ print(f"Resuming training from timestep {global_timestep} and loaded model from: {resume_model_path}")
144
+ elif resume_from_timestep > 0:
145
+ print(f"WARNING: Attempting to resume from timestep {global_timestep} but no valid model path provided or found. Starting fresh.")
146
+ else:
147
+ print("Starting new training run.")
148
+
149
+ obs, _ = self.envs.reset(seed=self.seed)
150
+
151
+ print(f"Target total timesteps: {total_timesteps}")
152
+ print(f"Current global timestep: {global_timestep}")
153
+
154
+ resume_save_frequency = self.steps_per_batch * self.num_envs * 5
155
+
156
+ while global_timestep < total_timesteps:
157
+ batch_observations = np.zeros((self.steps_per_batch, self.num_envs, *self.observation_shape), dtype=np.uint8)
158
+ batch_actions = np.zeros((self.steps_per_batch, self.num_envs, self.action_dim), dtype=np.float32)
159
+ batch_rewards = np.zeros((self.steps_per_batch, self.num_envs), dtype=np.float32)
160
+ batch_dones = np.zeros((self.steps_per_batch, self.num_envs), dtype=bool)
161
+ batch_values = np.zeros((self.steps_per_batch, self.num_envs), dtype=np.float32)
162
+ batch_log_probs = np.zeros((self.steps_per_batch, self.num_envs), dtype=np.float32)
163
+ batch_original_rewards = np.zeros((self.steps_per_batch, self.num_envs), dtype=np.float32)
164
+
165
+ for i in range(self.steps_per_batch):
166
+ tf_obs = tf.convert_to_tensor(obs, dtype=tf.uint8)
167
+ action_dist, value = self.model(tf_obs)
168
+ action = action_dist.sample()
169
+ log_prob = action_dist.log_prob(action)
170
+
171
+ action_np = action.numpy()
172
+ value_np = tf.squeeze(value).numpy()
173
+ log_prob_np = log_prob.numpy()
174
+
175
+ next_obs, reward, terminated, truncated, info = self.envs.step(action_np)
176
+ done = terminated | truncated
177
+
178
+ batch_observations[i] = obs
179
+ batch_actions[i] = action_np
180
+ batch_rewards[i, :] = reward
181
+ batch_dones[i] = done
182
+ batch_values[i] = value_np
183
+ batch_log_probs[i] = log_prob_np
184
+
185
+ if not isinstance(info, list):
186
+ info = [info]
187
+
188
+ for inf_idx, (inf, d) in enumerate(zip(info, done)):
189
+ original_reward_value = inf.get("original_reward", reward[inf_idx])
190
+ if isinstance(original_reward_value, (list, np.ndarray)):
191
+ batch_original_rewards[i, inf_idx] = original_reward_value[0]
192
+ else:
193
+ batch_original_rewards[i, inf_idx] = original_reward_value
194
+
195
+ if d:
196
+ if isinstance(inf, dict):
197
+ final_info = inf.get("final_info")
198
+ if isinstance(final_info, dict) and "episode" in final_info:
199
+ ep_rewards.append(final_info["episode"]["r"])
200
+
201
+ obs = next_obs
202
+
203
+ global_timestep += self.num_envs
204
+
205
+ _, last_values_np = self.model(tf.convert_to_tensor(obs, dtype=tf.uint8))
206
+ last_values_np = tf.squeeze(last_values_np).numpy()
207
+
208
+ batch_values = np.concatenate((batch_values, last_values_np[np.newaxis, :]), axis=0)
209
+
210
+ advantages, returns = self._compute_returns_and_advantages(
211
+ batch_rewards, batch_values, batch_dones
212
+ )
213
+
214
+ flat_observations = batch_observations.reshape((-1, *self.observation_shape))
215
+ flat_actions = batch_actions.reshape((-1, self.action_dim))
216
+ flat_old_log_probs = batch_log_probs.reshape(-1)
217
+ flat_advantages = advantages.reshape(-1)
218
+ flat_returns = returns.reshape(-1)
219
+
220
+ flat_advantages = (flat_advantages - np.mean(flat_advantages)) / (np.std(flat_advantages) + 1e-8)
221
+
222
+ batch_original_total_reward = np.sum(batch_original_rewards)
223
+ batch_modified_total_reward = np.sum(batch_rewards)
224
+
225
+ batch_indices = np.arange(self.steps_per_batch * self.num_envs)
226
+ for _ in range(self.ppo_epochs):
227
+ np.random.shuffle(batch_indices)
228
+ for start_idx in range(0, len(batch_indices), len(batch_indices) // self.minibatches):
229
+ end_idx = start_idx + len(batch_indices) // self.minibatches
230
+ minibatch_indices = batch_indices[start_idx:end_idx]
231
+
232
+ mb_obs = tf.constant(flat_observations[minibatch_indices], dtype=tf.uint8)
233
+ mb_actions = tf.constant(flat_actions[minibatch_indices], dtype=tf.float32)
234
+ mb_old_log_probs = tf.constant(flat_old_log_probs[minibatch_indices], dtype=tf.float32)
235
+ mb_advantages = tf.constant(flat_advantages[minibatch_indices], dtype=tf.float32)
236
+ mb_returns = tf.constant(flat_returns[minibatch_indices], dtype=tf.float32)
237
+
238
+ actor_loss, critic_loss, entropy, total_loss = self._train_step(
239
+ mb_obs, mb_actions, mb_old_log_probs, mb_advantages, mb_returns
240
+ )
241
+
242
+ with self.summary_writer.as_default():
243
+ tf.summary.scalar("charts/total_timesteps", global_timestep, step=global_timestep)
244
+ tf.summary.scalar("losses/actor_loss", actor_loss, step=global_timestep)
245
+ tf.summary.scalar("losses/critic_loss", critic_loss, step=global_timestep)
246
+ tf.summary.scalar("losses/entropy", entropy, step=global_timestep)
247
+ tf.summary.scalar("losses/total_loss", total_loss, step=global_timestep)
248
+
249
+ if ep_rewards:
250
+ tf.summary.scalar("charts/avg_episode_reward_original_env", np.mean(ep_rewards), step=global_timestep)
251
+ tf.summary.scalar("charts/min_episode_reward_original_env", np.min(ep_rewards), step=global_timestep)
252
+ tf.summary.scalar("charts/max_episode_reward_original_env", np.max(ep_rewards), step=global_timestep)
253
+
254
+ tf.summary.scalar("charts/batch_total_reward_original", batch_original_total_reward, step=global_timestep)
255
+ tf.summary.scalar("charts/batch_total_reward_modified", batch_modified_total_reward, step=global_timestep)
256
+
257
+ with tf.name_scope('actor_std'):
258
+ tf.summary.histogram('log_std', self.model.actor_log_std, step=global_timestep)
259
+ tf.summary.scalar('std_mean_overall', tf.reduce_mean(tf.exp(self.model.actor_log_std)), step=global_timestep)
260
+
261
+ if global_timestep % (self.steps_per_batch * self.num_envs * 5) == 0:
262
+ if ep_rewards:
263
+ avg_orig_reward_str = f"{np.mean(ep_rewards):.2f}"
264
+ else:
265
+ avg_orig_reward_str = 'N/A'
266
+
267
+ #print(f"Timestep: {global_timestep}, Avg Original Env Reward (100 eps): {avg_orig_reward_str}")
268
+ print(f"Timestep: {global_timestep}, Number of episodes in Timestep: (Check tensorboard..lol)") #{avg_orig_reward_str}")
269
+
270
+ current_checkpoint_path = os.path.join(self.train_log_dir, "checkpoints", f"Actor-Critic_at_{global_timestep}.weights.h5")
271
+ self.model.save_weights(current_checkpoint_path)
272
+
273
+ resume_info = {
274
+ "last_global_timestep": global_timestep,
275
+ "last_checkpoint_path": current_checkpoint_path,
276
+ "run_log_directory": self.train_log_dir
277
+ }
278
+ with open(resume_json_path, "w") as f:
279
+ json.dump(resume_info, f, indent=4)
280
+ print(f"Resume info saved to {resume_json_path}")
281
+
282
+
283
+ print("Training finished.")
284
+ self.envs.close()
285
+ self.summary_writer.close()
286
+
287
+ final_model_path = os.path.join(self.train_log_dir, "Actor-Critic_final_model.weights.h5")
288
+ self.model.save_weights(final_model_path)
289
+
290
+ if os.path.exists(resume_json_path):
291
+ os.remove(resume_json_path)
292
+ print(f"Removed {resume_json_path} as training completed successfully.")
293
+
294
+ def evaluate(self, num_episodes=5, render=True, model_path=None):
295
+ eval_env = gym.make(self.env_id, render_mode="human" if render else "rgb_array", continuous=True)
296
+ eval_env = CarRacingEnvWrapper(eval_env, num_stack_frames=self.num_stack_frames,
297
+ grayscale=self.grayscale, resize_dim=self.resize_dim)
298
+
299
+ if model_path:
300
+ dummy_input = np.zeros((1, *self.observation_shape), dtype=np.uint8)
301
+ _ = self.model(dummy_input)
302
+ self.model.load_weights(model_path)
303
+ print(f"Loaded model from {model_path}")
304
+
305
+ episode_rewards = []
306
+ episode_original_rewards = []
307
+
308
+ for ep in range(num_episodes):
309
+ obs, _ = eval_env.reset()
310
+ done = False
311
+ total_reward = 0
312
+ total_original_reward = 0
313
+ while not done:
314
+ tf_obs = tf.convert_to_tensor(obs[np.newaxis, :], dtype=tf.uint8)
315
+ action_dist, _ = self.model(tf_obs)
316
+ action = action_dist.mean().numpy().flatten()
317
+
318
+ action[0] = np.clip(action[0], -1.0, 1.0)
319
+ action[1] = np.clip(action[1], 0.0, 1.0)
320
+ action[2] = np.clip(action[2], 0.0, 1.0)
321
+
322
+ obs, reward, terminated, truncated, info = eval_env.step(action)
323
+ done = terminated or truncated
324
+ total_reward += reward
325
+ total_original_reward += info.get('original_reward', reward)
326
+
327
+ episode_rewards.append(total_reward)
328
+ episode_original_rewards.append(total_original_reward)
329
+ print(f"Episode {ep+1} finished. Modified Reward: {total_reward:.2f}, Original Env Reward: {total_original_reward:.2f}")
330
+ eval_env.close()
331
+ print(f"Average modified evaluation reward over {num_episodes} episodes: {np.mean(episode_rewards):.2f}")
332
+ print(f"Average original environment reward over {num_episodes} episodes: {np.mean(episode_original_rewards):.2f}")
333
+ return episode_rewards, episode_original_rewards
334
+ #E
RaceCar.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #D
2
+ import tensorflow as tf
3
+ import keras
4
+ from keras import layers, Model
5
+ import tensorflow_probability as tfp
6
+
7
+ tfd = tfp.distributions
8
+
9
+ class ActorCritic(keras.Model):
10
+ def __init__(self, action_dim, num_stack_frames, img_height, img_width, hidden_layer_sizes):
11
+ super().__init__()
12
+ self.conv_layers = keras.Sequential([
13
+ layers.Conv2D(32, 8, strides=4, activation="relu", input_shape=(img_height, img_width, num_stack_frames)),
14
+ layers.Conv2D(64, 4, strides=2, activation="relu"),
15
+ layers.Conv2D(64, 3, strides=1, activation="relu"),
16
+ layers.Flatten(),
17
+ ])
18
+
19
+ actor_layers = []
20
+ for size in hidden_layer_sizes:
21
+ actor_layers.append(layers.Dense(size, activation="relu"))
22
+ self.common_actor_layer = keras.Sequential(actor_layers)
23
+
24
+ self.actor_mean = layers.Dense(action_dim, activation=None)
25
+ self.actor_log_std = tf.Variable(tf.zeros(action_dim, dtype=tf.float32), trainable=True)
26
+
27
+ critic_layers = []
28
+ for size in hidden_layer_sizes:
29
+ critic_layers.append(layers.Dense(size, activation="relu"))
30
+ self.common_critic_layer = keras.Sequential(critic_layers)
31
+
32
+ self.critic_value = layers.Dense(1, activation=None)
33
+
34
+ def call(self, inputs):
35
+ normalized_inputs = tf.cast(inputs, tf.float32) / 255.0
36
+
37
+ features = self.conv_layers(normalized_inputs)
38
+
39
+ actor_features = self.common_actor_layer(features)
40
+ mean = self.actor_mean(actor_features)
41
+
42
+ std = tf.exp(self.actor_log_std)
43
+
44
+ action_distribution = tfd.MultivariateNormalDiag(loc=mean, scale_diag=std)
45
+
46
+ critic_features = self.common_critic_layer(features)
47
+ value = self.critic_value(critic_features)
48
+
49
+ return action_distribution, value
50
+ #V
Train.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+ import os
3
+ import json
4
+ from PPO_Model import PPOAgent
5
+ from datetime import datetime
6
+
7
+ gpus = tf.config.list_physical_devices('GPU')
8
+ if gpus:
9
+ try:
10
+ for gpu in gpus:
11
+ tf.config.experimental.set_memory_growth(gpu, True)
12
+ logical_gpus = tf.config.experimental.list_logical_devices('GPU')
13
+ print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
14
+ except RuntimeError as e:
15
+ print(e)
16
+
17
+ agent_config = {
18
+ "env_id": "CarRacing-v3",
19
+ "num_envs": 21,
20
+ "gamma": 0.99,
21
+ "lam": 0.95,
22
+ "clip_epsilon": 0.2,
23
+ "actor_lr": 3e-4,
24
+ "critic_lr": 3e-4,
25
+ "ppo_epochs": 10,
26
+ "minibatches": 4,
27
+ "steps_per_batch": 1024,
28
+ "num_stack_frames": 4,
29
+ "resize_dim": (84, 84),
30
+ "grayscale": True,
31
+ "seed": 42,
32
+ "log_dir": "./ppo_car_racing_logs",
33
+ "entropy_coeff": 0.001,
34
+ 'save_interval_timesteps': 537600,
35
+ 'hidden_layer_sizes': [512, 512, 512]
36
+ }
37
+
38
+ RESUME_TRAINING_FLAG = True
39
+ RESUME_CONFIG_FILE = "resume_config.json"
40
+
41
+ if __name__ == "__main__":
42
+ resume_from_timestep = 0
43
+ resume_model_path = None
44
+ run_log_directory = None
45
+
46
+ if RESUME_TRAINING_FLAG and os.path.exists(RESUME_CONFIG_FILE):
47
+ try:
48
+ with open(RESUME_CONFIG_FILE, "r") as f:
49
+ resume_info = json.load(f)
50
+ resume_from_timestep = resume_info.get("last_global_timestep", 0)
51
+ resume_model_path = resume_info.get("last_checkpoint_path", None)
52
+ run_log_directory = resume_info.get("run_log_directory", None)
53
+ print(f"Found resume config: Will attempt to resume from timestep {resume_from_timestep}")
54
+ print(f"Loading model from: {resume_model_path}")
55
+ print(f"Continuing logging in directory: {run_log_directory}")
56
+
57
+ if not (resume_model_path and os.path.exists(resume_model_path)):
58
+ print("WARNING: Resume model path invalid or not found. Starting a new run.")
59
+ resume_from_timestep = 0
60
+ resume_model_path = None
61
+ run_log_directory = None
62
+ os.remove(RESUME_CONFIG_FILE)
63
+ except (IOError, json.JSONDecodeError) as e:
64
+ print(f"WARNING: Failed to read or parse resume config file. Starting a new run. Error: {e}")
65
+ resume_from_timestep = 0
66
+ resume_model_path = None
67
+ run_log_directory = None
68
+ if os.path.exists(RESUME_CONFIG_FILE):
69
+ os.remove(RESUME_CONFIG_FILE)
70
+
71
+ if run_log_directory is None:
72
+ current_time = datetime.now().strftime("%Y%m%d-%H%M%S")
73
+ run_log_directory = os.path.join(agent_config["log_dir"], current_time)
74
+ print(f"No valid resume config found. Starting a new run in: {run_log_directory}")
75
+
76
+ agent_config["log_dir"] = run_log_directory
77
+
78
+ print("Initializing PPO Agent...")
79
+ agent = PPOAgent(**agent_config)
80
+
81
+ total_timesteps = 30_000_000
82
+ try:
83
+ agent.train(total_timesteps,
84
+ resume_from_timestep=resume_from_timestep,
85
+ resume_model_path=resume_model_path,
86
+ run_log_dir=run_log_directory)
87
+ except KeyboardInterrupt:
88
+ print("\nTraining interrupted by user. Saving current state for resume...")
89
+ print("State likely saved by periodic checkpointing. Exiting.")
90
+ except Exception as e:
91
+ print(f"\nAn error occurred during training: {e}")
92
+ print("Attempting to save current state for resume before exiting...")
93
+ finally:
94
+ print(f"\nTraining session ended. TensorBoard logs available at: tensorboard --logdir {agent.train_log_dir}")
95
+ print("To view logs, run the above command in your terminal.")
96
+ #I
Trained_Agent.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+ import os
3
+ from PPO_Model import PPOAgent
4
+
5
+ gpus = tf.config.list_physical_devices('GPU')
6
+ if gpus:
7
+ try:
8
+ for gpu in gpus:
9
+ tf.config.experimental.set_memory_growth(gpu, True)
10
+ logical_gpus = tf.config.experimental.list_logical_devices('GPU')
11
+ print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
12
+ except RuntimeError as e:
13
+ print(e)
14
+
15
+ agent_config = {
16
+ "env_id": "CarRacing-v3",
17
+ "num_envs": 21,
18
+ "gamma": 0.99,
19
+ "lam": 0.95,
20
+ "clip_epsilon": 0.2,
21
+ "actor_lr": 3e-4,
22
+ "critic_lr": 3e-4,
23
+ "ppo_epochs": 10,
24
+ "minibatches": 4,
25
+ "steps_per_batch": 1024,
26
+ "num_stack_frames": 4,
27
+ "resize_dim": (84, 84),
28
+ "grayscale": True,
29
+ "seed": 42,
30
+ "log_dir": "./ppo_car_racing_logs",
31
+ "entropy_coeff": 0.001,
32
+ 'save_interval_timesteps': 537600,
33
+ 'hidden_layer_sizes': [512, 512, 512]
34
+ }
35
+
36
+ if __name__ == "__main__":
37
+ print("Initializing PPO Agent for evaluation...")
38
+
39
+ agent = PPOAgent(**agent_config)
40
+
41
+ root_log_dir = "./ppo_car_racing_logs"
42
+
43
+ latest_log_run_dir = None
44
+ if os.path.exists(root_log_dir):
45
+ all_runs = [os.path.join(root_log_dir, d) for d in os.listdir(root_log_dir) if os.path.isdir(os.path.join(root_log_dir, d))]
46
+ if all_runs:
47
+
48
+ latest_log_run_dir = max(all_runs, key=os.path.getmtime)
49
+ print(f"Found latest training run directory: {latest_log_run_dir}")
50
+ else:
51
+ print(f"No training run directories found in {root_log_dir}.")
52
+ else:
53
+ print(f"Log directory {root_log_dir} does not exist. Cannot find trained model.")
54
+
55
+
56
+ model_to_load = None
57
+ if latest_log_run_dir:
58
+
59
+ final_model_path = os.path.join(latest_log_run_dir, "final_model.weights.h5")
60
+ if os.path.exists(final_model_path):
61
+ model_to_load = final_model_path
62
+ else:
63
+ print(f"Final model weights not found in {latest_log_run_dir}. Checking checkpoints...")
64
+
65
+ checkpoint_dir = os.path.join(latest_log_run_dir, "checkpoints")
66
+ if os.path.exists(checkpoint_dir):
67
+ all_checkpoints = [os.path.join(checkpoint_dir, f) for f in os.listdir(checkpoint_dir) if f.endswith(".weights.h5")]
68
+ if all_checkpoints:
69
+ model_to_load = max(all_checkpoints, key=os.path.getmtime)
70
+ print(f"Loading latest checkpoint: {model_to_load}")
71
+ else:
72
+ print("No checkpoints found.")
73
+ else:
74
+ print("Checkpoints directory does not exist.")
75
+
76
+
77
+ if model_to_load:
78
+
79
+ print("\n--- Evaluation ---")
80
+ agent.evaluate(num_episodes=100, render=True, model_path=model_to_load)
81
+ else:
82
+ print("No trained model found to evaluate. Please train an agent first.")
83
+ #L