privateboss commited on
Commit
409b653
·
verified ·
1 Parent(s): a668619

Upload 6 files

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