| |
| """MLP surrogate Optimizer Agent for GPUDrive long-tail search. |
| |
| The optimizer consumes Evaluator Agent `optimizer_metrics.json` files, learns a |
| small surrogate model from search parameters to quality metrics, scores a |
| discrete candidate grid, and writes next-round search recommendations. |
| |
| When history is still too small for a meaningful MLP, the script falls back to a |
| deterministic exploration plan while still recording the MLP-ready dataset. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import glob |
| import itertools |
| import json |
| import math |
| import random |
| from collections import defaultdict |
| from pathlib import Path |
| from typing import Any |
|
|
| import torch |
| from torch import nn |
|
|
|
|
| DEFAULT_GRID = { |
| "risk_collision_weight": [-0.2, -0.1, 0.0], |
| "risk_goal_weight": [1.6, 1.8, 2.0], |
| "risk_offroad_weight": [-0.8, -0.6, -0.4], |
| "risk_agents_per_world": [1, 2, 3, 4], |
| "normal_mode": ["policy", "expert"], |
| "deterministic": [0], |
| } |
|
|
| TARGET_KEYS = [ |
| "composite_objective", |
| "accepted_rate", |
| "high_value_rate", |
| "natural_critical_rate", |
| "risk_direct_accept_rate", |
| "semantic_diversity_entropy", |
| "hard_artifact_record_rate", |
| ] |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--metrics-glob", action="append", default=[]) |
| parser.add_argument("--metrics-file", action="append", default=[]) |
| parser.add_argument("--output-dir", default="search_outputs/optimizer_agent/mlp_next") |
| parser.add_argument("--candidate-grid-json", default="") |
| parser.add_argument("--top-k", type=int, default=8) |
| parser.add_argument("--explore-k", type=int, default=4) |
| parser.add_argument("--allow-repeat", type=int, default=0) |
| parser.add_argument("--seed", type=int, default=42) |
| parser.add_argument("--hidden-dim", type=int, default=64) |
| parser.add_argument("--epochs", type=int, default=1200) |
| parser.add_argument("--lr", type=float, default=1e-3) |
| parser.add_argument("--weight-decay", type=float, default=1e-4) |
| parser.add_argument("--min-train-samples", type=int, default=6) |
| parser.add_argument("--exploration-weight", type=float, default=0.12) |
| parser.add_argument("--default-normal-mode", default="policy") |
| parser.add_argument("--default-deterministic", type=int, default=0) |
| parser.add_argument("--default-normal-style", default="balanced") |
| parser.add_argument("--default-risk-style", default="risk_taker") |
| return parser.parse_args() |
|
|
|
|
| def read_json(path: str | Path) -> dict[str, Any]: |
| with open(path, "r", encoding="utf-8") as f: |
| return json.load(f) |
|
|
|
|
| def write_json(path: str | Path, data: Any) -> None: |
| with open(path, "w", encoding="utf-8") as f: |
| json.dump(data, f, ensure_ascii=False, indent=2) |
|
|
|
|
| def append_jsonl(path: str | Path, record: dict[str, Any]) -> None: |
| with open(path, "a", encoding="utf-8") as f: |
| f.write(json.dumps(record, ensure_ascii=False) + "\n") |
|
|
|
|
| def as_float(value: Any, default: float = 0.0) -> float: |
| try: |
| out = float(value) |
| except (TypeError, ValueError): |
| return default |
| return out if math.isfinite(out) else default |
|
|
|
|
| def as_int(value: Any, default: int = 0) -> int: |
| try: |
| return int(value) |
| except (TypeError, ValueError): |
| return default |
|
|
|
|
| def clamp(value: float, lower: float, upper: float) -> float: |
| return min(max(value, lower), upper) |
|
|
|
|
| def discover_metrics(args: argparse.Namespace) -> list[Path]: |
| paths: list[Path] = [] |
| for pattern in args.metrics_glob: |
| paths.extend(Path(p) for p in glob.glob(pattern, recursive=True)) |
| paths.extend(Path(p) for p in args.metrics_file) |
| if not paths: |
| paths.extend(Path(p) for p in glob.glob("search_outputs/evaluator_agent/**/optimizer_metrics.json", recursive=True)) |
| unique = [] |
| seen = set() |
| for path in paths: |
| path = path.resolve() |
| if path.exists() and path not in seen: |
| seen.add(path) |
| unique.append(path) |
| return sorted(unique) |
|
|
|
|
| def load_candidate_grid(raw: str) -> dict[str, list[Any]]: |
| if not raw: |
| return dict(DEFAULT_GRID) |
| loaded = json.loads(raw) |
| grid = dict(DEFAULT_GRID) |
| grid.update(loaded) |
| return grid |
|
|
|
|
| def params_from_metrics(metrics: dict[str, Any], args: argparse.Namespace) -> dict[str, Any]: |
| params = metrics.get("current_search_parameters", {}) or {} |
| return { |
| "risk_collision_weight": as_float(params.get("risk_collision_weight"), 0.0), |
| "risk_goal_weight": as_float(params.get("risk_goal_weight"), 2.0), |
| "risk_offroad_weight": as_float(params.get("risk_offroad_weight"), -0.4), |
| "risk_agents_per_world": as_int(params.get("risk_agents_per_world"), 3), |
| "normal_mode": str(params.get("normal_mode", args.default_normal_mode)), |
| "deterministic": as_int(params.get("deterministic"), args.default_deterministic), |
| "normal_style": str(params.get("normal_style", args.default_normal_style)), |
| "risk_style": str(params.get("risk_style", args.default_risk_style)), |
| } |
|
|
|
|
| def param_key(params: dict[str, Any]) -> tuple[Any, ...]: |
| return ( |
| round(as_float(params["risk_collision_weight"]), 5), |
| round(as_float(params["risk_goal_weight"]), 5), |
| round(as_float(params["risk_offroad_weight"]), 5), |
| as_int(params["risk_agents_per_world"]), |
| str(params["normal_mode"]), |
| as_int(params["deterministic"]), |
| ) |
|
|
|
|
| def targets_from_metrics(metrics: dict[str, Any]) -> dict[str, float]: |
| obj = metrics.get("objective_metrics", {}) or {} |
| return {key: as_float(obj.get(key), 0.0) for key in TARGET_KEYS} |
|
|
|
|
| def aggregate_history(paths: list[Path], args: argparse.Namespace) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: |
| raw_samples = [] |
| grouped: dict[tuple[Any, ...], list[dict[str, Any]]] = defaultdict(list) |
| for path in paths: |
| metrics = read_json(path) |
| params = params_from_metrics(metrics, args) |
| targets = targets_from_metrics(metrics) |
| sample = { |
| "metrics_path": str(path), |
| "params": params, |
| "targets": targets, |
| "objective_metrics": metrics.get("objective_metrics", {}), |
| "counts": metrics.get("counts", {}), |
| "suggested_next_search_parameters": metrics.get("suggested_next_search_parameters", []), |
| } |
| raw_samples.append(sample) |
| grouped[param_key(params)].append(sample) |
|
|
| aggregated = [] |
| for key, samples in grouped.items(): |
| params = dict(samples[0]["params"]) |
| target_mean = {} |
| target_std = {} |
| for target_key in TARGET_KEYS: |
| values = [sample["targets"][target_key] for sample in samples] |
| target_mean[target_key] = sum(values) / len(values) |
| target_std[target_key] = std(values) |
| aggregated.append( |
| { |
| "params": params, |
| "targets": target_mean, |
| "target_std": target_std, |
| "replicates": len(samples), |
| "metrics_paths": [sample["metrics_path"] for sample in samples], |
| } |
| ) |
| return raw_samples, aggregated |
|
|
|
|
| def std(values: list[float]) -> float: |
| if len(values) <= 1: |
| return 0.0 |
| mu = sum(values) / len(values) |
| return math.sqrt(sum((value - mu) ** 2 for value in values) / (len(values) - 1)) |
|
|
|
|
| def generate_candidates(grid: dict[str, list[Any]], args: argparse.Namespace) -> list[dict[str, Any]]: |
| keys = [ |
| "risk_collision_weight", |
| "risk_goal_weight", |
| "risk_offroad_weight", |
| "risk_agents_per_world", |
| "normal_mode", |
| "deterministic", |
| ] |
| candidates = [] |
| for values in itertools.product(*(grid[key] for key in keys)): |
| params = dict(zip(keys, values)) |
| params["normal_style"] = args.default_normal_style |
| params["risk_style"] = args.default_risk_style |
| candidates.append(params) |
| return candidates |
|
|
|
|
| def feature_vector(params: dict[str, Any]) -> list[float]: |
| normal_mode = str(params.get("normal_mode", "policy")) |
| return [ |
| as_float(params.get("risk_collision_weight"), 0.0), |
| as_float(params.get("risk_goal_weight"), 2.0), |
| as_float(params.get("risk_offroad_weight"), -0.4), |
| as_float(params.get("risk_agents_per_world"), 3), |
| 1.0 if normal_mode == "policy" else 0.0, |
| 1.0 if normal_mode == "expert" else 0.0, |
| as_float(params.get("deterministic"), 0.0), |
| ] |
|
|
|
|
| def target_vector(targets: dict[str, float]) -> list[float]: |
| return [as_float(targets.get(key), 0.0) for key in TARGET_KEYS] |
|
|
|
|
| class SurrogateMLP(nn.Module): |
| def __init__(self, input_dim: int, output_dim: int, hidden_dim: int) -> None: |
| super().__init__() |
| self.net = nn.Sequential( |
| nn.Linear(input_dim, hidden_dim), |
| nn.ReLU(), |
| nn.Linear(hidden_dim, hidden_dim), |
| nn.ReLU(), |
| nn.Linear(hidden_dim, output_dim), |
| ) |
|
|
| def forward(self, x: torch.Tensor) -> torch.Tensor: |
| return self.net(x) |
|
|
|
|
| def normalize_matrix(values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: |
| mean = values.mean(dim=0, keepdim=True) |
| std_value = values.std(dim=0, keepdim=True) |
| std_value = torch.where(std_value < 1e-6, torch.ones_like(std_value), std_value) |
| return (values - mean) / std_value, mean, std_value |
|
|
|
|
| def train_surrogate(samples: list[dict[str, Any]], args: argparse.Namespace) -> dict[str, Any]: |
| x = torch.tensor([feature_vector(sample["params"]) for sample in samples], dtype=torch.float32) |
| y = torch.tensor([target_vector(sample["targets"]) for sample in samples], dtype=torch.float32) |
| x_norm, x_mean, x_std = normalize_matrix(x) |
| y_norm, y_mean, y_std = normalize_matrix(y) |
|
|
| torch.manual_seed(args.seed) |
| model = SurrogateMLP(x.shape[1], y.shape[1], args.hidden_dim) |
| optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay) |
| loss_fn = nn.MSELoss() |
| losses = [] |
| for _ in range(args.epochs): |
| pred = model(x_norm) |
| loss = loss_fn(pred, y_norm) |
| optimizer.zero_grad() |
| loss.backward() |
| optimizer.step() |
| losses.append(float(loss.item())) |
|
|
| with torch.no_grad(): |
| train_pred = model(x_norm) * y_std + y_mean |
| mae = (train_pred - y).abs().mean(dim=0) |
|
|
| return { |
| "trained": True, |
| "model": model, |
| "x_mean": x_mean, |
| "x_std": x_std, |
| "y_mean": y_mean, |
| "y_std": y_std, |
| "train_loss_final": losses[-1] if losses else None, |
| "train_loss_initial": losses[0] if losses else None, |
| "train_mae": {key: round(float(value), 5) for key, value in zip(TARGET_KEYS, mae.tolist())}, |
| } |
|
|
|
|
| def predict(surrogate: dict[str, Any], params: dict[str, Any]) -> dict[str, float]: |
| x = torch.tensor([feature_vector(params)], dtype=torch.float32) |
| x_norm = (x - surrogate["x_mean"]) / surrogate["x_std"] |
| with torch.no_grad(): |
| y = surrogate["model"](x_norm) * surrogate["y_std"] + surrogate["y_mean"] |
| return { |
| key: round(float(value), 5) |
| for key, value in zip(TARGET_KEYS, y.squeeze(0).tolist()) |
| } |
|
|
|
|
| def heuristic_prediction(params: dict[str, Any], samples: list[dict[str, Any]]) -> dict[str, float]: |
| if not samples: |
| return {key: 0.0 for key in TARGET_KEYS} |
| |
| |
| weights = [] |
| for sample in samples: |
| dist = param_distance(params, sample["params"]) |
| weights.append(1.0 / (0.05 + dist)) |
| total = sum(weights) |
| pred = {} |
| for key in TARGET_KEYS: |
| pred[key] = sum(weight * sample["targets"][key] for weight, sample in zip(weights, samples)) / total |
| return {key: round(value, 5) for key, value in pred.items()} |
|
|
|
|
| def param_distance(a: dict[str, Any], b: dict[str, Any]) -> float: |
| fa = feature_vector(a) |
| fb = feature_vector(b) |
| scales = [0.2, 0.4, 0.4, 3.0, 1.0, 1.0, 1.0] |
| sq = 0.0 |
| for va, vb, scale in zip(fa, fb, scales): |
| sq += ((va - vb) / max(scale, 1e-6)) ** 2 |
| return math.sqrt(sq / len(fa)) |
|
|
|
|
| def nearest_history_distance(params: dict[str, Any], samples: list[dict[str, Any]]) -> float: |
| if not samples: |
| return 1.0 |
| return min(param_distance(params, sample["params"]) for sample in samples) |
|
|
|
|
| def utility(pred: dict[str, float]) -> float: |
| return ( |
| 0.45 * pred["composite_objective"] |
| + 0.16 * pred["accepted_rate"] |
| + 0.16 * pred["high_value_rate"] |
| + 0.12 * pred["risk_direct_accept_rate"] |
| + 0.11 * pred["semantic_diversity_entropy"] |
| - 0.18 * pred["hard_artifact_record_rate"] |
| ) |
|
|
|
|
| def score_candidates( |
| candidates: list[dict[str, Any]], |
| samples: list[dict[str, Any]], |
| surrogate: dict[str, Any] | None, |
| args: argparse.Namespace, |
| ) -> list[dict[str, Any]]: |
| evaluated = {param_key(sample["params"]) for sample in samples} |
| scored = [] |
| for params in candidates: |
| already = param_key(params) in evaluated |
| if already and not args.allow_repeat: |
| continue |
| pred = predict(surrogate, params) if surrogate else heuristic_prediction(params, samples) |
| base_utility = utility(pred) |
| distance = nearest_history_distance(params, samples) |
| exploration_bonus = args.exploration_weight * clamp(distance, 0.0, 2.0) |
| acquisition = base_utility + exploration_bonus |
| scored.append( |
| { |
| "params": params, |
| "predicted_metrics": pred, |
| "utility": round(base_utility, 5), |
| "exploration_score": round(distance, 5), |
| "acquisition": round(acquisition, 5), |
| "already_evaluated": already, |
| } |
| ) |
| return sorted(scored, key=lambda item: item["acquisition"], reverse=True) |
|
|
|
|
| def choose_recommendations(scored: list[dict[str, Any]], args: argparse.Namespace) -> list[dict[str, Any]]: |
| exploit = scored[: max(args.top_k, 0)] |
| remaining = scored[max(args.top_k, 0) :] |
| explore = sorted(remaining, key=lambda item: item["exploration_score"], reverse=True)[: max(args.explore_k, 0)] |
| combined = [] |
| seen = set() |
| for source, items in (("mlp_top", exploit), ("exploration", explore)): |
| for item in items: |
| key = param_key(item["params"]) |
| if key in seen: |
| continue |
| seen.add(key) |
| out = dict(item) |
| out["source"] = source |
| out["rank"] = len(combined) + 1 |
| combined.append(out) |
| return combined |
|
|
|
|
| def env_block(params: dict[str, Any]) -> str: |
| return "\n".join( |
| [ |
| f"RISK_COLLISION_WEIGHT={params['risk_collision_weight']}", |
| f"RISK_GOAL_WEIGHT={params['risk_goal_weight']}", |
| f"RISK_OFFROAD_WEIGHT={params['risk_offroad_weight']}", |
| f"RISK_AGENTS_PER_WORLD={params['risk_agents_per_world']}", |
| f"NORMAL_MODE={params['normal_mode']}", |
| f"DETERMINISTIC={params['deterministic']}", |
| ] |
| ) |
|
|
|
|
| def command_line(params: dict[str, Any]) -> str: |
| prefix = " ".join( |
| [ |
| f"RISK_COLLISION_WEIGHT={params['risk_collision_weight']}", |
| f"RISK_GOAL_WEIGHT={params['risk_goal_weight']}", |
| f"RISK_OFFROAD_WEIGHT={params['risk_offroad_weight']}", |
| f"RISK_AGENTS_PER_WORLD={params['risk_agents_per_world']}", |
| f"NORMAL_MODE={params['normal_mode']}", |
| f"DETERMINISTIC={params['deterministic']}", |
| ] |
| ) |
| return f"{prefix} sbatch scripts/search_longtail_reward_conditioned.sbatch" |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| random.seed(args.seed) |
| torch.manual_seed(args.seed) |
| output_dir = Path(args.output_dir) |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| metric_paths = discover_metrics(args) |
| raw_samples, samples = aggregate_history(metric_paths, args) |
| grid = load_candidate_grid(args.candidate_grid_json) |
| candidates = generate_candidates(grid, args) |
|
|
| surrogate = None |
| train_report: dict[str, Any] = { |
| "trained": False, |
| "reason": f"Need at least {args.min_train_samples} aggregated samples.", |
| } |
| if len(samples) >= args.min_train_samples: |
| surrogate = train_surrogate(samples, args) |
| train_report = { |
| "trained": True, |
| "num_samples": len(samples), |
| "train_loss_initial": surrogate["train_loss_initial"], |
| "train_loss_final": surrogate["train_loss_final"], |
| "train_mae": surrogate["train_mae"], |
| } |
|
|
| scored = score_candidates(candidates, samples, surrogate, args) |
| recommendations = choose_recommendations(scored, args) |
|
|
| candidate_path = output_dir / "candidate_predictions.jsonl" |
| if candidate_path.exists(): |
| candidate_path.unlink() |
| for item in scored: |
| append_jsonl(candidate_path, item) |
|
|
| for item in recommendations: |
| item["env_block"] = env_block(item["params"]) |
| item["search_command"] = command_line(item["params"]) |
|
|
| plan = { |
| "schema_version": "mlp_optimizer_plan_v1", |
| "metrics_paths": [str(path) for path in metric_paths], |
| "num_raw_metric_files": len(raw_samples), |
| "num_aggregated_parameter_samples": len(samples), |
| "candidate_grid": grid, |
| "num_candidates": len(candidates), |
| "num_scored_candidates": len(scored), |
| "feature_schema": [ |
| "risk_collision_weight", |
| "risk_goal_weight", |
| "risk_offroad_weight", |
| "risk_agents_per_world", |
| "normal_mode_is_policy", |
| "normal_mode_is_expert", |
| "deterministic", |
| ], |
| "target_schema": TARGET_KEYS, |
| "training": train_report, |
| "history_samples": samples, |
| "recommendations": recommendations, |
| } |
| write_json(output_dir / "optimizer_plan.json", plan) |
|
|
| if recommendations: |
| (output_dir / "best_recommendation.env").write_text( |
| recommendations[0]["env_block"] + "\n", |
| encoding="utf-8", |
| ) |
| (output_dir / "recommended_search_commands.sh").write_text( |
| "\n".join(item["search_command"] for item in recommendations) + "\n", |
| encoding="utf-8", |
| ) |
|
|
| print( |
| "[optimizer] done:", |
| json.dumps( |
| { |
| "metrics": len(raw_samples), |
| "aggregated_samples": len(samples), |
| "trained": train_report["trained"], |
| "recommendations": len(recommendations), |
| "output_dir": str(output_dir), |
| }, |
| ensure_ascii=False, |
| ), |
| flush=True, |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|