forked from ClaireBookworm/polytopia_rl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_eval.py
More file actions
357 lines (293 loc) Β· 11.6 KB
/
Copy pathquick_eval.py
File metadata and controls
357 lines (293 loc) Β· 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#!/usr/bin/env python3
"""
Quick evaluation script to test and compare our actual Polytopia RL models
This script runs short training sessions with different approaches and measures:
1. Score improvement over time
2. Action selection patterns
3. Learning stability
4. Sample efficiency
Usage: python quick_eval.py
"""
import os
import sys
import time
import numpy as np
import torch
import matplotlib.pyplot as plt
from collections import defaultdict, deque
# Add repo root
repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__)))
if repo_root not in sys.path:
sys.path.insert(0, repo_root)
def evaluate_baseline_ppo():
"""Evaluate baseline PPO (standard CleanRL implementation)"""
print("π Evaluating Baseline PPO...")
try:
# Run baseline PPO for short training
import subprocess
result = subprocess.run([
sys.executable,
"py_rl/cleanrl/cleanrl/ppo.py",
"--total-timesteps", "5000",
"--num-steps", "32",
"--track", "False"
], cwd=repo_root, capture_output=True, text=True, timeout=300)
if result.returncode == 0:
# Parse output for scores
scores = parse_scores_from_output(result.stdout)
return {
'name': 'Baseline PPO',
'success': True,
'scores': scores,
'final_score': scores[-1] if scores else 0,
'output': result.stdout
}
else:
return {
'name': 'Baseline PPO',
'success': False,
'error': result.stderr
}
except Exception as e:
return {'name': 'Baseline PPO', 'success': False, 'error': str(e)}
def evaluate_action_quality_ppo():
"""Evaluate Action Quality PPO"""
print("π Evaluating Action Quality PPO...")
try:
import subprocess
result = subprocess.run([
sys.executable,
"py_rl/cleanrl/cleanrl/ppo_action_quality.py",
"--total-timesteps", "5000",
"--num-steps", "32",
"--track", "False"
], cwd=repo_root, capture_output=True, text=True, timeout=300)
if result.returncode == 0:
scores = parse_scores_from_output(result.stdout)
return {
'name': 'Action Quality PPO',
'success': True,
'scores': scores,
'final_score': scores[-1] if scores else 0,
'output': result.stdout
}
else:
return {
'name': 'Action Quality PPO',
'success': False,
'error': result.stderr
}
except Exception as e:
return {'name': 'Action Quality PPO', 'success': False, 'error': str(e)}
def evaluate_semantic_ppo():
"""Evaluate Semantic PPO with action type embeddings"""
print("π Evaluating Semantic PPO...")
try:
import subprocess
result = subprocess.run([
sys.executable,
"py_rl/cleanrl/cleanrl/ppo_semantic.py",
"--total-timesteps", "5000",
"--num-steps", "32",
"--track", "False"
], cwd=repo_root, capture_output=True, text=True, timeout=300)
if result.returncode == 0:
scores = parse_scores_from_output(result.stdout)
return {
'name': 'Semantic PPO',
'success': True,
'scores': scores,
'final_score': scores[-1] if scores else 0,
'output': result.stdout
}
else:
return {
'name': 'Semantic PPO',
'success': False,
'error': result.stderr
}
except Exception as e:
return {'name': 'Semantic PPO', 'success': False, 'error': str(e)}
def parse_scores_from_output(output: str) -> list:
"""Extract scores from training output"""
scores = []
lines = output.split('\n')
for line in lines:
# Look for score patterns in the output
if 'episodic_return=' in line:
try:
# Extract the score value
start = line.find('episodic_return=') + len('episodic_return=')
end = line.find(',', start) if ',' in line[start:] else len(line)
score_str = line[start:end].strip()
score = float(score_str)
scores.append(score)
except:
continue
# Also look for score patterns from our custom output
elif '] [' in line and len(line.split()) >= 2:
try:
# Pattern like "923 [624, 623, 726]"
parts = line.strip().split()
if len(parts) >= 2 and parts[0].isdigit():
score = float(parts[0])
scores.append(score)
except:
continue
return scores
def analyze_action_patterns(output: str) -> dict:
"""Analyze action selection patterns from output"""
action_stats = defaultdict(int)
lines = output.split('\n')
for line in lines:
# Look for action-related output
if 'RESEARCH' in line:
action_stats['RESEARCH'] += 1
elif 'MOVE' in line:
action_stats['MOVE'] += 1
elif 'ATTACK' in line:
action_stats['ATTACK'] += 1
elif 'BUILD' in line:
action_stats['BUILD'] += 1
elif 'END_TURN' in line:
action_stats['END_TURN'] += 1
return dict(action_stats)
def calculate_learning_metrics(scores: list) -> dict:
"""Calculate learning metrics from score progression"""
if len(scores) < 2:
return {'learning_rate': 0, 'stability': 0, 'improvement': 0}
# Learning rate (slope of improvement)
x = np.arange(len(scores))
y = np.array(scores)
learning_rate = np.polyfit(x, y, 1)[0] if len(scores) > 1 else 0
# Stability (inverse of variance)
stability = 1.0 / (np.var(scores) + 1e-6)
# Total improvement
improvement = scores[-1] - scores[0] if len(scores) > 0 else 0
return {
'learning_rate': learning_rate,
'stability': stability,
'improvement': improvement
}
def run_comprehensive_evaluation():
"""Run evaluation of all available models"""
print("π Quick Polytopia RL Model Evaluation")
print("=" * 60)
print("Testing models with 5K timesteps each...")
print()
# List of evaluation functions
evaluations = [
evaluate_baseline_ppo,
evaluate_action_quality_ppo,
evaluate_semantic_ppo,
]
results = []
start_time = time.time()
# Run each evaluation
for eval_func in evaluations:
try:
result = eval_func()
results.append(result)
if result['success']:
print(f"β
{result['name']}: Final score = {result['final_score']:.1f}")
else:
print(f"β {result['name']}: Failed - {result.get('error', 'Unknown error')}")
except Exception as e:
print(f"β {eval_func.__name__}: Exception - {str(e)}")
results.append({
'name': eval_func.__name__.replace('evaluate_', '').replace('_', ' ').title(),
'success': False,
'error': str(e)
})
total_time = time.time() - start_time
print(f"\nβ±οΈ Total evaluation time: {total_time:.1f} seconds")
# Analyze results
successful_results = [r for r in results if r['success']]
if not successful_results:
print("\nβ No models completed successfully!")
return results
print(f"\nπ RESULTS ANALYSIS")
print("=" * 40)
# Sort by final score
successful_results.sort(key=lambda x: x['final_score'], reverse=True)
for i, result in enumerate(successful_results, 1):
print(f"\n{i}. {result['name']}")
print(f" Final Score: {result['final_score']:.1f}")
if 'scores' in result and result['scores']:
metrics = calculate_learning_metrics(result['scores'])
print(f" Learning Rate: {metrics['learning_rate']:.3f}")
print(f" Improvement: {metrics['improvement']:.1f}")
print(f" Stability: {metrics['stability']:.2f}")
# Action pattern analysis
if 'output' in result:
action_patterns = analyze_action_patterns(result['output'])
if action_patterns:
print(f" Action Patterns: {action_patterns}")
# Recommendations
print(f"\nπ― RECOMMENDATIONS")
print("=" * 30)
if len(successful_results) > 0:
best = successful_results[0]
print(f"π Best Performer: {best['name']}")
print(f" Achieved score: {best['final_score']:.1f}")
if len(successful_results) > 1:
baseline_score = next((r['final_score'] for r in successful_results if 'Baseline' in r['name']), None)
if baseline_score:
improvements = []
for result in successful_results:
if 'Baseline' not in result['name']:
improvement = (result['final_score'] - baseline_score) / baseline_score * 100
improvements.append((result['name'], improvement))
if improvements:
print(f"\nπ Improvements over baseline:")
for name, improvement in improvements:
print(f" {name}: {improvement:+.1f}%")
# Plot results if we have data
plot_results(successful_results)
return results
def plot_results(results: list):
"""Plot comparison of model performance"""
if len(results) < 2:
print("Not enough successful results to plot.")
return
try:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# Plot 1: Final Scores
names = [r['name'] for r in results]
scores = [r['final_score'] for r in results]
bars = ax1.bar(range(len(names)), scores, alpha=0.7)
ax1.set_xlabel('Model')
ax1.set_ylabel('Final Score')
ax1.set_title('Final Performance Comparison')
ax1.set_xticks(range(len(names)))
ax1.set_xticklabels([n.replace(' ', '\n') for n in names], rotation=0)
# Highlight best performer
if scores:
best_idx = np.argmax(scores)
bars[best_idx].set_color('gold')
# Plot 2: Learning Curves
ax2.set_xlabel('Training Steps')
ax2.set_ylabel('Score')
ax2.set_title('Learning Curves')
for result in results:
if 'scores' in result and result['scores']:
scores = result['scores']
# Estimate timesteps (assuming even spacing)
timesteps = np.linspace(0, 5000, len(scores))
ax2.plot(timesteps, scores, label=result['name'], linewidth=2, marker='o')
ax2.legend()
ax2.grid(True, alpha=0.3)
plt.tight_layout()
# Save plot
timestamp = time.strftime("%Y%m%d_%H%M%S")
filename = f"quick_eval_results_{timestamp}.png"
plt.savefig(filename, dpi=150, bbox_inches='tight')
print(f"\nπ Plot saved as: {filename}")
plt.show()
except Exception as e:
print(f"Could not create plots: {e}")
def main():
"""Main evaluation function"""
return run_comprehensive_evaluation()
if __name__ == "__main__":
results = main()