privateboss commited on
Commit
b4ad891
·
verified ·
1 Parent(s): 196ecf3

Upload 13 files

Browse files
AI_ContinuousLunarLander/__pycache__/agent.cpython-310.pyc ADDED
Binary file (6.42 kB). View file
 
AI_ContinuousLunarLander/__pycache__/config.cpython-310.pyc ADDED
Binary file (1.37 kB). View file
 
AI_ContinuousLunarLander/__pycache__/model.cpython-310.pyc ADDED
Binary file (2.55 kB). View file
 
AI_ContinuousLunarLander/__pycache__/utils.cpython-310.pyc ADDED
Binary file (2.77 kB). View file
 
AI_ContinuousLunarLander/agent.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tensorflow as tf
3
+ from model import Actor, Critic, gaussian_log_prob, gaussian_entropy
4
+ from config import (
5
+ LEARNING_RATE, LR_MIN_FRACTION, GAMMA, GAE_LAMBDA, CLIP_RATIO,
6
+ VALUE_LOSS_COEF, INITIAL_ENTROPY_COEF, MAX_GRAD_NORM,
7
+ CHECKPOINT_DIR, TOTAL_ITERATIONS
8
+ )
9
+ from utils import compute_gae_vectorized
10
+
11
+
12
+ def _build_optimizer(optimizer, variables):
13
+ """Create optimizer slots without taking a real update step."""
14
+ try:
15
+ optimizer.build(variables)
16
+ except AttributeError:
17
+ pass # legacy optimizers create slots lazily; checkpoint restore is deferred instead
18
+
19
+
20
+ def _set_lr(optimizer, value):
21
+ try:
22
+ optimizer.learning_rate.assign(value)
23
+ except Exception:
24
+ optimizer.learning_rate = value
25
+
26
+
27
+ class PPOAgent:
28
+ def __init__(self, state_dim, action_dim):
29
+ self.gamma = GAMMA
30
+ self.gae_lambda = GAE_LAMBDA
31
+ self.base_clip_ratio = CLIP_RATIO
32
+ self.value_loss_coef = VALUE_LOSS_COEF
33
+ self.entropy_coef = INITIAL_ENTROPY_COEF
34
+
35
+ self.global_step = tf.Variable(0, trainable=False, dtype=tf.int64, name="global_step")
36
+
37
+ self.actor = Actor(action_dim)
38
+ self.critic = Critic()
39
+ # Build the networks so every variable (incl. log_std) exists before the optimizers
40
+ dummy_state = tf.zeros((1, state_dim), dtype=tf.float32)
41
+ self.actor(dummy_state)
42
+ self.critic(dummy_state)
43
+
44
+ # Fail loudly if log_std is not trained (sigma would silently stay frozen)
45
+ names = [v.name for v in self.actor.trainable_variables]
46
+ if not any("log_std" in n for n in names):
47
+ raise RuntimeError(f"actor log_std is not trainable! variables: {names}")
48
+ print(f"Actor trainable variables: {len(names)} (log_std tracked)")
49
+
50
+ self.actor_optimizer = tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE)
51
+ self.critic_optimizer = tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE)
52
+ _build_optimizer(self.actor_optimizer, self.actor.trainable_variables)
53
+ _build_optimizer(self.critic_optimizer, self.critic.trainable_variables)
54
+
55
+ self.checkpoint = tf.train.Checkpoint(
56
+ global_step=self.global_step,
57
+ actor=self.actor, critic=self.critic,
58
+ actor_optimizer=self.actor_optimizer, critic_optimizer=self.critic_optimizer,
59
+ )
60
+ self.checkpoint_manager = tf.train.CheckpointManager(
61
+ self.checkpoint, directory=CHECKPOINT_DIR, max_to_keep=5
62
+ )
63
+
64
+ # schedules / checkpoints
65
+ def update_schedules(self, current_iteration, total_iterations=TOTAL_ITERATIONS):
66
+ """Track the global step and linearly anneal the learning rate."""
67
+ self.global_step.assign(current_iteration)
68
+ frac = max(1.0 - (current_iteration - 1) / float(total_iterations), LR_MIN_FRACTION)
69
+ self.current_lr = LEARNING_RATE * frac
70
+ _set_lr(self.actor_optimizer, self.current_lr)
71
+ _set_lr(self.critic_optimizer, self.current_lr)
72
+
73
+ @property
74
+ def current_clip_ratio(self):
75
+ return self.base_clip_ratio
76
+
77
+ def save_checkpoint(self):
78
+ path = self.checkpoint_manager.save()
79
+ print(f"Checkpoint saved at step {self.global_step.numpy()}: {path}")
80
+
81
+ def load_checkpoint(self):
82
+ latest = self.checkpoint_manager.latest_checkpoint
83
+ if latest:
84
+ self.checkpoint.restore(latest)
85
+ print(f"Restored from checkpoint (resuming at global step {self.global_step.numpy()}): {latest}")
86
+ return True
87
+ print("No checkpoint found. Starting fresh from global step 0.")
88
+ return False
89
+
90
+ def save_era(self, directory):
91
+ """Write a self-contained checkpoint into its own folder (no file copying)."""
92
+ os.makedirs(directory, exist_ok=True)
93
+ return self.checkpoint.save(os.path.join(directory, "ckpt"))
94
+
95
+ def load_from(self, directory):
96
+ """Restore the newest checkpoint inside `directory` (used for eras / inference)."""
97
+ path = tf.train.latest_checkpoint(directory)
98
+ if path is None:
99
+ return False
100
+ self.checkpoint.restore(path).expect_partial()
101
+ return True
102
+
103
+ # acting
104
+ @tf.function(reduce_retracing=True)
105
+ def act_batch(self, states):
106
+ """Sample actions for all envs at once.
107
+ Returns the RAW Gaussian sample (stored for training), its log-prob and V(s).
108
+ Clip to [-1, 1] only when stepping the env."""
109
+ mu, sigma = self.actor(states)
110
+ raw = mu + sigma * tf.random.normal(tf.shape(mu))
111
+ log_prob = gaussian_log_prob(raw, mu, sigma)
112
+ value = tf.squeeze(self.critic(states), axis=-1)
113
+ return raw, log_prob, value
114
+
115
+ @tf.function(reduce_retracing=True)
116
+ def value_batch(self, states):
117
+ return tf.squeeze(self.critic(states), axis=-1)
118
+
119
+ def compute_trajectory_advantages(self, rewards, values, dones, next_values):
120
+ return compute_gae_vectorized(rewards, values, dones, next_values, self.gamma, self.gae_lambda)
121
+
122
+ # learning
123
+ @tf.function(reduce_retracing=True)
124
+ def train_step(self, states, actions, old_log_probs, returns, advantages, entropy_coef, clip_val):
125
+ with tf.GradientTape() as actor_tape:
126
+ mu, sigma = self.actor(states)
127
+ log_probs = gaussian_log_prob(actions, mu, sigma)
128
+ log_ratio = log_probs - old_log_probs
129
+ ratio = tf.exp(log_ratio)
130
+ surr1 = ratio * advantages
131
+ surr2 = tf.clip_by_value(ratio, 1.0 - clip_val, 1.0 + clip_val) * advantages
132
+ policy_loss = -tf.reduce_mean(tf.minimum(surr1, surr2))
133
+ entropy = gaussian_entropy(sigma) # scalar: summed over action dims
134
+ actor_loss = policy_loss - entropy_coef * entropy
135
+ actor_grads = actor_tape.gradient(actor_loss, self.actor.trainable_variables)
136
+ actor_grads, _ = tf.clip_by_global_norm(actor_grads, MAX_GRAD_NORM)
137
+ self.actor_optimizer.apply_gradients(zip(actor_grads, self.actor.trainable_variables))
138
+
139
+ with tf.GradientTape() as critic_tape:
140
+ values_pred = tf.squeeze(self.critic(states), axis=-1)
141
+ value_loss = tf.reduce_mean(tf.square(returns - values_pred)) # no value clipping
142
+ critic_loss = self.value_loss_coef * value_loss
143
+ critic_grads = critic_tape.gradient(critic_loss, self.critic.trainable_variables)
144
+ critic_grads, _ = tf.clip_by_global_norm(critic_grads, MAX_GRAD_NORM)
145
+ self.critic_optimizer.apply_gradients(zip(critic_grads, self.critic.trainable_variables))
146
+
147
+ return {
148
+ "policy_loss": policy_loss,
149
+ "value_loss": value_loss,
150
+ "entropy": entropy,
151
+ "approx_kl": tf.reduce_mean((ratio - 1.0) - log_ratio),
152
+ "clip_frac": tf.reduce_mean(tf.cast(tf.abs(ratio - 1.0) > clip_val, tf.float32)),
153
+ "sigma_mean": tf.reduce_mean(sigma),
154
+ }
AI_ContinuousLunarLander/config.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from gymnasium.envs.box2d import lunar_lander
2
+
3
+ ENV_NAME = "LunarLander-v3"
4
+
5
+ # Mars Environmental & Physics Configuration
6
+ CONTINUOUS_CONTROL = True
7
+ GRAVITY = -3.72 # Mars gravitational acceleration
8
+ WIND_POWER = 5.0
9
+ TURBULENCE_POWER = 2.0
10
+ ENABLE_WIND = True
11
+ MAX_EPISODE_STEPS = 1200 # time limit; truncation is bootstrapped in train.py
12
+
13
+ # Thrust to Weight Ratio- TWR-Matched Engine Power for Mars Physics
14
+ MAIN_ENGINE_POWER = 4.84
15
+ SIDE_ENGINE_POWER = 0.30
16
+
17
+ # Apply TWR-matched monkey patch globally across Gymnasium.
18
+ # Every module imports config, so the patch is applied in train and inference alike.
19
+ lunar_lander.MAIN_ENGINE_POWER = MAIN_ENGINE_POWER
20
+ lunar_lander.SIDE_ENGINE_POWER = SIDE_ENGINE_POWER
21
+ # Optional: the initial random kick is not scaled by gravity in Gymnasium, so it is
22
+ # relatively ~1.6x stronger on Mars. Uncomment to scale it like gravity:
23
+ # lunar_lander.INITIAL_RANDOM = 1000.0 * (3.72 / 10.0)
24
+
25
+ # Run layout (so old, incompatible checkpoints are not restored)
26
+ RUN_DIR = "./marsLander_GustyMars_v2"
27
+ CHECKPOINT_DIR = f"{RUN_DIR}/checkpoints"
28
+ ERAS_DIR = f"{RUN_DIR}/eras"
29
+ BEST_ERA_DIR = f"{RUN_DIR}/best_era"
30
+ LOG_DIR = f"{RUN_DIR}/logs"
31
+
32
+ # Training Hyperparameters
33
+ SEED = 42
34
+ NUM_ENVS = 16
35
+ TOTAL_ITERATIONS = 8000 # 8000 * 8192 = ~65536000 steps
36
+ ERA_ITERATION_INTERVAL = 100
37
+ STEPS_PER_ENV = 512
38
+ BATCH_SIZE = NUM_ENVS * STEPS_PER_ENV # 8192
39
+ EPOCHS_PER_BATCH = 10
40
+ MINI_BATCH_SIZE = 1024 # 8 minibatches per epoch
41
+ LEARNING_RATE = 3e-4
42
+ LR_MIN_FRACTION = 0.1
43
+ GAMMA = 0.997
44
+ GAE_LAMBDA = 0.97
45
+ CLIP_RATIO = 0.2
46
+ VALUE_LOSS_COEF = 0.5
47
+ MAX_GRAD_NORM = 0.5
48
+ TARGET_KL = 0.02 # stop remaining epochs if approx KL exceeds 1.5x this
49
+ REWARD_SCALE = 100.0 # rewards are divided by this before GAE
50
+
51
+ # --- Exploration ---
52
+ INITIAL_ENTROPY_COEF = 0.012 #0.001
53
+ LOG_STD_INIT = -0.3
54
+ SIGMA_FLOOR = 0.02 # added to exp(log_std); keeps gradients alive (no clipping)
55
+
56
+ HIDDEN_DIMS = [128, 128]
57
+ SAVE_FREQ = 10
58
+ EVAL_EPISODES = 10
59
+ EVAL_SEED = 1000
60
+
61
+ # Landing accuracy (training envs only; evaluation stays unshaped)
62
+ PAD_BONUS = 50.0 # raw reward added for a dead-center landing (scaled by REWARD_SCALE later)
63
+ PAD_BONUS_FALLOFF = 1.0 #0.5 # bonus fades linearly to 0 at |x| = this (observation units)
64
+ PAD_HALF_WIDTH = 0.2 # flags sit at |x| = 0.2; used only for the "in zone" metric
AI_ContinuousLunarLander/evaluate_robust.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Large-sample evaluation of saved eras (headless, parallel, unshaped reward).
3
+
4
+ Phase 1 (screen): every era x {deterministic, stochastic} on N fresh seeds per mode
5
+ (default 3000 per mode = 6000 per era), then a robustness ranking of all eras
6
+ Phase 2 (finalists): the top few eras of the robustness ranking on a much bigger sample.
7
+ Ranking = each era's WORST mode (lower bound of its between-flags rate), then mean reward,
8
+ so an era that stays safe under action noise outranks one that only shines with the mean action.
9
+ Outputs: summary table + per-episode CSVs + the worst episodes (seeds you can replay)
10
+
11
+ Usage
12
+ python evaluate_robust.py # screen all eras (3000 eps per mode (Stochastic and Deterministic) = 6000 per era), finalists (20000 eps)
13
+ python evaluate_robust.py --screen-episodes 2000 --final-episodes 100000 --finalists 2
14
+ python evaluate_robust.py --eras era_iter_2000 era_iter_2500 --skip-final
15
+ python evaluate_robust.py --final-eras era_iter_2000 --final-episodes 50000
16
+ python evaluate_robust.py --replay era_iter_2000 --seeds 100123 100457 --mode det # watch specific seeds
17
+
18
+ Notes
19
+ * Seeds: screening uses seed_base + i, finalists use seed_base + 10_000_000 + i. Both are disjoint from the
20
+ 1000-1009 seeds used by trained_agent.py, and every era sees the same seeds (paired comparison).
21
+ * Workers run the policy in plain numpy (no TensorFlow), one LunarLander env per process.
22
+ The numpy forward pass is checked against the TensorFlow actor before any episode runs.
23
+ * Deterministic = mean action (what trained_agent.py evaluates). Stochastic = sampled, like training.
24
+ """
25
+
26
+ import argparse
27
+ import csv
28
+ import math
29
+ import os
30
+ import re
31
+ import time
32
+ from multiprocessing import get_context
33
+
34
+ import numpy as np
35
+
36
+ from config import ERAS_DIR, RUN_DIR, SIGMA_FLOOR, PAD_HALF_WIDTH
37
+ from utils import make_env
38
+
39
+ FIELDS = ["era", "mode", "seed", "reward", "landed", "in_zone", "x", "y", "td_speed", "steps", "timeout"]
40
+ I_ERA, I_MODE, I_SEED, I_REW, I_LAND, I_ZONE, I_X, I_Y, I_TD, I_STEPS, I_TMO = range(11)
41
+ FINAL_SEED_OFFSET = 10_000_000
42
+
43
+
44
+ # policy / episode
45
+ def _mu(w, x):
46
+ """Mean action from the actor weights, plain numpy (x can be 1-D or 2-D)."""
47
+ for kernel, bias in w["hidden"]:
48
+ x = np.tanh(x @ kernel + bias)
49
+ return x @ w["W_mu"] + w["b_mu"]
50
+
51
+
52
+ def _episode(env, w, era, seed, stochastic):
53
+ """One full episode. Returns a tuple in FIELDS order. Fully determined by (weights, seed, mode)."""
54
+ rng = np.random.default_rng(seed)
55
+ obs, _ = env.reset(seed=int(seed))
56
+ total, steps, td_speed = 0.0, 0, float("nan")
57
+ terminated = truncated = False
58
+ while not (terminated or truncated):
59
+ mu = _mu(w, obs.astype(np.float32))
60
+ if stochastic:
61
+ mu = mu + w["sigma"] * rng.standard_normal(mu.shape)
62
+ obs, reward, terminated, truncated, _ = env.step(np.clip(mu, -1.0, 1.0).astype(np.float32))
63
+ total += float(reward)
64
+ steps += 1
65
+ if math.isnan(td_speed) and (obs[6] > 0.5 or obs[7] > 0.5): # first leg contact
66
+ td_speed = float(math.hypot(obs[2], obs[3]))
67
+ x = float(obs[0])
68
+ # game_over is set on crashes; |x| >= 1 means the lander left the screen
69
+ landed = bool(terminated and not env.unwrapped.game_over and abs(x) < 1.0)
70
+ in_zone = bool(landed and abs(x) < PAD_HALF_WIDTH)
71
+ timeout = bool(truncated and not terminated)
72
+ return (era, "stoch" if stochastic else "det", int(seed), total, landed, in_zone,
73
+ x, float(obs[1]), td_speed, steps, timeout)
74
+
75
+
76
+ # worker side
77
+ _ENV = None
78
+ _WEIGHTS = None
79
+
80
+
81
+ def _init_worker(all_weights):
82
+ global _ENV, _WEIGHTS
83
+ _WEIGHTS = all_weights
84
+ _ENV = make_env() # unshaped: true reward
85
+
86
+
87
+ def _run_task(task):
88
+ era, seed, stochastic = task
89
+ return _episode(_ENV, _WEIGHTS[era], era, seed, stochastic)
90
+
91
+
92
+ # weights
93
+ def era_sort_key(name):
94
+ m = re.search(r"(\d+)$", name)
95
+ return int(m.group(1)) if m else -1
96
+
97
+
98
+ def list_eras():
99
+ return sorted([d for d in os.listdir(ERAS_DIR) if os.path.isdir(os.path.join(ERAS_DIR, d))],
100
+ key=era_sort_key)
101
+
102
+
103
+ def load_all_weights(era_names):
104
+ """Load each era with the real PPOAgent and export the actor as numpy arrays.
105
+ The numpy forward pass is verified against the TensorFlow actor for every era."""
106
+ os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # 8-dim MLP inference does not need the GPU
107
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # also hides the harmless "no CUDA device" error line
108
+ import tensorflow as tf
109
+ from agent import PPOAgent
110
+
111
+ probe = make_env()
112
+ state_dim = probe.observation_space.shape[0]
113
+ action_dim = probe.action_space.shape[0]
114
+ probe.close()
115
+
116
+ agent = PPOAgent(state_dim, action_dim)
117
+ test_states = np.random.default_rng(0).uniform(-1, 1, (64, state_dim)).astype(np.float32)
118
+ weights = {}
119
+ for name in era_names:
120
+ if not agent.load_from(os.path.join(ERAS_DIR, name)):
121
+ print(f"Skipping {name}: no checkpoint found.")
122
+ continue
123
+ w = {
124
+ "hidden": [tuple(np.asarray(a, dtype=np.float32) for a in layer.get_weights())
125
+ for layer in agent.actor.hidden_layers],
126
+ "W_mu": np.asarray(agent.actor.mu_layer.get_weights()[0], dtype=np.float32),
127
+ "b_mu": np.asarray(agent.actor.mu_layer.get_weights()[1], dtype=np.float32),
128
+ "sigma": (np.exp(np.asarray(agent.actor.log_std.numpy())) + SIGMA_FLOOR).astype(np.float32),
129
+ }
130
+ mu_tf = agent.actor(tf.convert_to_tensor(test_states))[0].numpy()
131
+ if not np.allclose(mu_tf, _mu(w, test_states), atol=1e-4):
132
+ raise RuntimeError(f"numpy policy does not match the TensorFlow actor for {name}")
133
+ weights[name] = w
134
+ print(f"Loaded {len(weights)} era(s); numpy policy matches the TensorFlow actor.")
135
+ return weights
136
+
137
+
138
+ # statistics
139
+ def wilson(k, n, z=1.96):
140
+ """95% Wilson score interval for a proportion k/n."""
141
+ if n == 0:
142
+ return float("nan"), float("nan")
143
+ p = k / n
144
+ denom = 1.0 + z * z / n
145
+ centre = (p + z * z / (2 * n)) / denom
146
+ half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
147
+ return centre - half, centre + half
148
+
149
+
150
+ def summarize(rows):
151
+ n = len(rows)
152
+ rew = np.array([r[I_REW] for r in rows], dtype=float)
153
+ landed = np.array([r[I_LAND] for r in rows], dtype=bool)
154
+ zone = np.array([r[I_ZONE] for r in rows], dtype=bool)
155
+ tmo = np.array([r[I_TMO] for r in rows], dtype=bool)
156
+ ax = np.abs(np.array([r[I_X] for r in rows], dtype=float))
157
+ td = np.array([r[I_TD] for r in rows], dtype=float)
158
+ zone_lo, _ = wilson(int(zone.sum()), n)
159
+ land_lo, _ = wilson(int(landed.sum()), n)
160
+ return {
161
+ "era": rows[0][I_ERA], "mode": rows[0][I_MODE], "n": n,
162
+ "land_rate": landed.mean(), "land_lo": land_lo,
163
+ "zone_rate": zone.mean(), "zone_lo": zone_lo,
164
+ "mean": rew.mean(), "p1": float(np.percentile(rew, 1)), "min": rew.min(),
165
+ "crashes": int((~landed & ~tmo).sum()), "off_zone": int((landed & ~zone).sum()),
166
+ "timeouts": int(tmo.sum()),
167
+ "x_p99": float(np.percentile(ax, 99)), "x_max": ax.max(),
168
+ "td_max": float(np.nanmax(td)) if np.isfinite(td).any() else float("nan"),
169
+ }
170
+
171
+
172
+ def group(rows):
173
+ groups = {}
174
+ for r in rows:
175
+ groups.setdefault((r[I_ERA], r[I_MODE]), []).append(r)
176
+ return groups
177
+
178
+
179
+ def print_table(summaries, title):
180
+ print(f"\n=== {title} ===")
181
+ print(f"{'era':<15}{'mode':<6}{'n':>8} {'land%':>7} {'zone%':>7} {'zone>=%':>8} {'mean':>7} {'p1':>7} "
182
+ f"{'min':>7} {'crash':>6} {'offz':>5} {'tmo':>4} {'|x|p99':>7} {'|x|max':>7} {'tdmax':>6}")
183
+ for s in summaries:
184
+ print(f"{s['era']:<15}{s['mode']:<6}{s['n']:>8d} {100*s['land_rate']:7.2f} {100*s['zone_rate']:7.2f} "
185
+ f"{100*s['zone_lo']:8.2f} {s['mean']:7.1f} {s['p1']:7.1f} {s['min']:7.1f} {s['crashes']:>6d} "
186
+ f"{s['off_zone']:>5d} {s['timeouts']:>4d} {s['x_p99']:7.3f} {s['x_max']:7.3f} {s['td_max']:6.3f}")
187
+ print(f"land%/zone% = share of episodes that landed / landed between the flags (|x|<{PAD_HALF_WIDTH}); "
188
+ "zone>=% = 95% Wilson lower bound; crash/offz/tmo = counts of crashes, landings outside the flags, "
189
+ "time-outs; tdmax = fastest first-contact speed (observation units).")
190
+
191
+
192
+ def rank_eras(summaries):
193
+ """Order eras by their WORST-mode result, so an era that holds up under action noise ranks above one that
194
+ only looks good with the mean action. Key: lower bound of the between-flags rate in the worse mode,
195
+ then mean reward averaged over modes."""
196
+ by_era = {}
197
+ for s in summaries:
198
+ by_era.setdefault(s["era"], {})[s["mode"]] = s
199
+ ranking = []
200
+ for era, modes in by_era.items():
201
+ ms = list(modes.values())
202
+ ranking.append({
203
+ "era": era,
204
+ "robust_lo": min(m["zone_lo"] for m in ms),
205
+ "mean": float(np.mean([m["mean"] for m in ms])),
206
+ "worst_p1": min(m["p1"] for m in ms),
207
+ "zone_rate": {mode: m["zone_rate"] for mode, m in modes.items()},
208
+ "crash_rate": {mode: m["crashes"] / m["n"] for mode, m in modes.items()},
209
+ })
210
+ return sorted(ranking, key=lambda r: (r["robust_lo"], r["mean"]), reverse=True)
211
+
212
+
213
+ def _pct(d, key):
214
+ return f"{100 * d[key]:.2f}" if key in d else "-"
215
+
216
+
217
+ def print_ranking(ranking, phase):
218
+ print(f"\n--- {phase.upper()} robustness ranking: worst mode first (zone>= = 95% lower bound of the "
219
+ f"between-flags rate in the worse mode) ---")
220
+ print(f"{'#':>3} {'era':<15}{'zone>=%':>8} {'det zone%':>10} {'stoch zone%':>12} "
221
+ f"{'det crash%':>11} {'stoch crash%':>13} {'mean':>7} {'worst p1':>9}")
222
+ for i, r in enumerate(ranking, 1):
223
+ print(f"{i:>3} {r['era']:<15}{100*r['robust_lo']:8.2f} {_pct(r['zone_rate'], 'det'):>10} "
224
+ f"{_pct(r['zone_rate'], 'stoch'):>12} {_pct(r['crash_rate'], 'det'):>11} "
225
+ f"{_pct(r['crash_rate'], 'stoch'):>13} {r['mean']:7.1f} {r['worst_p1']:9.1f}")
226
+
227
+
228
+ def write_csv(path, header, rows):
229
+ with open(path, "w", newline="") as f:
230
+ wr = csv.writer(f)
231
+ wr.writerow(header)
232
+ wr.writerows(rows)
233
+
234
+
235
+ def report(phase, rows, out_dir, worst_k=5):
236
+ groups = group(rows)
237
+ summaries = [summarize(groups[k]) for k in sorted(groups, key=lambda k: (era_sort_key(k[0]), k[1]))]
238
+ print_table(summaries, f"{phase.upper()} ({len(rows)} episodes)")
239
+ write_csv(os.path.join(out_dir, f"episodes_{phase}.csv"), FIELDS, rows)
240
+ keys = ["era", "mode", "n", "land_rate", "land_lo", "zone_rate", "zone_lo", "mean", "p1", "min",
241
+ "crashes", "off_zone", "timeouts", "x_p99", "x_max", "td_max"]
242
+ write_csv(os.path.join(out_dir, f"summary_{phase}.csv"), keys, [[s[k] for k in keys] for s in summaries])
243
+ ranking = rank_eras(summaries)
244
+ print_ranking(ranking, phase)
245
+ write_csv(os.path.join(out_dir, f"ranking_{phase}.csv"),
246
+ ["rank", "era", "robust_zone_lo", "det_zone_rate", "stoch_zone_rate", "det_crash_rate",
247
+ "stoch_crash_rate", "mean", "worst_p1"],
248
+ [[i, r["era"], r["robust_lo"], r["zone_rate"].get("det", ""), r["zone_rate"].get("stoch", ""),
249
+ r["crash_rate"].get("det", ""), r["crash_rate"].get("stoch", ""), r["mean"], r["worst_p1"]]
250
+ for i, r in enumerate(ranking, 1)])
251
+ # worst episodes per (era, mode): crashes first, then off-zone landings, then lowest reward
252
+ worst = []
253
+ for k in sorted(groups, key=lambda k: (era_sort_key(k[0]), k[1])):
254
+ worst.extend(sorted(groups[k], key=lambda r: (r[I_LAND], r[I_ZONE], r[I_REW]))[:worst_k])
255
+ write_csv(os.path.join(out_dir, f"worst_{phase}.csv"), FIELDS, worst)
256
+ return summaries
257
+
258
+
259
+ # running
260
+ def run_phase(pool, eras, modes, seeds, label):
261
+ tasks = [(era, s, mode == "stoch") for s in seeds for era in eras for mode in modes]
262
+ total, rows = len(tasks), []
263
+ step = max(1, total // 20)
264
+ t0 = time.time()
265
+ for i, row in enumerate(pool.imap_unordered(_run_task, tasks, chunksize=32), 1):
266
+ rows.append(row)
267
+ if i % step == 0 or i == total:
268
+ rate = i / (time.time() - t0)
269
+ print(f"[{label}] {i}/{total} episodes ({100*i/total:.0f}%) | {rate:.1f} eps/s "
270
+ f"| ETA {(total - i) / max(rate, 1e-9) / 60:.1f} min", flush=True)
271
+ return rows, total / (time.time() - t0)
272
+
273
+
274
+ def replay(era, seeds, mode):
275
+ w = load_all_weights([era]).get(era)
276
+ if w is None:
277
+ return
278
+ env = make_env(render_mode="human")
279
+ for seed in seeds:
280
+ row = _episode(env, w, era, seed, mode == "stoch")
281
+ status = "landed between flags" if row[I_ZONE] else ("landed outside flags" if row[I_LAND] else
282
+ ("time-out" if row[I_TMO] else "crashed"))
283
+ print(f"{era} | {row[I_MODE]} | seed {seed} | reward {row[I_REW]:.2f} | x {row[I_X]:+.3f} | {status}")
284
+ env.close()
285
+
286
+
287
+ def main():
288
+ ap = argparse.ArgumentParser(description="Large-sample evaluation of saved eras.")
289
+ ap.add_argument("--eras", nargs="*", help="eras to screen (default: all in ERAS_DIR)")
290
+ ap.add_argument("--screen-episodes", type=int, default=3000,
291
+ help="episodes PER MODE for every era (3000 x 2 modes = 6000 per era)")
292
+ ap.add_argument("--finalists", type=int, default=3, help="how many top eras go to phase 2")
293
+ ap.add_argument("--final-eras", nargs="*", help="pick the phase-2 eras yourself")
294
+ ap.add_argument("--final-episodes", type=int, default=20000)
295
+ ap.add_argument("--skip-final", action="store_true")
296
+ ap.add_argument("--modes", choices=["det", "stoch", "both"], default="both")
297
+ ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 1))
298
+ ap.add_argument("--seed-base", type=int, default=100_000)
299
+ ap.add_argument("--out", default=os.path.join(RUN_DIR, "robust_eval"))
300
+ ap.add_argument("--replay", metavar="ERA", help="render specific seeds of one era, then exit")
301
+ ap.add_argument("--seeds", nargs="*", type=int, help="seeds for --replay")
302
+ ap.add_argument("--mode", choices=["det", "stoch"], default="det", help="policy mode for --replay")
303
+ args = ap.parse_args()
304
+
305
+ if args.replay:
306
+ if not args.seeds:
307
+ ap.error("--replay needs --seeds")
308
+ replay(args.replay, args.seeds, args.mode)
309
+ return
310
+
311
+ if not os.path.isdir(ERAS_DIR):
312
+ print(f"No eras directory found at {ERAS_DIR}.")
313
+ return
314
+ eras = args.eras or list_eras()
315
+ modes = ["det", "stoch"] if args.modes == "both" else [args.modes]
316
+ weights = load_all_weights(eras)
317
+ eras = [e for e in eras if e in weights]
318
+ if not eras:
319
+ print("No era could be loaded.")
320
+ return
321
+ os.makedirs(args.out, exist_ok=True)
322
+
323
+ ctx = get_context("spawn") # spawn: workers import only numpy + gym, never TensorFlow
324
+ pool = ctx.Pool(args.workers, initializer=_init_worker, initargs=(weights,))
325
+ try:
326
+ seeds = [args.seed_base + i for i in range(args.screen_episodes)]
327
+ rows, rate = run_phase(pool, eras, modes, seeds, "screen")
328
+ summaries = report("screen", rows, args.out)
329
+
330
+ if args.skip_final or args.final_episodes <= 0:
331
+ return
332
+ if args.final_eras:
333
+ finalists = [e for e in args.final_eras if e in weights]
334
+ else:
335
+ finalists = [r["era"] for r in rank_eras(summaries)[:args.finalists]]
336
+ if not finalists:
337
+ print("No finalists selected.")
338
+ return
339
+ n_tasks = len(finalists) * len(modes) * args.final_episodes
340
+ print(f"\nFinalists: {', '.join(finalists)}")
341
+ print(f"Phase 2: {n_tasks} episodes, estimated {n_tasks / rate / 60:.1f} min at the screening speed "
342
+ f"({rate:.1f} eps/s). Ctrl-C to abort; phase-1 results are already saved.")
343
+ seeds = [args.seed_base + FINAL_SEED_OFFSET + i for i in range(args.final_episodes)]
344
+ rows, _ = run_phase(pool, finalists, modes, seeds, "final")
345
+ report("final", rows, args.out)
346
+ print(f"\nPer-episode CSVs, summaries and worst episodes are in {args.out}")
347
+ print("Replay an outlier: python evaluate_robust.py --replay <era> --seeds <seed> --mode <det|stoch>")
348
+ except KeyboardInterrupt:
349
+ print("\nInterrupted; terminating workers.")
350
+ pool.terminate()
351
+ finally:
352
+ pool.close()
353
+ pool.join()
354
+
355
+
356
+ if __name__ == "__main__":
357
+ main()
AI_ContinuousLunarLander/model.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import tensorflow as tf
3
+ from config import HIDDEN_DIMS, LOG_STD_INIT, SIGMA_FLOOR
4
+
5
+ LOG_2PI = float(np.log(2.0 * np.pi))
6
+
7
+
8
+ def gaussian_log_prob(x, mu, sigma):
9
+
10
+ return tf.reduce_sum(
11
+ -0.5 * (tf.square((x - mu) / sigma) + 2.0 * tf.math.log(sigma) + LOG_2PI),
12
+ axis=-1,
13
+ )
14
+
15
+
16
+ def gaussian_entropy(sigma):
17
+
18
+ return tf.reduce_sum(0.5 + 0.5 * LOG_2PI + tf.math.log(sigma), axis=-1)
19
+
20
+
21
+ class Actor(tf.keras.Model):
22
+ def __init__(self, action_dim):
23
+ super().__init__()
24
+ init = tf.keras.initializers
25
+ self.hidden_layers = [
26
+ tf.keras.layers.Dense(h, activation="tanh",
27
+ kernel_initializer=init.Orthogonal(gain=np.sqrt(2.0)))
28
+ for h in HIDDEN_DIMS
29
+ ]
30
+ # small gain -> initial mean actions close to 0
31
+ self.mu_layer = tf.keras.layers.Dense(
32
+ action_dim, kernel_initializer=init.Orthogonal(gain=0.01))
33
+ # add_weight is tracked as trainable on every Keras version
34
+ self.log_std = self.add_weight(
35
+ shape=(action_dim,), initializer=init.Constant(LOG_STD_INIT),
36
+ trainable=True, name="actor_log_std")
37
+
38
+ def call(self, state):
39
+ x = state
40
+ for layer in self.hidden_layers:
41
+ x = layer(x)
42
+ mu = self.mu_layer(x)
43
+ sigma = tf.exp(self.log_std) + SIGMA_FLOOR # floor by addition, not clipping
44
+ return mu, sigma
45
+
46
+
47
+ class Critic(tf.keras.Model):
48
+ def __init__(self):
49
+ super().__init__()
50
+ init = tf.keras.initializers
51
+ self.hidden_layers = [
52
+ tf.keras.layers.Dense(h, activation="tanh",
53
+ kernel_initializer=init.Orthogonal(gain=np.sqrt(2.0)))
54
+ for h in HIDDEN_DIMS
55
+ ]
56
+ self.value_layer = tf.keras.layers.Dense(
57
+ 1, kernel_initializer=init.Orthogonal(gain=1.0))
58
+
59
+ def call(self, state):
60
+ x = state
61
+ for layer in self.hidden_layers:
62
+ x = layer(x)
63
+ return self.value_layer(x)
AI_ContinuousLunarLander/sanity_checks.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+ import numpy as np
4
+ import tensorflow as tf
5
+ from agent import PPOAgent
6
+ from utils import compute_gae_vectorized
7
+
8
+
9
+ def test_gae():
10
+ # single env, rewards 1,1,1, values 0, terminal at the end, gamma = lambda = 1 -> [3, 2, 1]
11
+ r = np.ones((1, 3), np.float32); v = np.zeros((1, 3), np.float32)
12
+ adv, _ = compute_gae_vectorized(r, v, np.array([[0, 0, 1]], np.float32), np.zeros(1, np.float32), 1.0, 1.0)
13
+ assert np.allclose(adv, [[3, 2, 1]]), adv
14
+ # episode boundary in the middle: first two steps must not see the third
15
+ adv, _ = compute_gae_vectorized(r, v, np.array([[0, 1, 0]], np.float32), np.zeros(1, np.float32), 1.0, 1.0)
16
+ assert np.allclose(adv[0, :2], [2, 1]) and np.isclose(adv[0, 2], 1.0), adv
17
+ print("GAE ok")
18
+
19
+
20
+ def test_agent():
21
+ agent = PPOAgent(8, 2)
22
+ n_actor = len(agent.actor.trainable_variables)
23
+ assert n_actor == 7, f"expected 7 actor variables (3 kernels + 3 biases + log_std), got {n_actor}"
24
+
25
+ # one training step on random data; log_std must actually move
26
+ before = agent.actor.log_std.numpy().copy()
27
+ B = 256
28
+ s = tf.random.normal((B, 8)); a, lp, _ = agent.act_batch(s)
29
+ adv = tf.random.normal((B,)); ret = tf.random.normal((B,))
30
+ for _ in range(20):
31
+ m = agent.train_step(s, a, lp, ret, adv, tf.constant(0.001), tf.constant(0.2))
32
+ after = agent.actor.log_std.numpy()
33
+ assert not np.allclose(before, after), "log_std did not change -> not being trained"
34
+ assert all(np.isfinite(float(v.numpy())) for v in m.values()), m
35
+ print("agent ok | log_std", before, "->", after, "| sigma_mean", float(m["sigma_mean"].numpy()))
36
+
37
+ # first update from identical policy: ratio is 1, so KL ~ 0 and nothing is clipped
38
+ agent2 = PPOAgent(8, 2)
39
+ a2, lp2, _ = agent2.act_batch(s)
40
+ m2 = agent2.train_step(s, a2, lp2, ret, adv, tf.constant(0.0), tf.constant(0.2))
41
+ assert abs(float(m2["approx_kl"].numpy())) < 1e-5 and float(m2["clip_frac"].numpy()) == 0.0, m2
42
+ print("ratio==1 on first step ok")
43
+
44
+ # era save / restore must reproduce the weights
45
+ with tempfile.TemporaryDirectory() as d:
46
+ agent.save_era(os.path.join(d, "era_iter_1"))
47
+ fresh = PPOAgent(8, 2)
48
+ assert fresh.load_from(os.path.join(d, "era_iter_1"))
49
+ mu1, sg1 = agent.actor(s[:4]); mu2, sg2 = fresh.actor(s[:4])
50
+ assert np.allclose(mu1.numpy(), mu2.numpy()) and np.allclose(sg1.numpy(), sg2.numpy())
51
+ print("era save/restore ok")
52
+
53
+
54
+ if __name__ == "__main__":
55
+ test_gae()
56
+ test_agent()
57
+ print("\nAll sanity checks passed.")
AI_ContinuousLunarLander/train.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import psutil
4
+ import subprocess
5
+ import numpy as np
6
+ import tensorflow as tf
7
+ import gymnasium as gym
8
+ from agent import PPOAgent
9
+ from utils import make_env, explained_variance
10
+ from config import (
11
+ SEED, NUM_ENVS, TOTAL_ITERATIONS, EPOCHS_PER_BATCH, MINI_BATCH_SIZE, STEPS_PER_ENV,
12
+ GAMMA, REWARD_SCALE, TARGET_KL, LOG_DIR, CHECKPOINT_DIR, ERAS_DIR,
13
+ SAVE_FREQ, ERA_ITERATION_INTERVAL, PAD_HALF_WIDTH,
14
+ )
15
+
16
+ # Configure GPU memory growth
17
+ gpus = tf.config.list_physical_devices("GPU")
18
+ if gpus:
19
+ try:
20
+ for gpu in gpus:
21
+ tf.config.experimental.set_memory_growth(gpu, True)
22
+ except RuntimeError as e:
23
+ print(e)
24
+
25
+
26
+ def get_hardware_stats():
27
+ stats = {"cpu_percent": psutil.cpu_percent(interval=None),
28
+ "ram_percent": psutil.virtual_memory().percent}
29
+ try:
30
+ cmd = ["nvidia-smi", "--query-gpu=utilization.gpu,memory.used,memory.total,temperature.gpu",
31
+ "--format=csv,noheader,nounits"]
32
+ result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
33
+ line = result.stdout.strip().split("\n")[0]
34
+ gpu_util, mem_used, mem_total, temp = map(float, line.split(","))
35
+ stats["gpu_util_percent"] = gpu_util
36
+ stats["gpu_mem_percent"] = (mem_used / mem_total) * 100.0
37
+ stats["gpu_temp_c"] = temp
38
+ except Exception:
39
+ pass
40
+ return stats
41
+
42
+
43
+ def make_vector_env():
44
+ """Next-step autoreset (Gymnasium >= 1.0): after an episode ends, the NEXT env.step() ignores the
45
+ action, resets the env and returns reward 0. The rollout masks those fake transitions."""
46
+ assert int(gym.__version__.split(".")[0]) >= 1, "Requires Gymnasium >= 1.0 for next-step autoreset"
47
+ env_fns = [lambda: make_env(shaped=True) for _ in range(NUM_ENVS)] # landing-accuracy bonus on
48
+ try:
49
+ return gym.vector.SyncVectorEnv(env_fns, autoreset_mode=gym.vector.AutoresetMode.NEXT_STEP)
50
+ except (TypeError, AttributeError):
51
+ return gym.vector.SyncVectorEnv(env_fns)
52
+
53
+
54
+ def main():
55
+ np.random.seed(SEED)
56
+ tf.random.set_seed(SEED)
57
+ os.makedirs(LOG_DIR, exist_ok=True)
58
+ os.makedirs(CHECKPOINT_DIR, exist_ok=True)
59
+ os.makedirs(ERAS_DIR, exist_ok=True)
60
+ summary_writer = tf.summary.create_file_writer(LOG_DIR)
61
+
62
+ envs = make_vector_env()
63
+ state_dim = envs.single_observation_space.shape[0]
64
+ action_dim = envs.single_action_space.shape[0]
65
+
66
+ agent = PPOAgent(state_dim, action_dim)
67
+ restored = agent.load_checkpoint()
68
+ start_iteration = int(agent.global_step.numpy())
69
+ if restored and start_iteration > 0:
70
+ print(f">>> Resuming training from iteration {start_iteration} <<<")
71
+
72
+ try:
73
+ episode_rewards = np.zeros(NUM_ENVS)
74
+ prev_done = np.zeros(NUM_ENVS, dtype=bool)
75
+ states, _ = envs.reset(seed=SEED)
76
+ running_reward_ema = None
77
+ alpha = 0.05
78
+
79
+ for iteration in range(start_iteration, TOTAL_ITERATIONS):
80
+ t_start = time.time()
81
+ current_iter = iteration + 1
82
+ agent.update_schedules(current_iter)
83
+ current_clip = agent.current_clip_ratio
84
+
85
+ traj_states = np.zeros((NUM_ENVS, STEPS_PER_ENV, state_dim), dtype=np.float32)
86
+ traj_actions = np.zeros((NUM_ENVS, STEPS_PER_ENV, action_dim), dtype=np.float32)
87
+ traj_rewards = np.zeros((NUM_ENVS, STEPS_PER_ENV), dtype=np.float32)
88
+ traj_log_probs = np.zeros((NUM_ENVS, STEPS_PER_ENV), dtype=np.float32)
89
+ traj_dones = np.zeros((NUM_ENVS, STEPS_PER_ENV), dtype=np.float32)
90
+ traj_values = np.zeros((NUM_ENVS, STEPS_PER_ENV), dtype=np.float32)
91
+ traj_valid = np.ones((NUM_ENVS, STEPS_PER_ENV), dtype=np.float32)
92
+
93
+ batch_completed_rewards = []
94
+ batch_landed, batch_in_zone = 0, 0
95
+
96
+ # rollout
97
+ for step in range(STEPS_PER_ENV):
98
+ raw_actions, log_probs, values = agent.act_batch(tf.convert_to_tensor(states, dtype=tf.float32))
99
+ raw_actions, log_probs, values = raw_actions.numpy(), log_probs.numpy(), values.numpy()
100
+
101
+ # raw sample is stored for training; only the clipped action goes to the env
102
+ next_states, raw_rewards, terms, truncs, _ = envs.step(np.clip(raw_actions, -1.0, 1.0))
103
+ terms = np.asarray(terms, dtype=bool)
104
+ truncs = np.asarray(truncs, dtype=bool)
105
+ dones = terms | truncs
106
+ scaled_rewards = (np.asarray(raw_rewards, dtype=np.float32) / REWARD_SCALE)
107
+
108
+ # next_states holds the true final observation here (next-step autoreset).
109
+ trunc_only = truncs & ~terms
110
+ if trunc_only.any():
111
+ v_final = agent.value_batch(tf.convert_to_tensor(next_states, dtype=tf.float32)).numpy()
112
+ scaled_rewards = scaled_rewards + GAMMA * v_final * trunc_only
113
+
114
+ traj_states[:, step] = states
115
+ traj_actions[:, step] = raw_actions
116
+ traj_rewards[:, step] = scaled_rewards
117
+ traj_log_probs[:, step] = log_probs
118
+ traj_dones[:, step] = dones.astype(np.float32)
119
+ traj_values[:, step] = values
120
+ traj_valid[:, step] = (~prev_done).astype(np.float32) # fake post-done step -> 0
121
+ prev_done = dones.copy()
122
+
123
+ # Landing stats: a terminated step with positive reward is a landing (crash ~ -100);
124
+ # next_states holds the true final observation, so obs[0] is the landing x position.
125
+ landed_now = terms & (np.asarray(raw_rewards) > 0)
126
+ batch_landed += int(landed_now.sum())
127
+ batch_in_zone += int((landed_now & (np.abs(next_states[:, 0]) < PAD_HALF_WIDTH)).sum())
128
+
129
+ episode_rewards += raw_rewards
130
+ for idx in np.flatnonzero(dones):
131
+ batch_completed_rewards.append(episode_rewards[idx])
132
+ episode_rewards[idx] = 0.0
133
+ states = next_states
134
+
135
+ next_values = agent.value_batch(tf.convert_to_tensor(states, dtype=tf.float32)).numpy()
136
+ rollout_time = time.time() - t_start
137
+
138
+ advantages, returns = agent.compute_trajectory_advantages(
139
+ traj_rewards, traj_values, traj_dones, next_values
140
+ )
141
+
142
+ # flatten, drop fake steps, normalize
143
+ valid = traj_valid.reshape(-1).astype(bool)
144
+ states_arr = traj_states.reshape(-1, state_dim)[valid]
145
+ actions_arr = traj_actions.reshape(-1, action_dim)[valid]
146
+ old_log_probs_arr = traj_log_probs.reshape(-1)[valid]
147
+ values_arr = traj_values.reshape(-1)[valid]
148
+ advantages_arr = advantages.reshape(-1)[valid]
149
+ returns_arr = returns.reshape(-1)[valid]
150
+
151
+ ev = explained_variance(values_arr, returns_arr)
152
+ frac_saturated = float(np.mean(np.abs(actions_arr) >= 1.0))
153
+ advantages_arr = (advantages_arr - advantages_arr.mean()) / (advantages_arr.std() + 1e-8)
154
+
155
+ # PPO update
156
+ dataset_size = len(states_arr)
157
+ ent_coef = tf.constant(agent.entropy_coef, dtype=tf.float32)
158
+ clip_c = tf.constant(current_clip, dtype=tf.float32)
159
+ metric_sums, n_updates, stopped_early = {}, 0, False
160
+
161
+ for epoch in range(EPOCHS_PER_BATCH):
162
+ indices = np.random.permutation(dataset_size)
163
+ epoch_kl = []
164
+ # full minibatches only (a fresh permutation each epoch avoids bias, and shapes stay fixed)
165
+ for start in range(0, dataset_size - MINI_BATCH_SIZE + 1, MINI_BATCH_SIZE):
166
+ mb = indices[start:start + MINI_BATCH_SIZE]
167
+ m = agent.train_step(
168
+ tf.convert_to_tensor(states_arr[mb]),
169
+ tf.convert_to_tensor(actions_arr[mb]),
170
+ tf.convert_to_tensor(old_log_probs_arr[mb]),
171
+ tf.convert_to_tensor(returns_arr[mb]),
172
+ tf.convert_to_tensor(advantages_arr[mb]),
173
+ ent_coef, clip_c,
174
+ )
175
+ m = {k: float(v.numpy()) for k, v in m.items()}
176
+ epoch_kl.append(m["approx_kl"])
177
+ for k, v in m.items():
178
+ metric_sums[k] = metric_sums.get(k, 0.0) + v
179
+ n_updates += 1
180
+ if epoch_kl and np.mean(epoch_kl) > 1.5 * TARGET_KL:
181
+ stopped_early = True
182
+ break
183
+
184
+ metrics = {k: v / max(1, n_updates) for k, v in metric_sums.items()}
185
+
186
+ # logging
187
+ mean_batch_reward = np.mean(batch_completed_rewards) if batch_completed_rewards else 0.0
188
+ if batch_completed_rewards:
189
+ running_reward_ema = (mean_batch_reward if running_reward_ema is None
190
+ else (1 - alpha) * running_reward_ema + alpha * mean_batch_reward)
191
+
192
+ n_eps = max(1, len(batch_completed_rewards))
193
+ land_rate, zone_rate = batch_landed / n_eps, batch_in_zone / n_eps
194
+
195
+ hw_stats = get_hardware_stats()
196
+ with summary_writer.as_default():
197
+ tf.summary.scalar("Landing/LandedRate", land_rate, step=current_iter)
198
+ tf.summary.scalar("Landing/InZoneRate", zone_rate, step=current_iter)
199
+ for k, v in metrics.items():
200
+ tf.summary.scalar(f"PPO/{k}", v, step=current_iter)
201
+ tf.summary.scalar("PPO/explained_variance", ev, step=current_iter)
202
+ tf.summary.scalar("PPO/frac_actions_saturated", frac_saturated, step=current_iter)
203
+ tf.summary.scalar("PPO/epochs_run", epoch + 1, step=current_iter)
204
+ tf.summary.scalar("PPO/valid_fraction", dataset_size / (NUM_ENVS * STEPS_PER_ENV), step=current_iter)
205
+ tf.summary.scalar("Hyperparameters/LearningRate", agent.current_lr, step=current_iter)
206
+ tf.summary.scalar("Hyperparameters/EntropyCoef", agent.entropy_coef, step=current_iter)
207
+ if batch_completed_rewards:
208
+ tf.summary.scalar("Reward/MeanBatchEpisodeReward", mean_batch_reward, step=current_iter)
209
+ tf.summary.scalar("Reward/EMA_EpisodeReward", running_reward_ema, step=current_iter)
210
+ for key, tag in [("cpu_percent", "Hardware/CPU_Usage_Percent"),
211
+ ("ram_percent", "Hardware/RAM_Usage_Percent"),
212
+ ("gpu_util_percent", "Hardware/GPU_Util_Percent"),
213
+ ("gpu_mem_percent", "Hardware/GPU_Mem_Percent"),
214
+ ("gpu_temp_c", "Hardware/GPU_Temp_Celsius")]:
215
+ if key in hw_stats:
216
+ tf.summary.scalar(tag, hw_stats[key], step=current_iter)
217
+
218
+ print(f"=== Iter {current_iter}/{TOTAL_ITERATIONS} | Rew: {mean_batch_reward:8.2f} "
219
+ f"| KL: {metrics['approx_kl']:.4f}{'*' if stopped_early else ' '} "
220
+ f"| Land: {land_rate:.2f} | Zone: {zone_rate:.2f} "
221
+ f"| Clip: {metrics['clip_frac']:.2f} | Sigma: {metrics['sigma_mean']:.3f} "
222
+ f"| EV: {ev:5.2f} | Sat: {frac_saturated:.2f} "
223
+ f"| VLoss: {metrics['value_loss']:.4f} | {time.time() - t_start:.1f}s "
224
+ f"(rollout {rollout_time:.1f}s) ===")
225
+
226
+ # checkpoints
227
+ if current_iter % ERA_ITERATION_INTERVAL == 0 or current_iter == TOTAL_ITERATIONS:
228
+ era_path = agent.save_era(os.path.join(ERAS_DIR, f"era_iter_{current_iter}"))
229
+ print(f"Era saved: {era_path}")
230
+ if current_iter % SAVE_FREQ == 0:
231
+ agent.save_checkpoint()
232
+
233
+ except KeyboardInterrupt:
234
+ print("\nTraining interrupted by user. Saving current state...")
235
+ agent.save_checkpoint()
236
+
237
+ envs.close()
238
+
239
+
240
+ if __name__ == "__main__":
241
+ main()
AI_ContinuousLunarLander/trained_agent.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import shutil
4
+ import numpy as np
5
+ import tensorflow as tf
6
+ from agent import PPOAgent
7
+ from utils import make_env
8
+ from config import ERAS_DIR, BEST_ERA_DIR, EVAL_EPISODES, EVAL_SEED, PAD_BONUS, PAD_HALF_WIDTH
9
+
10
+
11
+ def _run_episode(env, agent, seed=None, render=False):
12
+ """Returns (true_reward, landed, in_zone). Envs here are UNSHAPED, so reward is the real score."""
13
+ state, _ = env.reset(seed=seed)
14
+ done, ep_reward = False, 0.0
15
+ terminated = False
16
+ while not done:
17
+ if render:
18
+ env.render()
19
+ mu, _ = agent.actor(tf.convert_to_tensor(state[np.newaxis, :], dtype=tf.float32))
20
+ # deterministic mean action: evaluates the policy itself, not its exploration noise
21
+ action = tf.clip_by_value(mu, -1.0, 1.0).numpy()[0]
22
+ state, reward, terminated, truncated, _ = env.step(action)
23
+ done = terminated or truncated
24
+ ep_reward += reward
25
+ # game_over is set on crashes; |x| >= 1 means the lander left the screen
26
+ landed = bool(terminated and not env.unwrapped.game_over and abs(state[0]) < 1.0)
27
+ in_zone = bool(landed and abs(state[0]) < PAD_HALF_WIDTH)
28
+ return ep_reward, landed, in_zone
29
+
30
+
31
+ def evaluate_era_checkpoint(agent, num_episodes=EVAL_EPISODES):
32
+ eval_env = make_env() # unshaped: scores stay comparable across runs
33
+ # same seeds for every era -> scores are directly comparable
34
+ results = [_run_episode(eval_env, agent, seed=EVAL_SEED + i) for i in range(num_episodes)]
35
+ eval_env.close()
36
+ scores = [r[0] for r in results]
37
+ return {
38
+ "mean": float(np.mean(scores)),
39
+ "max": float(np.max(scores)),
40
+ "land_rate": float(np.mean([r[1] for r in results])),
41
+ "zone_rate": float(np.mean([r[2] for r in results])),
42
+ }
43
+
44
+
45
+ def render_best_era(agent, render_episodes=3):
46
+ print(f"\nLaunching visual simulation of the best era for {render_episodes} episode(s)...")
47
+ render_env = make_env(render_mode="human")
48
+ for ep in range(render_episodes):
49
+ reward, landed, in_zone = _run_episode(render_env, agent, render=True)
50
+ status = "landed between flags" if in_zone else ("landed outside flags" if landed else "did not land")
51
+ print(f"Rendered Episode {ep + 1}/{render_episodes} | True Reward: {reward:.2f} | {status}")
52
+ render_env.close()
53
+
54
+
55
+ def _era_sort_key(name):
56
+ m = re.search(r"(\d+)$", name)
57
+ return int(m.group(1)) if m else -1 # numeric order (100 before 1000)
58
+
59
+
60
+ def main():
61
+ if not os.path.exists(ERAS_DIR):
62
+ print(f"No eras directory found at {ERAS_DIR}. Run training first.")
63
+ return
64
+
65
+ era_names = sorted(
66
+ [d for d in os.listdir(ERAS_DIR) if os.path.isdir(os.path.join(ERAS_DIR, d))],
67
+ key=_era_sort_key,
68
+ )
69
+ if not era_names:
70
+ print("No era subfolders detected inside eras directory.")
71
+ return
72
+
73
+ probe = make_env()
74
+ state_dim = probe.observation_space.shape[0]
75
+ action_dim = probe.action_space.shape[0]
76
+ probe.close()
77
+
78
+ agent = PPOAgent(state_dim, action_dim)
79
+ best_score, best_era_name, best_stats = -float("inf"), None, None
80
+
81
+ print(f"Evaluating {len(era_names)} saved eras over {EVAL_EPISODES} episodes each...")
82
+ for era_name in era_names:
83
+ era_path = os.path.join(ERAS_DIR, era_name)
84
+ # Restore straight from the era folder.
85
+ if not agent.load_from(era_path):
86
+ print(f"Skipping {era_name}: no checkpoint found.")
87
+ continue
88
+ s = evaluate_era_checkpoint(agent)
89
+ # Selection score: true mean reward plus the pad bonus scaled by how often it lands between flags
90
+ selection = s["mean"] + PAD_BONUS * s["zone_rate"]
91
+ print(f"-> {era_name} | Mean: {s['mean']:.2f} | Max: {s['max']:.2f} "
92
+ f"| Landed: {s['land_rate']:.0%} | Between flags: {s['zone_rate']:.0%} | Select: {selection:.2f}")
93
+ if selection > best_score:
94
+ best_score, best_era_name, best_stats = selection, era_name, s
95
+
96
+ if best_era_name is None:
97
+ print("No era could be evaluated.")
98
+ return
99
+
100
+ print(f"\nBest era: {best_era_name} | Mean: {best_stats['mean']:.2f} "
101
+ f"| Between flags: {best_stats['zone_rate']:.0%}")
102
+ best_path = os.path.join(ERAS_DIR, best_era_name)
103
+ shutil.copytree(best_path, BEST_ERA_DIR, dirs_exist_ok=True)
104
+ print(f"Best era weights copied into {BEST_ERA_DIR}")
105
+
106
+ agent.load_from(BEST_ERA_DIR)
107
+ try:
108
+ user_input = input("\nHow many render episodes do you want to watch (default 3): ").strip()
109
+ render_count = int(user_input) if user_input else 3
110
+ except ValueError:
111
+ print("Invalid input. Defaulting to 3 episodes.")
112
+ render_count = 3
113
+
114
+ render_best_era(agent, render_episodes=render_count)
115
+
116
+
117
+ if __name__ == "__main__":
118
+ main()
AI_ContinuousLunarLander/utils.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import gymnasium as gym
3
+ from config import (
4
+ ENV_NAME, CONTINUOUS_CONTROL, GRAVITY, ENABLE_WIND,
5
+ WIND_POWER, TURBULENCE_POWER, MAX_EPISODE_STEPS,
6
+ PAD_BONUS, PAD_BONUS_FALLOFF,
7
+ )
8
+
9
+
10
+ class PadBonus(gym.Wrapper):
11
+ """Adds a terminal bonus for landing close to the pad center (raw reward units).
12
+ Full bonus at x = 0, falling off linearly to zero at |x| = falloff (observation units)."""
13
+
14
+ def __init__(self, env, bonus=PAD_BONUS, falloff=PAD_BONUS_FALLOFF):
15
+ super().__init__(env)
16
+ self.bonus, self.falloff = bonus, falloff
17
+
18
+ def step(self, action):
19
+ obs, reward, terminated, truncated, info = super().step(action)
20
+ # game_over is set on crashes; |x| >= 1 means the lander left the screen (also -100)
21
+ landed = terminated and not self.env.unwrapped.game_over and abs(obs[0]) < 1.0
22
+ if landed:
23
+ reward += self.bonus * (1.0 - min(abs(obs[0]) / self.falloff, 1.0))
24
+ return obs, reward, terminated, truncated, info
25
+
26
+
27
+ def make_env(render_mode=None, shaped=False):
28
+ """Single place where the Mars LunarLander env is constructed.
29
+ shaped=True adds the landing-accuracy bonus. Use it for TRAINING envs only, so evaluation
30
+ and rendering keep reporting the true, unshaped reward."""
31
+ env = gym.make(
32
+ ENV_NAME,
33
+ render_mode=render_mode,
34
+ continuous=CONTINUOUS_CONTROL,
35
+ gravity=GRAVITY,
36
+ enable_wind=ENABLE_WIND,
37
+ wind_power=WIND_POWER,
38
+ turbulence_power=TURBULENCE_POWER,
39
+ max_episode_steps=MAX_EPISODE_STEPS,
40
+ )
41
+ if shaped:
42
+ env = PadBonus(env)
43
+ return env
44
+
45
+
46
+ def compute_gae_vectorized(rewards, values, dones, next_values, gamma, gae_lambda):
47
+ #Vectorized GAE computation for a batch of envs.
48
+ num_envs, T = rewards.shape
49
+ advantages = np.zeros_like(rewards, dtype=np.float32)
50
+ last = np.zeros(num_envs, dtype=np.float32)
51
+ for t in reversed(range(T)):
52
+ nonterminal = 1.0 - dones[:, t].astype(np.float32)
53
+ nxt = next_values if t == T - 1 else values[:, t + 1]
54
+ delta = rewards[:, t] + gamma * nxt * nonterminal - values[:, t]
55
+ last = delta + gamma * gae_lambda * nonterminal * last
56
+ advantages[:, t] = last
57
+ returns = advantages + values
58
+ return advantages, returns
59
+
60
+
61
+ def explained_variance(y_pred, y_true):
62
+ """1 - Var(y_true - y_pred) / Var(y_true). ~1 is perfect, <=0 means a useless critic."""
63
+ var_y = np.var(y_true)
64
+ return float("nan") if var_y == 0 else float(1.0 - np.var(y_true - y_pred) / var_y)
agent.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tensorflow as tf
3
+ from model import Actor, Critic, gaussian_log_prob, gaussian_entropy
4
+ from config import (
5
+ LEARNING_RATE, LR_MIN_FRACTION, GAMMA, GAE_LAMBDA, CLIP_RATIO,
6
+ VALUE_LOSS_COEF, INITIAL_ENTROPY_COEF, MAX_GRAD_NORM,
7
+ CHECKPOINT_DIR, TOTAL_ITERATIONS
8
+ )
9
+ from utils import compute_gae_vectorized
10
+
11
+
12
+ def _build_optimizer(optimizer, variables):
13
+ """Create optimizer slots without taking a real update step."""
14
+ try:
15
+ optimizer.build(variables)
16
+ except AttributeError:
17
+ pass # legacy optimizers create slots lazily; checkpoint restore is deferred instead
18
+
19
+
20
+ def _set_lr(optimizer, value):
21
+ try:
22
+ optimizer.learning_rate.assign(value)
23
+ except Exception:
24
+ optimizer.learning_rate = value
25
+
26
+
27
+ class PPOAgent:
28
+ def __init__(self, state_dim, action_dim):
29
+ self.gamma = GAMMA
30
+ self.gae_lambda = GAE_LAMBDA
31
+ self.base_clip_ratio = CLIP_RATIO
32
+ self.value_loss_coef = VALUE_LOSS_COEF
33
+ self.entropy_coef = INITIAL_ENTROPY_COEF
34
+
35
+ self.global_step = tf.Variable(0, trainable=False, dtype=tf.int64, name="global_step")
36
+
37
+ self.actor = Actor(action_dim)
38
+ self.critic = Critic()
39
+ # Build the networks so every variable (incl. log_std) exists before the optimizers
40
+ dummy_state = tf.zeros((1, state_dim), dtype=tf.float32)
41
+ self.actor(dummy_state)
42
+ self.critic(dummy_state)
43
+
44
+ # Fail loudly if log_std is not trained (sigma would silently stay frozen)
45
+ names = [v.name for v in self.actor.trainable_variables]
46
+ if not any("log_std" in n for n in names):
47
+ raise RuntimeError(f"actor log_std is not trainable! variables: {names}")
48
+ print(f"Actor trainable variables: {len(names)} (log_std tracked)")
49
+
50
+ self.actor_optimizer = tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE)
51
+ self.critic_optimizer = tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE)
52
+ _build_optimizer(self.actor_optimizer, self.actor.trainable_variables)
53
+ _build_optimizer(self.critic_optimizer, self.critic.trainable_variables)
54
+
55
+ self.checkpoint = tf.train.Checkpoint(
56
+ global_step=self.global_step,
57
+ actor=self.actor, critic=self.critic,
58
+ actor_optimizer=self.actor_optimizer, critic_optimizer=self.critic_optimizer,
59
+ )
60
+ self.checkpoint_manager = tf.train.CheckpointManager(
61
+ self.checkpoint, directory=CHECKPOINT_DIR, max_to_keep=5
62
+ )
63
+
64
+ # schedules / checkpoints
65
+ def update_schedules(self, current_iteration, total_iterations=TOTAL_ITERATIONS):
66
+ """Track the global step and linearly anneal the learning rate."""
67
+ self.global_step.assign(current_iteration)
68
+ frac = max(1.0 - (current_iteration - 1) / float(total_iterations), LR_MIN_FRACTION)
69
+ self.current_lr = LEARNING_RATE * frac
70
+ _set_lr(self.actor_optimizer, self.current_lr)
71
+ _set_lr(self.critic_optimizer, self.current_lr)
72
+
73
+ @property
74
+ def current_clip_ratio(self):
75
+ return self.base_clip_ratio
76
+
77
+ def save_checkpoint(self):
78
+ path = self.checkpoint_manager.save()
79
+ print(f"Checkpoint saved at step {self.global_step.numpy()}: {path}")
80
+
81
+ def load_checkpoint(self):
82
+ latest = self.checkpoint_manager.latest_checkpoint
83
+ if latest:
84
+ self.checkpoint.restore(latest)
85
+ print(f"Restored from checkpoint (resuming at global step {self.global_step.numpy()}): {latest}")
86
+ return True
87
+ print("No checkpoint found. Starting fresh from global step 0.")
88
+ return False
89
+
90
+ def save_era(self, directory):
91
+ """Write a self-contained checkpoint into its own folder (no file copying)."""
92
+ os.makedirs(directory, exist_ok=True)
93
+ return self.checkpoint.save(os.path.join(directory, "ckpt"))
94
+
95
+ def load_from(self, directory):
96
+ """Restore the newest checkpoint inside `directory` (used for eras / inference)."""
97
+ path = tf.train.latest_checkpoint(directory)
98
+ if path is None:
99
+ return False
100
+ self.checkpoint.restore(path).expect_partial()
101
+ return True
102
+
103
+ # acting
104
+ @tf.function(reduce_retracing=True)
105
+ def act_batch(self, states):
106
+ """Sample actions for all envs at once.
107
+ Returns the RAW Gaussian sample (stored for training), its log-prob and V(s).
108
+ Clip to [-1, 1] only when stepping the env."""
109
+ mu, sigma = self.actor(states)
110
+ raw = mu + sigma * tf.random.normal(tf.shape(mu))
111
+ log_prob = gaussian_log_prob(raw, mu, sigma)
112
+ value = tf.squeeze(self.critic(states), axis=-1)
113
+ return raw, log_prob, value
114
+
115
+ @tf.function(reduce_retracing=True)
116
+ def value_batch(self, states):
117
+ return tf.squeeze(self.critic(states), axis=-1)
118
+
119
+ def compute_trajectory_advantages(self, rewards, values, dones, next_values):
120
+ return compute_gae_vectorized(rewards, values, dones, next_values, self.gamma, self.gae_lambda)
121
+
122
+ # learning
123
+ @tf.function(reduce_retracing=True)
124
+ def train_step(self, states, actions, old_log_probs, returns, advantages, entropy_coef, clip_val):
125
+ with tf.GradientTape() as actor_tape:
126
+ mu, sigma = self.actor(states)
127
+ log_probs = gaussian_log_prob(actions, mu, sigma)
128
+ log_ratio = log_probs - old_log_probs
129
+ ratio = tf.exp(log_ratio)
130
+ surr1 = ratio * advantages
131
+ surr2 = tf.clip_by_value(ratio, 1.0 - clip_val, 1.0 + clip_val) * advantages
132
+ policy_loss = -tf.reduce_mean(tf.minimum(surr1, surr2))
133
+ entropy = gaussian_entropy(sigma) # scalar: summed over action dims
134
+ actor_loss = policy_loss - entropy_coef * entropy
135
+ actor_grads = actor_tape.gradient(actor_loss, self.actor.trainable_variables)
136
+ actor_grads, _ = tf.clip_by_global_norm(actor_grads, MAX_GRAD_NORM)
137
+ self.actor_optimizer.apply_gradients(zip(actor_grads, self.actor.trainable_variables))
138
+
139
+ with tf.GradientTape() as critic_tape:
140
+ values_pred = tf.squeeze(self.critic(states), axis=-1)
141
+ value_loss = tf.reduce_mean(tf.square(returns - values_pred)) # no value clipping
142
+ critic_loss = self.value_loss_coef * value_loss
143
+ critic_grads = critic_tape.gradient(critic_loss, self.critic.trainable_variables)
144
+ critic_grads, _ = tf.clip_by_global_norm(critic_grads, MAX_GRAD_NORM)
145
+ self.critic_optimizer.apply_gradients(zip(critic_grads, self.critic.trainable_variables))
146
+
147
+ return {
148
+ "policy_loss": policy_loss,
149
+ "value_loss": value_loss,
150
+ "entropy": entropy,
151
+ "approx_kl": tf.reduce_mean((ratio - 1.0) - log_ratio),
152
+ "clip_frac": tf.reduce_mean(tf.cast(tf.abs(ratio - 1.0) > clip_val, tf.float32)),
153
+ "sigma_mean": tf.reduce_mean(sigma),
154
+ }