privateboss commited on
Commit
18bcdea
·
verified ·
1 Parent(s): 376ed6e

Create PPO_Model.py

Browse files
Files changed (1) hide show
  1. PPO_Model.py +276 -0
PPO_Model.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+ import keras
3
+ from keras import layers, Model
4
+ import numpy as np
5
+ import tensorflow_probability as tfp
6
+ import os
7
+ import traceback
8
+
9
+ tfd = tfp.distributions
10
+
11
+ @tf.keras.utils.register_keras_serializable()
12
+ class Actor(Model):
13
+     def __init__(self, obs_shape, action_size, hidden_layer_sizes=[512, 512, 512], **kwargs):
14
+         super().__init__(**kwargs)
15
+
16
+         if len(obs_shape) > 1:
17
+             self.flatten = layers.Flatten(input_shape=obs_shape)
18
+        
19
+             self.flatten(tf.zeros((1,) + obs_shape))
20
+         else:
21
+             self.flatten = None
22
+        
23
+         self.dense_layers = []
24
+         for size in hidden_layer_sizes:
25
+             self.dense_layers.append(layers.Dense(size, activation='relu'))
26
+         self.logits = layers.Dense(action_size)
27
+
28
+         self._obs_shape = obs_shape
29
+         self._action_size = action_size
30
+         self._hidden_layer_sizes = hidden_layer_sizes
31
+
32
+     def call(self, inputs):
33
+    
34
+         x = self.flatten(inputs) if self.flatten else inputs
35
+         for layer in self.dense_layers:
36
+             x = layer(x)
37
+         return self.logits(x)
38
+
39
+     def get_config(self):
40
+         config = super().get_config()
41
+         config.update({
42
+             'obs_shape': self._obs_shape,
43
+             'action_size': self._action_size,
44
+             'hidden_layer_sizes': self._hidden_layer_sizes
45
+         })
46
+         return config
47
+
48
+ @tf.keras.utils.register_keras_serializable()
49
+ class Critic(Model):
50
+     def __init__(self, obs_shape, hidden_layer_sizes=[512, 512, 512], **kwargs):
51
+         super().__init__(**kwargs)
52
+
53
+         if len(obs_shape) > 1:
54
+             self.flatten = layers.Flatten(input_shape=obs_shape)
55
+             self.flatten(tf.zeros((1,) + obs_shape))
56
+         else:
57
+             self.flatten = None
58
+        
59
+         self.dense_layers = []
60
+         for size in hidden_layer_sizes:
61
+             self.dense_layers.append(layers.Dense(size, activation='relu'))
62
+         self.value = layers.Dense(1)
63
+
64
+         self._obs_shape = obs_shape
65
+         self._hidden_layer_sizes = hidden_layer_sizes
66
+
67
+     def call(self, inputs):
68
+         x = self.flatten(inputs) if self.flatten else inputs
69
+         for layer in self.dense_layers:
70
+             x = layer(x)
71
+         return self.value(x)
72
+
73
+     def get_config(self):
74
+         config = super().get_config()
75
+         config.update({
76
+             'obs_shape': self._obs_shape,
77
+             'hidden_layer_sizes': self._hidden_layer_sizes
78
+         })
79
+         return config
80
+
81
+ class PPOAgent:
82
+     def __init__(self, observation_space_shape, action_space_size,
83
+                  actor_lr=3e-4, critic_lr=3e-4, gamma=0.99,
84
+                  gae_lambda=0.95, clip_epsilon=0.2,
85
+                  num_epochs_per_update=10, batch_size=64,
86
+                  hidden_layer_sizes=[512, 512, 512]):
87
+        
88
+         self.gamma = gamma
89
+         self.gae_lambda = gae_lambda
90
+         self.clip_epsilon = clip_epsilon
91
+         self.num_epochs_per_update = num_epochs_per_update
92
+         self.batch_size = batch_size
93
+
94
+         self.observation_space_shape = observation_space_shape
95
+         self.action_space_size = action_space_size
96
+
97
+         self.actor = Actor(observation_space_shape, action_space_size, hidden_layer_sizes=hidden_layer_sizes)
98
+         self.critic = Critic(observation_space_shape, hidden_layer_sizes=hidden_layer_sizes)
99
+
100
+         self.actor_optimizer = tf.keras.optimizers.Adam(learning_rate=actor_lr)
101
+         self.critic_optimizer = tf.keras.optimizers.Adam(learning_rate=critic_lr)
102
+
103
+         self.states = []
104
+         self.actions = []
105
+         self.rewards = []
106
+         self.next_states = []
107
+         self.dones = []
108
+         self.log_probs = []
109
+         self.values = []
110
+
111
+         dummy_obs = tf.zeros((1,) + observation_space_shape, dtype=tf.float32)
112
+         self.actor(dummy_obs)
113
+         self.critic(dummy_obs)
114
+
115
+     def remember(self, state, action, reward, next_state, done, log_prob, value):
116
+         self.states.append(state)
117
+         self.actions.append(action)
118
+         self.rewards.append(reward)
119
+         self.next_states.append(next_state)
120
+         self.dones.append(done)
121
+         self.log_probs.append(log_prob)
122
+         self.values.append(value)
123
+
124
+     @tf.function
125
+
126
+     def _choose_action_tf(self, observation, action_mask):
127
+         observation = tf.expand_dims(tf.convert_to_tensor(observation, dtype=tf.float32), 0)
128
+        
129
+         pi_logits = self.actor(observation)
130
+        
131
+         masked_logits = tf.where(action_mask, pi_logits, -1e9)
132
+        
133
+         value = self.critic(observation)
134
+        
135
+         distribution = tfd.Categorical(logits=masked_logits)
136
+        
137
+         action = distribution.sample()
138
+         log_prob = distribution.log_prob(action)
139
+        
140
+         return action, log_prob, value
141
+
142
+     def choose_action(self, observation, action_mask):
143
+         action_tensor, log_prob_tensor, value_tensor = self._choose_action_tf(observation, action_mask)
144
+        
145
+         return action_tensor.numpy(), log_prob_tensor.numpy(), value_tensor.numpy()[0,0]
146
+
147
+     def calculate_advantages_and_returns(self):
148
+         rewards = np.array(self.rewards, dtype=np.float32)
149
+         values = np.array(self.values, dtype=np.float32)
150
+         dones = np.array(self.dones, dtype=np.float32)
151
+        
152
+         last_next_state_value = self.critic(tf.expand_dims(tf.convert_to_tensor(self.next_states[-1], dtype=tf.float32), 0)).numpy()[0,0] if not dones[-1] else 0
153
+         next_values = np.append(values[1:], last_next_state_value)
154
+        
155
+         advantages = []
156
+         returns = []
157
+        
158
+         last_advantage = 0
159
+         for t in reversed(range(len(rewards))):
160
+             delta = rewards[t] + self.gamma * next_values[t] * (1 - dones[t]) - values[t]
161
+          
162
+             advantage = delta + self.gae_lambda * self.gamma * (1 - dones[t]) * last_advantage
163
+             advantages.insert(0, advantage)
164
+
165
+             returns.insert(0, advantage + values[t])
166
+             last_advantage = advantage
167
+            
168
+         return np.array(advantages, dtype=np.float32), np.array(returns, dtype=np.float32)
169
+
170
+     def learn(self):
171
+         if not self.states:
172
+             return
173
+
174
+         states = tf.convert_to_tensor(np.array(self.states), dtype=tf.float32)
175
+         actions = tf.convert_to_tensor(np.array(self.actions), dtype=tf.int32)
176
+         old_log_probs = tf.convert_to_tensor(np.array(self.log_probs), dtype=tf.float32)
177
+        
178
+         advantages, returns = self.calculate_advantages_and_returns()
179
+         advantages = (advantages - tf.reduce_mean(advantages)) / (tf.math.reduce_std(advantages) + 1e-8)
180
+        
181
+         dataset = tf.data.Dataset.from_tensor_slices((states, actions, old_log_probs, advantages, returns))
182
+         dataset = dataset.shuffle(buffer_size=len(self.states)).batch(self.batch_size)
183
+
184
+         for _ in range(self.num_epochs_per_update):
185
+             for batch_states, batch_actions, batch_old_log_probs, batch_advantages, batch_returns in dataset:
186
+    
187
+                 with tf.GradientTape() as tape:
188
+                     current_logits = self.actor(batch_states)
189
+                    
190
+                     new_distribution = tfd.Categorical(logits=current_logits)
191
+                    
192
+                     new_log_probs = new_distribution.log_prob(batch_actions)
193
+                     ratio = tf.exp(new_log_probs - batch_old_log_probs)
194
+                                        
195
+                     surrogate1 = ratio * batch_advantages
196
+                     surrogate2 = tf.clip_by_value(ratio, 1 - self.clip_epsilon, 1 + self.clip_epsilon) * batch_advantages
197
+                                        
198
+                     actor_loss = -tf.reduce_mean(tf.minimum(surrogate1, surrogate2))
199
+                                
200
+                 actor_grads = tape.gradient(actor_loss, self.actor.trainable_variables)
201
+                 self.actor_optimizer.apply_gradients(zip(actor_grads, self.actor.trainable_variables))
202
+
203
+                 with tf.GradientTape() as tape:
204
+                     new_values = self.critic(batch_states)
205
+                     critic_loss = tf.reduce_mean(tf.square(new_values - batch_returns))
206
+                                
207
+                 critic_grads = tape.gradient(critic_loss, self.critic.trainable_variables)
208
+                 self.critic_optimizer.apply_gradients(zip(critic_grads, self.critic.trainable_variables))
209
+        
210
+         self.states = []
211
+         self.actions = []
212
+         self.rewards = []
213
+         self.next_states = []
214
+         self.dones = []
215
+         self.log_probs = []
216
+         self.values = []
217
+
218
+     def save_models(self, path):
219
+         actor_save_path = f"{path}_actor.keras"
220
+         critic_save_path = f"{path}_critic.keras"
221
+         print(f"\n--- Attempting to save models ---")
222
+         print(f"Target Actor path: {os.path.abspath(actor_save_path)}")
223
+         print(f"Target Critic path: {os.path.abspath(critic_save_path)}")
224
+         try:
225
+             self.actor.save(actor_save_path)
226
+             print(f"Actor model saved successfully to {os.path.abspath(actor_save_path)}")
227
+         except Exception as e:
228
+             print(f"ERROR: Failed to save Actor model to {os.path.abspath(actor_save_path)}")
229
+             print(f"Reason: {e}")
230
+   ��         traceback.print_exc()
231
+         try:
232
+             self.critic.save(critic_save_path)
233
+             print(f"Critic model saved successfully to {os.path.abspath(critic_save_path)}")
234
+         except Exception as e:
235
+             print(f"ERROR: Failed to save Critic model to {os.path.abspath(critic_save_path)}")
236
+             print(f"Reason: {e}")
237
+             traceback.print_exc()
238
+         print(f"--- Models save process completed ---\n")
239
+
240
+     def load_models(self, path):
241
+    
242
+         actor_load_path = f"{path}_actor.keras"
243
+         critic_load_path = f"{path}_critic.keras"
244
+         actor_loaded_ok = False
245
+         critic_loaded_ok = False
246
+
247
+         custom_objects = {
248
+             'Actor': Actor,
249
+             'Critic': Critic
250
+         }
251
+        
252
+         try:
253
+
254
+             self.actor = tf.keras.models.load_model(actor_load_path, custom_objects=custom_objects)
255
+             actor_loaded_ok = True
256
+             print(f"Actor model loaded from: {os.path.abspath(actor_load_path)}")
257
+         except Exception as e:
258
+             print(f"ERROR: Failed to load Actor model from {os.path.abspath(actor_load_path)}")
259
+             print(f"Reason: {e}")
260
+             traceback.print_exc()
261
+
262
+         try:
263
+             self.critic = tf.keras.models.load_model(critic_load_path, custom_objects=custom_objects)
264
+             critic_loaded_ok = True
265
+             print(f"Critic model loaded from: {os.path.abspath(critic_load_path)}")
266
+         except Exception as e:
267
+             print(f"ERROR: Failed to load Critic model from {os.path.abspath(critic_load_path)}")
268
+             print(f"Reason: {e}")
269
+             traceback.print_exc()
270
+
271
+         if actor_loaded_ok and critic_loaded_ok:
272
+             print(f"All PPO models loaded successfully from '{path}'.")
273
+             return True
274
+         else:
275
+             print(f"Warning: One or both models failed to load. The agent will use untrained models.")
276
+             return False