-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmenu.py
More file actions
2633 lines (2196 loc) · 93.1 KB
/
menu.py
File metadata and controls
2633 lines (2196 loc) · 93.1 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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# menu.py — unified CLI for training, evaluation, TensorBoard, and manual play
# Compatible with: Hydra overrides, TB logs under mylogs/, flat model files in models/
#
# Structure overview:
# 1. Imports & constants — packages, paths, required deps list
# 2. Config helpers — read grid.yaml, discover games/algos/personas
# 3. UI helpers — ANSI palette, toggle_select, ask_index
# 4. Training execution — execute_training_run, print_training_summary
# 5. Main actions — run_training, train_all, train_complete_grid,
# run_manual_play, watch_*, level editor, etc.
# 6. Main menu loop — DISPATCH table + main()
# Imports
import subprocess
import webbrowser
import os
import sys
import platform
from pathlib import Path
import shutil
import time
from omegaconf import OmegaConf
import importlib
import random
import pygame
import numpy as np
# Enable ANSI escape codes on Windows 10+ terminals
if sys.platform == "win32":
try:
os.system("") # triggers VT100 mode in cmd.exe / powershell
except Exception:
pass
# Stable-Baselines3 Algo Imports
try:
from stable_baselines3 import PPO, A2C, DQN, SAC, TD3
from stable_baselines3.common.vec_env import DummyVecEnv, VecVideoRecorder
# Import Monitor for recording purposes
from stable_baselines3.common.monitor import Monitor
# Algo mapping
HAS_SB3 = True
ALGO_CLASS_MAP = {
"ppo": PPO,
"a2c": A2C,
"dqn": DQN,
"sac": SAC,
"td3": TD3,
}
except ImportError:
HAS_SB3 = False
ALGO_CLASS_MAP = {}
# Add winsound for Windows only
try:
import winsound
HAS_WINSOUND = True
except ImportError:
HAS_WINSOUND = False
# root folder setup
DEFAULT_TB_ROOT = "mylogs"
MODELS_DIR = Path("models/")
CONF_ROOT = Path("code/conf")
GRID_CONFIG_PATH = CONF_ROOT / "grid.yaml"
CONF_GAME_DIR = CONF_ROOT / "game"
CONF_REWARD_DIR = CONF_ROOT / "reward"
CONF_ALGO_DIR = CONF_ROOT / "algo"
CURRENT_ALGO = None
REQUIRED_PACKAGES = [
'torch>=1.9.0',
'stable-baselines3>=1.6.0',
'sb3-contrib>=1.6.0',
'gymnasium>=0.26.0',
'pygame>=2.1.0',
'numpy>=1.21.0',
'tensorboard>=2.8.0',
'hydra-core>=1.1.0',
'pyyaml>=6.0',
'omegaconf>=2.1.0',
'imageio',
'moviepy',
'streamlit',
'plotly'
]
# ============================================================================
# HELPER FUNCTIONS - Configuration & Setup
# ============================================================================
# video deps (lazy-loaded to avoid import issues)
def get_moviepy_editor():
"""
Try to obtain a MoviePy editor-like module in a version-agnostic way.
Returns:
mpy module (with ImageSequenceClip / VideoFileClip) or None.
"""
# Newer MoviePy: recommended pattern is `from moviepy import editor`
try:
from moviepy import editor as mpy
return mpy
except Exception:
pass
# Fallback: classic style `import moviepy.editor as mpy`
try:
import moviepy.editor as mpy
return mpy
except Exception:
pass
# Last resort: raw moviepy; some versions expose classes at top-level
try:
import moviepy as mpy
return mpy
except Exception:
pass
return None
# MOVE START UP
MPY = get_moviepy_editor()
HAS_MOVIEPY = MPY is not None
def check_and_install_dependencies():
"""Check if required packages are installed and install missing ones"""
print(_DIM(" Checking dependencies..."))
missing_packages = []
for package in REQUIRED_PACKAGES:
package_name = package.split('>=')[0].split('==')[0]
try:
__import__(package_name.replace('-', '_'))
except ImportError:
try:
if package_name == 'stable-baselines3':
import stable_baselines3
elif package_name == 'sb3-contrib':
import sb3_contrib
elif package_name == 'hydra-core':
import hydra
elif package_name == 'pyyaml':
import yaml
elif package_name == 'omegaconf':
import omegaconf
else:
raise ImportError()
except ImportError:
missing_packages.append(package)
if not missing_packages:
print(_GRN(" ✓ All dependencies are installed!"))
return True
print(_YEL(f" Missing packages: {', '.join(missing_packages)}"))
response = input(_BOLD("\n ⟫ Install missing dependencies? [y/N]: ")).strip().lower()
if response not in ('y', 'yes'):
print(_RED(" Cannot proceed without required dependencies."))
return False
print(_DIM(" Installing missing packages..."))
try:
cmd = [sys.executable, '-m', 'pip', 'install'] + missing_packages
subprocess.check_call(cmd)
print(_GRN(" ✓ Successfully installed all dependencies!"))
return True
except subprocess.CalledProcessError as e:
print(_RED(f" ✖ Failed to install dependencies: {e}"))
print(_DIM(" Please install manually using: pip install -r requirements.txt"))
return False
def setup_project():
"""Initial project setup"""
# if requirements don't exists makes requirements.txt
# Check and create requirements.txt if missing
requirements_path = Path("requirements.txt")
if not requirements_path.exists():
requirements_content = "\n".join(REQUIRED_PACKAGES) + "\n"
requirements_path.write_text(requirements_content)
# Grid config is the single source of truth for which games, algos, and
# personas are active. All get_available_* helpers call this first.
def load_grid_config():
"""Load grid.yaml configuration"""
if not GRID_CONFIG_PATH.exists():
return None
try:
return OmegaConf.load(GRID_CONFIG_PATH)
except Exception as e:
print(f"Error loading grid.yaml: {e}")
return None
def get_available_games():
"""
Read the 'games' key from grid.yaml and return a sorted list of game names.
Falls back to an empty list with a warning if the key is absent or the
file cannot be parsed. Game names here must match code/games/*_core.py files.
"""
cfg = load_grid_config()
if cfg is not None and 'games' in cfg and cfg.games:
return sorted(list(cfg.games))
print(_YEL(" Warning: No 'games' section found or it is empty in grid.yaml."))
return []
def get_available_algos_from_grid():
"""Get algorithms from grid.yaml that have corresponding YAML files"""
cfg = load_grid_config()
if cfg is None or 'models' not in cfg:
return []
grid_algos = list(cfg.models) if cfg.models else []
available = []
for algo in grid_algos:
algo_file = CONF_ALGO_DIR / f"{algo}.yaml"
if algo_file.exists():
available.append(algo)
else:
print(f"Warning: Algorithm '{algo}' in grid.yaml but no file at {algo_file}")
return sorted(available)
def get_available_personas_from_grid():
"""Get personas from grid.yaml."""
cfg = load_grid_config()
if cfg is not None and 'personas' in cfg and cfg.personas:
return sorted(list(cfg.personas))
print(_YEL(" Warning: No 'personas' section found or it is empty in grid.yaml."))
return []
def get_personas_for_game(game: str):
"""Return only personas from grid.yaml whose YAML stem starts with '<game>_'"""
all_personas = get_available_personas_from_grid()
filtered = [p for p in all_personas if p.startswith(f"{game}_")]
return filtered if filtered else all_personas
# Architecture metadata used by the menu
_ARCH_INFO = {
"lightmobile": ("LightMobile / Depthwise", "LightMobileExtractor - lightweight depthwise stack"),
"spatialattention": ("SpatialAttention", "SpatialAttentionExtractor"),
"channelattention": ("ChannelAttention", "ChannelAttentionExtractor"),
"deepchannelattention":("DeepChannelAttention", "DeepChannelAttentionExtractor"),
"mlp": ("MlpPolicy", "default flat observation policy"),
}
def get_available_architectures_from_grid():
"""Return architectures list from grid.yaml, falling back to the extractor tag set if absent."""
cfg = load_grid_config()
if cfg is not None and "architectures" in cfg and cfg.architectures:
return list(cfg.architectures)
return ["lightmobile", "spatialattention", "channelattention", "deepchannelattention"]
def get_trained_models_count():
"""Count total number of trained models in models/best/"""
BEST_DIR = MODELS_DIR / "best"
if not BEST_DIR.exists():
return 0
model_folders = [f for f in BEST_DIR.iterdir() if f.is_dir() and (f / "best_model.zip").exists()]
return len(model_folders)
def get_trained_games_from_models_flat():
"""Infer trained games from model folders in models/best/"""
BEST_DIR = MODELS_DIR / "best"
if not BEST_DIR.exists():
return []
model_folders = [f for f in BEST_DIR.iterdir() if f.is_dir() and (f / "best_model.zip").exists()]
if not model_folders:
return []
games = set()
for folder in model_folders:
parts = folder.name.split("_")
if len(parts) >= 5:
games.add(parts[0])
return sorted(games)
def get_model_folders():
"""Get all model folders containing best_model.zip"""
BEST_DIR = MODELS_DIR / "best"
if not BEST_DIR.exists():
return []
return [f for f in BEST_DIR.iterdir() if f.is_dir() and (f / "best_model.zip").exists()]
# ============================================================================
# HELPER FUNCTIONS - User Interface
# ============================================================================
def open_browser(url):
"""Open URL in default browser, cross-platform"""
try:
webbrowser.open(url)
except Exception:
try:
if platform.system() == "Linux":
os.system(f"xdg-open {url}")
elif platform.system() == "Windows":
os.system(f"start {url}")
elif platform.system() == "Darwin":
os.system(f"open {url}")
except Exception:
pass
print(_DIM(f" If your browser did not open automatically, go to: {url}"))
def ask_index(prompt, options, add_back=True, default=None):
"""
Simple numbered-list prompt — used for linear (non-toggle) selections.
Prints the option list, reads an integer, and returns the chosen item.
Returns None if the user selects the auto-appended "Back" entry.
Supports an optional default value selected by pressing Enter.
"""
if not options:
print(_DIM(" No options available."))
return None
print(prompt)
for i, opt in enumerate(options, 1):
default_flag = " (default)" if opt == default else ""
print(f" {i}. {opt}{default_flag}")
back_idx = len(options) + 1
if add_back:
print(f" {back_idx}. Back")
prompt_text = f"Select (1-{back_idx if add_back else len(options)})"
if default:
prompt_text += f" or Enter for [{default}]"
prompt_text += ": "
choice = input(prompt_text).strip()
if choice == "" and default:
return default
try:
num = int(choice)
if add_back and num == back_idx:
return None
if 1 <= num <= len(options):
return options[num - 1]
except ValueError:
pass
print(_RED(" ✖ Invalid selection."))
return None
def ensure_current_algo():
"""Ensure CURRENT_ALGO is set, defaulting to PPO if available"""
global CURRENT_ALGO
if CURRENT_ALGO is None:
algos = get_available_algos_from_grid()
if algos:
CURRENT_ALGO = "ppo" if "ppo" in algos else algos[0]
def get_training_runtime_defaults():
"""Read default device / env-count from grid.yaml."""
cfg = load_grid_config()
default_n_envs = 1
default_device = "cpu"
if cfg is not None:
try:
default_n_envs = int(cfg.get("n_envs", default_n_envs))
except (TypeError, ValueError):
default_n_envs = 1
default_device = str(cfg.get("device", default_device) or default_device).strip().lower()
if default_n_envs < 1:
default_n_envs = 1
if default_device not in ("cpu", "cuda"):
default_device = "cpu"
return default_n_envs, default_device
def prompt_training_runtime_overrides():
"""
Ask for optional launch-only runtime overrides.
Enter keeps the grid.yaml value; typed input overrides it for this menu run.
"""
default_n_envs, default_device = get_training_runtime_defaults()
envs_raw = input(_DIM(f"\n Env count [{default_n_envs}] (Enter to keep grid default): ")).strip()
n_envs_override = None
if envs_raw:
try:
n_envs_override = int(envs_raw)
if n_envs_override < 1:
raise ValueError
except ValueError:
print(_RED(" Invalid env count. Use a positive integer."))
return None
device_raw = input(_DIM(f" Device [{default_device}] (cpu/cuda, Enter to keep grid default): ")).strip().lower()
device_override = None
if device_raw:
if device_raw == "gpu":
device_raw = "cuda"
if device_raw not in ("cpu", "cuda"):
print(_RED(" Invalid device. Use 'cpu' or 'cuda'."))
return None
device_override = device_raw
return {
"default_n_envs": default_n_envs,
"default_device": default_device,
"n_envs_override": n_envs_override,
"device_override": device_override,
}
def toggle_select(title, options, default_indices=None, min_select=1, show_desc=None):
"""
Interactive toggle-style multi-select used throughout the training menus.
Renders a numbered checklist where each item can be toggled on/off.
Supports comma-separated input ("1,3") and ranges ("1-3") in one go.
Returns the confirmed list of selected items, or None if user typed "0" (back).
Parameters
----------
title : str — section header shown above the list
options : list[str] — the items to display
default_indices: list[int] — 0-based indices that start toggled ON
min_select : int — minimum items required before confirming
show_desc : dict | None — {option: hint_string} for extra detail per row
Type a number to flip that item on/off. Press Enter to confirm.
Returns a list of selected items, or None if the user backs out.
show_desc: optional dict {option: description_string} for extra info per row.
"""
selected = set(default_indices or [0]) # 0-based indices
while True:
print(f"\n {_BOLD(_CYAN('▸'))} {_BOLD(title)} {_DIM('(toggle · Enter to confirm)')}")
print(_DIM(" Type numbers to toggle · Enter to confirm · 0 = Back"))
print()
for i, opt in enumerate(options):
tick = _GRN("✓") if i in selected else _DIM("o")
desc = ""
if show_desc:
d = show_desc.get(opt, "")
if d:
desc = _DIM(f" {d}")
print(f" {_YEL(f'[{i+1}]')} {tick} {opt}{desc}")
print()
raw = input(_BOLD(" ⟫ ")).strip()
if raw == "":
if len(selected) >= min_select:
return [options[i] for i in sorted(selected)]
print(_RED(f" Please select at least {min_select} item(s)."))
continue
if raw == "0":
return None
# Support comma-separated and range input: "1,3" or "1-3"
tokens = []
for part in raw.replace(" ", "").split(","):
if "-" in part:
try:
a, b = part.split("-", 1)
tokens.extend(range(int(a), int(b) + 1))
except ValueError:
pass
else:
try:
tokens.append(int(part))
except ValueError:
pass
for n in tokens:
idx = n - 1
if 0 <= idx < len(options):
if idx in selected:
selected.discard(idx)
else:
selected.add(idx)
else:
print(_RED(f" Invalid: {n}"))
# ============================================================================
# TRAINING EXECUTION - Core Logic (DRY refactor)
# ============================================================================
def execute_training_run(
game,
algo,
persona,
skill,
tb_root=DEFAULT_TB_ROOT,
architecture=None,
n_envs_override=None,
device_override=None,
):
"""
Build and run a single Hydra training command via subprocess.
Constructs the `python -m code.scripts.train` invocation with the
appropriate +game, +model, +persona, +skill, tb_root, and optionally
+architecture overrides. Returns True on success, False on non-zero exit.
KeyboardInterrupt is re-raised so the caller's loop can catch and abort.
"""
cmd = [
sys.executable, "-m", "code.scripts.train",
f"+game={game}",
f"+model={algo}",
f"+persona={persona}",
f"+skill={skill}",
f"tb_root={tb_root}",
]
if architecture:
cmd.append(f"+architecture={architecture}")
if n_envs_override is not None:
cmd.append(f"n_envs={int(n_envs_override)}")
if device_override:
cmd.append(f"device={device_override}")
print(_DIM(" >>> ") + _WHT(" ".join(cmd)) + "\n")
# Runs the hydra CMD training script with specified parameters
try:
subprocess.run(cmd, check=True)
return True
except subprocess.CalledProcessError as e:
print(_RED(f" ✖ Failed: {game} | {algo} | {persona} | {skill} (exit {e.returncode})"))
return False
except KeyboardInterrupt:
raise # Re-raise to be caught by caller
def print_training_summary(total, successful, failed):
"""Print final training summary with sound notification"""
print()
print(_DIM(" ─" * 11))
print(f" {_BOLD(_GRN('✓'))} {_BOLD('TRAINING COMPLETE')}")
print(_DIM(" ─" * 11))
print(f" {_DIM('Successful:')} {_GRN(f'{successful}/{total}')}")
if failed > 0:
print(f" {_DIM('Failed :')} {_RED(f'{failed}/{total}')}")
print(f" {_DIM('Logs →')} {_WHT(DEFAULT_TB_ROOT + '/')}")
print(f" {_DIM('Models→')} {_WHT(str(MODELS_DIR) + '/best/')}")
if HAS_WINSOUND and failed == 0:
winsound.PlaySound("chime.wav", winsound.SND_FILENAME)
print()
# ============================================================================
# MAIN ACTIONS
# ============================================================================
def run_training():
"""Training run — multi-toggle selectors for algo, persona, skill, architecture."""
global CURRENT_ALGO
clear_cli()
_print_header(
get_available_games(), get_available_algos_from_grid(),
get_trained_games_from_models_flat(), get_trained_models_count()
)
_section("TRAIN › Configure Run")
# ── Game (single select via toggle) ───────────────────────────
games = get_available_games()
if not games:
print(_RED(" No game configurations found in grid.yaml"))
return
game_sel = toggle_select("Game", games, default_indices=[0], min_select=1)
if game_sel is None:
return
game = game_sel[0] # single game for now
# ── Algorithm ─────────────────────────────────────────────────
algos = get_available_algos_from_grid()
if not algos:
print(_RED(" No algorithm configurations found"))
return
def_algo_idx = next((i for i, a in enumerate(algos) if a == CURRENT_ALGO), 0)
algo_sel = toggle_select("Algorithm", algos, default_indices=[def_algo_idx], min_select=1)
if algo_sel is None:
return
CURRENT_ALGO = algo_sel[0]
# ── Personas ──────────────────────────────────────────────────
personas = get_personas_for_game(game)
if not personas:
print(_RED(f" No personas found for game='{game}'"))
return
persona_sel = toggle_select("Personas", personas, default_indices=[0])
if persona_sel is None:
return
# ── Skills ────────────────────────────────────────────────────
skills_opts = ["Novice", "Expert", "Custom steps"]
skill_sel = toggle_select("Skills", skills_opts, default_indices=[0])
if skill_sel is None:
return
# Custom steps shortcut — if selected, prompt once
custom_steps = None
if "Custom steps" in skill_sel:
steps_str = input(_BOLD("\n ⟫ Custom total steps (e.g. 300000): ")).strip()
try:
custom_steps = int(steps_str)
except ValueError:
print(_RED(" Invalid number."))
return
skill_sel = [s for s in skill_sel if s != "Custom steps"]
# ── Architectures ─────────────────────────────────────────────
archs = get_available_architectures_from_grid()
def_arch_idx = next((i for i, a in enumerate(archs) if a == "spatialattention"), 0)
arch_desc = {a: f"{_ARCH_INFO[a][0]:<28} {_ARCH_INFO[a][1]}" for a in archs if a in _ARCH_INFO}
arch_sel = toggle_select("Architecture", archs, default_indices=[def_arch_idx], min_select=1,
show_desc=arch_desc)
if arch_sel is None:
return
# ── TensorBoard root ──────────────────────────────────────────
tb_root = input(_DIM(f"\n TensorBoard root [{DEFAULT_TB_ROOT}] (Enter to keep): ")).strip() or DEFAULT_TB_ROOT
runtime = prompt_training_runtime_overrides()
if runtime is None:
return
n_envs_override = runtime["n_envs_override"]
device_override = runtime["device_override"]
envs_display = str(n_envs_override) if n_envs_override is not None else f"{runtime['default_n_envs']} (grid)"
device_display = device_override if device_override is not None else f"{runtime['default_device']} (grid)"
# ── Summary ───────────────────────────────────────────────────
run_skills = list(skill_sel)
if custom_steps is not None:
run_skills.append(f"Custom({custom_steps})")
total = len(arch_sel) * len(algo_sel) * len(persona_sel) * max(len(run_skills), 1)
print()
print(f" {_BOLD(_CYAN('▸'))} {_BOLD('Run Summary')}")
print(f" {_DIM('─' * 50)}")
print(f" {_DIM('Game :')} {_WHT(game)}")
print(f" {_DIM('Algos :')} {_GRN(', '.join(algo_sel))}")
personas_short = ', '.join(p.replace(f'{game}_', '') for p in persona_sel)
print(f" {_DIM('Personas :')} {_GRN(personas_short)} {_DIM(f'({len(persona_sel)})')}")
print(f" {_DIM('Skills :')} {_GRN(', '.join(run_skills))}")
print(f" {_DIM('Archs :')} {_GRN(', '.join(arch_sel))}")
print(f" {_DIM('Env count :')} {_GRN(envs_display)}")
print(f" {_DIM('Device :')} {_GRN(device_display)}")
print(f" {_DIM('Total runs:')} {_WHT(str(total))}")
print(f" {_DIM('─' * 50)}")
print()
confirm = input(_BOLD(" ⟫ Proceed? [Y/n]: ")).strip().lower()
if confirm in ("n", "no"):
print(_DIM(" Aborted."))
return
# ── Execute ───────────────────────────────────────────────────
completed = 0; failed = 0
try:
for arch in arch_sel:
for algo in algo_sel:
for persona in persona_sel:
if custom_steps is not None:
completed += 1
print(_DIM(f"\n [{completed}/{total}]") + f" {game} | {algo} | {persona} | Custom {custom_steps} | {arch}")
cmd = [
sys.executable, "-m", "code.scripts.train",
f"+game={game}", f"+model={algo}", f"+persona={persona}",
"skill=Custom", f"+skills.Custom={custom_steps}",
f"tb_root={tb_root}", f"+architecture={arch}",
]
if n_envs_override is not None:
cmd.append(f"n_envs={int(n_envs_override)}")
if device_override:
cmd.append(f"device={device_override}")
print(">>> " + " ".join(cmd))
try:
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError:
failed += 1
for skill in skill_sel:
completed += 1
print(_DIM(f"\n [{completed}/{total}]") + f" {game} | {algo} | {persona} | {skill} | {arch}")
ok = execute_training_run(
game, algo, persona, skill, tb_root, arch,
n_envs_override=n_envs_override,
device_override=device_override,
)
if not ok:
failed += 1
except KeyboardInterrupt:
print(_RED(f"\n Interrupted. Completed {completed-1}/{total}"))
return
print_training_summary(total, completed - failed, failed)
def train_all_models_for_game():
"""Train all selected (algo x persona x skill) for ONE game — toggle selectors."""
global CURRENT_ALGO
clear_cli()
_print_header(
get_available_games(), get_available_algos_from_grid(),
get_trained_games_from_models_flat(), get_trained_models_count()
)
_section("TRAIN ALL › One Game")
# ── Game ──────────────────────────────────────────────────────
games = get_available_games()
if not games:
print(_RED(" No game configurations found in grid.yaml"))
return
game_sel = toggle_select("Game", games, default_indices=[0], min_select=1)
if game_sel is None:
return
game = game_sel[0]
# ── Algorithms ────────────────────────────────────────────────
algos = get_available_algos_from_grid()
if not algos:
print(_RED(" No algorithm configurations found"))
return
ensure_current_algo()
def_algo_idx = next((i for i, a in enumerate(algos) if a == CURRENT_ALGO), 0)
algo_sel = toggle_select("Algorithms", algos,
default_indices=list(range(len(algos)))) # all ON by default
if algo_sel is None:
return
CURRENT_ALGO = algo_sel[0]
# ── Personas ──────────────────────────────────────────────────
personas = get_personas_for_game(game)
if not personas:
print(_RED(f" No personas for game '{game}'"))
return
persona_sel = toggle_select("Personas", personas,
default_indices=list(range(len(personas))))
if persona_sel is None:
return
# ── Skills ────────────────────────────────────────────────────
skills_opts = ["Novice", "Expert"]
skill_sel = toggle_select("Skills", skills_opts,
default_indices=[0, 1]) # both ON by default
if skill_sel is None:
return
# ── Architecture ──────────────────────────────────────────────
archs = get_available_architectures_from_grid()
def_arch_idx = next((i for i, a in enumerate(archs) if a == "spatialattention"), 0)
arch_desc = {a: f"{_ARCH_INFO[a][0]:<28} {_ARCH_INFO[a][1]}" for a in archs if a in _ARCH_INFO}
arch_sel = toggle_select("Architecture", archs, default_indices=[def_arch_idx], min_select=1,
show_desc=arch_desc)
if arch_sel is None:
return
runtime = prompt_training_runtime_overrides()
if runtime is None:
return
n_envs_override = runtime["n_envs_override"]
device_override = runtime["device_override"]
envs_display = str(n_envs_override) if n_envs_override is not None else f"{runtime['default_n_envs']} (grid)"
device_display = device_override if device_override is not None else f"{runtime['default_device']} (grid)"
# ── Summary + confirm ─────────────────────────────────────────
total_runs = len(arch_sel) * len(algo_sel) * len(persona_sel) * len(skill_sel)
print()
print(f" {_BOLD(_CYAN('▸'))} {_BOLD('Run Summary')}")
print(f" {_DIM('─' * 50)}")
print(f" {_DIM('Game :')} {_WHT(game)}")
print(f" {_DIM('Algos :')} {_GRN(', '.join(algo_sel))}")
personas_short = ', '.join(p.replace(f'{game}_', '') for p in persona_sel)
print(f" {_DIM('Personas :')} {_GRN(personas_short)} {_DIM(f'({len(persona_sel)})')}")
print(f" {_DIM('Skills :')} {_GRN(', '.join(skill_sel))}")
print(f" {_DIM('Archs :')} {_GRN(', '.join(arch_sel))}")
print(f" {_DIM('Env count :')} {_GRN(envs_display)}")
print(f" {_DIM('Device :')} {_GRN(device_display)}")
print(f" {_DIM('Total runs:')} {_WHT(str(total_runs))}")
print(f" {_DIM('─' * 50)}")
confirm = input(_BOLD("\n ⟫ Proceed? [Y/n]: ")).strip().lower()
if confirm in ("n", "no"):
print(_DIM(" Aborted."))
return
# ── Execute ───────────────────────────────────────────────────
completed = 0; failed = 0
try:
for arch in arch_sel:
for algo in algo_sel:
for persona in persona_sel:
for skill in skill_sel:
completed += 1
print(_DIM(f"\n [{completed}/{total_runs}]") + f" {game} | {algo} | {persona} | {skill} | {arch}")
ok = execute_training_run(
game, algo, persona, skill, architecture=arch,
n_envs_override=n_envs_override,
device_override=device_override,
)
if not ok:
failed += 1
except KeyboardInterrupt:
print(_RED(f"\n Interrupted. Completed {completed-1}/{total_runs}"))
return
print_training_summary(total_runs, completed - failed, failed)
def train_complete_grid():
"""Train ALL (game x algo x persona x skill) combinations"""
clear_cli()
_print_header(
get_available_games(), get_available_algos_from_grid(),
get_trained_games_from_models_flat(), get_trained_models_count()
)
_section("TRAIN FULL GRID › All Games × Algos × Personas")
games = get_available_games()
algos = get_available_algos_from_grid()
if not games:
print(_RED(" No game configurations found in grid.yaml"))
return
if not algos:
print(_RED(" No algorithm configurations found in grid.yaml"))
return
# Calculate total runs
total_runs = 0
breakdown = []
for game in games:
personas = get_personas_for_game(game)
if not personas:
continue
runs_for_game = len(algos) * len(personas) * 2
total_runs += runs_for_game
breakdown.append(f" {_WHT(game)}: {len(personas)} persona(s) × {len(algos)} algo(s) × 2 skills = {_GRN(str(runs_for_game))} runs")
if total_runs == 0:
print(_RED("\n No valid training configurations found."))
return
print(f"\n Total runs: {_WHT(str(total_runs))} across {_WHT(str(len(games)))} game(s)")
print()
for line in breakdown:
print(line)
# Architecture toggle
archs = get_available_architectures_from_grid()
def_arch_idx = next((i for i, a in enumerate(archs) if a == "spatialattention"), 0)
arch_desc = {a: f"{_ARCH_INFO[a][0]:<28} {_ARCH_INFO[a][1]}" for a in archs if a in _ARCH_INFO}
arch_sel = toggle_select("Architecture", archs, default_indices=[def_arch_idx], min_select=1,
show_desc=arch_desc)
if arch_sel is None:
return
runtime = prompt_training_runtime_overrides()
if runtime is None:
return
n_envs_override = runtime["n_envs_override"]
device_override = runtime["device_override"]
envs_display = str(n_envs_override) if n_envs_override is not None else f"{runtime['default_n_envs']} (grid)"
device_display = device_override if device_override is not None else f"{runtime['default_device']} (grid)"
total_runs *= len(arch_sel)
print(f"\n Runtime: {_GRN(envs_display)} env(s) | {_GRN(device_display)}")
confirm = input(_BOLD(f"\n ⟫ Proceed with {total_runs} runs using [{', '.join(arch_sel)}]? [Y/n]: ")).strip().lower()
if confirm in ("n", "no"):
print(_DIM(" Aborted."))
return
# Execute training grid
skills = ["Novice", "Expert"]
completed = 0
failed = 0
try:
for arch in arch_sel:
for game in games:
personas = get_personas_for_game(game)
if not personas:
continue
for algo in algos:
for persona in personas:
for skill in skills:
completed += 1
print(_DIM(f"\n [{completed}/{total_runs}]") + f" {game} | {algo} | {persona} | {skill} | {arch}")
success = execute_training_run(
game, algo, persona, skill, architecture=arch,
n_envs_override=n_envs_override,
device_override=device_override,
)
if not success:
failed += 1
except KeyboardInterrupt:
print(_RED(f"\n Interrupted. Completed {completed-1}/{total_runs}"))
return
print_training_summary(total_runs, completed - failed, failed)
# Currently NOT IN USE - needs adaptation
def run_evaluation():
"""Evaluate all trained models for a selected game"""
_section("EVALUATE › Quick Eval")
BEST_DIR = MODELS_DIR / "best"
if not BEST_DIR.exists():
print("[!] models/best/ does not exist — please train some models first.")
return
model_folders = get_model_folders()
if not model_folders:
print("No best_model.zip files found in models/best/.")
return
games = sorted(set(f.name.split("_")[0] for f in model_folders))
if not games:
print("No recognized games found in models/best/.")
return
game = ask_index("Games with trained models", games)
if game is None:
return
model_dirs = [f for f in model_folders if f.name.startswith(game)]
if not model_dirs:
print(f"No best_model.zip folders found for game='{game}' in {BEST_DIR}")
return
_hint = _DIM("— 5 eps each")
print(f" {_DIM(chr(8250))} {_WHT(str(len(model_dirs)))} model(s) for {_GRN(game)} {_hint}")
for model_dir in model_dirs:
model_zip = model_dir / "best_model.zip"
model_name = model_dir.name
parts = model_name.split("_")
algo = parts[1] if len(parts) > 1 else "ppo"
out_json = MODELS_DIR / f"{model_name}_eval.json"
metrics_class = f"code.metrics.{game}_balance.{game.capitalize()}BalanceStats"
cmd = [
sys.executable, "-m", "code.scripts.evaluate",
"--game", game, "--algo", algo, "--model", str(model_zip),
"--episodes", "5", "--render", "none",
"--out", str(out_json), "--metrics", metrics_class,
]
print(">>>", " ".join(cmd))
subprocess.run(cmd)
print(_GRN(" ✓ Evaluation complete."))
def parse_model_metadata(model_path: Path):
"""
Reverse-engineers metadata from a best_model folder name.
Folder names follow the convention:
{game}_{algo}_{persona}_{skill}_{arch}
e.g. "platformer_ppo_platformer_simple_novice_slim"
Returns a dict with keys: game, algo, persona, skill, arch.
Architecture tag is stripped from the end if it matches a known set.
"""
folder = model_path.parent.name
parts = folder.split("_")
_ARCH_TAGS = {
"lightmobile": "lightmobile",
"spatialattention": "spatialattention",
"channelattention": "channelattention",
"deepchannelattention": "deepchannelattention",
"mlp": "mlp",
}
arch = None
if len(parts) >= 2 and parts[-1].lower() in _ARCH_TAGS:
arch = _ARCH_TAGS[parts[-1].lower()]
parts = parts[:-1]