|
| 1 | +import argparse |
| 2 | +import subprocess |
| 3 | +import sys |
| 4 | +import numpy as np |
| 5 | +import json |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +# --- Configuration --- |
| 9 | +DEFAULT_SEEDS = 5 |
| 10 | +DEFAULT_CONTRACT = "experiment_contract_light.yaml" |
| 11 | + |
| 12 | +def run_single_seed(variant, env, seed, contract, device=None): |
| 13 | + """ |
| 14 | + Runs a single experiment seed using run_experiment.py via subprocess. |
| 15 | + Returns the result dictionary (or None if failed). |
| 16 | + """ |
| 17 | + cmd = [ |
| 18 | + sys.executable, |
| 19 | + "ablation_studies/run_experiment.py", |
| 20 | + "--variant", variant, |
| 21 | + "--env", env, |
| 22 | + "--seed", str(seed), |
| 23 | + "--contract", contract |
| 24 | + ] |
| 25 | + |
| 26 | + print(f" > Starting Seed {seed}...") |
| 27 | + try: |
| 28 | + # Run the command and capture output |
| 29 | + result = subprocess.run(cmd, capture_output=True, text=True, check=True) |
| 30 | + |
| 31 | + # Parse the output to find the final metrics (jsonl or stdout) |
| 32 | + # We assume run_experiment.py logs the final metrics in a way we can grab, |
| 33 | + # but since it saves to runs/.../metrics.jsonl, we can also read that file. |
| 34 | + |
| 35 | + return True |
| 36 | + |
| 37 | + except subprocess.CalledProcessError as e: |
| 38 | + print(f" !!! Error running seed {seed} !!!") |
| 39 | + print(e.stderr) |
| 40 | + return False |
| 41 | + |
| 42 | +def get_run_metrics(variant, env, seed): |
| 43 | + """ |
| 44 | + Reads the metrics.jsonl file for a specific run to get the final performance. |
| 45 | + """ |
| 46 | + # Structure: runs/{variant}/seed_{seed}/{env}/metrics.jsonl |
| 47 | + # Note: run_experiment.py logic for run_name: |
| 48 | + # run_name = cfg.model.name if cfg.model.name != 'ablation_dsformer' else args.variant |
| 49 | + # This might need some adjustment if the variant name != model name mapping is complex. |
| 50 | + # Based on run_experiment.py: |
| 51 | + # model_name = cfg.get('model', {}).get('name', args.variant if args.variant in ['dt', 'snn_dt', 'iql', 'cql'] else 'ablation_dsformer') |
| 52 | + # run_name = cfg.model.name if cfg.model.name != 'ablation_dsformer' else args.variant |
| 53 | + |
| 54 | + # We will try to reconstruct the path. |
| 55 | + project_root = Path(__file__).parent |
| 56 | + |
| 57 | + # Determine directory name based on variant logic from run_experiment.py |
| 58 | + # If variant is simple, dir is variant. If dsformer, it's the variant name. |
| 59 | + # To be safe, we check both possible paths. |
| 60 | + |
| 61 | + possible_run_names = [variant] |
| 62 | + # Add mapped names if necessary, but 'snn_dt', 'iql' etc map to themselves usually unless configured otherwise. |
| 63 | + |
| 64 | + metrics_file = None |
| 65 | + for r_name in possible_run_names: |
| 66 | + p = project_root / "runs" / r_name / f"seed_{seed}" / env / "metrics.jsonl" |
| 67 | + if p.exists(): |
| 68 | + metrics_file = p |
| 69 | + break |
| 70 | + |
| 71 | + if not metrics_file: |
| 72 | + # Fallback check for model-based names if variant was just a config name |
| 73 | + # E.g. variant 'no_plasticity' might map to model 'ablation_dsformer' -> run_name 'no_plasticity' |
| 74 | + # It seems consistent. |
| 75 | + print(f" [Warning] Could not find metrics file for {variant} seed {seed}") |
| 76 | + return None |
| 77 | + |
| 78 | + final_return = None |
| 79 | + try: |
| 80 | + with open(metrics_file, 'r') as f: |
| 81 | + for line in f: |
| 82 | + if not line.strip(): continue |
| 83 | + data = json.loads(line) |
| 84 | + if 'val/mean_return' in data: |
| 85 | + final_return = data['val/mean_return'] |
| 86 | + except Exception as e: |
| 87 | + print(f" [Error] Reading metrics file: {e}") |
| 88 | + |
| 89 | + return final_return |
| 90 | + |
| 91 | +def main(): |
| 92 | + parser = argparse.ArgumentParser(description="Run a group of ablation experiments (multiple seeds) and report Mean +/- Std.") |
| 93 | + parser.add_argument("--variant", required=True, help="Experiment variant (e.g., snn_dt, no_plasticity)") |
| 94 | + parser.add_argument("--env", required=True, help="Environment (e.g., CartPole-v1)") |
| 95 | + parser.add_argument("--num_seeds", type=int, default=DEFAULT_SEEDS, help="Number of seeds to run (0 to N-1)") |
| 96 | + parser.add_argument("--contract", default=DEFAULT_CONTRACT, help="Experiment contract YAML") |
| 97 | + |
| 98 | + args = parser.parse_args() |
| 99 | + |
| 100 | + print(f"\n=======================================================") |
| 101 | + print(f" Running Ablation Group: {args.variant} | {args.env}") |
| 102 | + print(f" Seeds: 0 to {args.num_seeds - 1}") |
| 103 | + print(f"=======================================================\n") |
| 104 | + |
| 105 | + returns = [] |
| 106 | + |
| 107 | + for seed in range(args.num_seeds): |
| 108 | + success = run_single_seed(args.variant, args.env, seed, args.contract) |
| 109 | + if success: |
| 110 | + val_return = get_run_metrics(args.variant, args.env, seed) |
| 111 | + if val_return is not None: |
| 112 | + returns.append(val_return) |
| 113 | + print(f" > Seed {seed} Finished. Return: {val_return:.2f}") |
| 114 | + else: |
| 115 | + print(f" > Seed {seed} Finished but no return found.") |
| 116 | + else: |
| 117 | + print(f" > Seed {seed} FAILED.") |
| 118 | + |
| 119 | + print(f"\n=======================================================") |
| 120 | + if returns: |
| 121 | + mean_ret = np.mean(returns) |
| 122 | + std_ret = np.std(returns) |
| 123 | + print(f" FINAL RESULT [{args.variant} / {args.env}]:") |
| 124 | + print(f" Mean Return: {mean_ret:.2f} ± {std_ret:.2f}") |
| 125 | + print(f" (Based on {len(returns)}/{args.num_seeds} successful runs)") |
| 126 | + else: |
| 127 | + print(f" NO SUCCESSFUL RUNS.") |
| 128 | + print(f"=======================================================\n") |
| 129 | + |
| 130 | +if __name__ == "__main__": |
| 131 | + main() |
0 commit comments