Docking_project / libs /adaptive /epsilon_regret.py
QPromaQ's picture
Upload folder using huggingface_hub
c289d87 verified
Raw
History Blame Contribute Delete
6.29 kB
from __future__ import annotations
from dataclasses import dataclass
from typing import Dict, Iterable, List, Sequence
import numpy as np
@dataclass
class EpsilonRegretConfig:
epsilon_quality: float = 0.10
acceptable_regret: float = 0.10
min_budget: int = 250
max_budget: int = 10000
min_model_weight: float = 0.25
patience_rounds: int = 6
min_improvement: float = 0.02
uncertainty_multiplier: float = 0.50
min_cluster_coverage: float = 0.20
min_hypercluster_coverage: float = 0.20
class EpsilonRegretController:
"""
Budget-aware stop controller with epsilon-regret semantics.
Online intent:
stop when estimated remaining gain is small relative to current best score,
after minimum exploration and coverage constraints are satisfied.
"""
def __init__(self, config: EpsilonRegretConfig | None = None) -> None:
self.config = config or EpsilonRegretConfig()
self.best_score = np.inf
self.stagnant_rounds = 0
self.history: List[Dict[str, float | int | bool | str]] = []
@staticmethod
def _mean_or_nan(values: Sequence[float]) -> float:
arr = np.asarray(values, dtype=float)
if arr.size == 0:
return float("nan")
return float(np.nanmean(arr))
@staticmethod
def _estimate_remaining_gain(
best_score: float,
expected_remaining_scores: Iterable[float],
uncertainty_scores: Iterable[float],
uncertainty_multiplier: float,
) -> float:
pred = np.asarray(list(expected_remaining_scores), dtype=float)
unc = np.asarray(list(uncertainty_scores), dtype=float)
if pred.size == 0:
return float("inf")
if unc.size != pred.size:
unc = np.full(pred.shape[0], np.nanmean(unc) if unc.size else 1.0, dtype=float)
optimistic = pred - float(max(0.0, uncertainty_multiplier)) * np.abs(unc)
optimistic_best = float(np.nanmin(optimistic)) if np.isfinite(optimistic).any() else float(np.nanmin(pred))
if not np.isfinite(optimistic_best) or not np.isfinite(best_score):
return float("inf")
# lower score is better
return float(max(0.0, best_score - optimistic_best))
def update(
self,
*,
round_idx: int,
n_evaluated: int,
best_score_now: float,
recent_scores: Sequence[float],
model_weight: float,
cluster_coverage: float,
hypercluster_coverage: float,
expected_remaining_scores: Iterable[float],
uncertainty_scores: Iterable[float],
time_importance: float,
budget_cap: int,
) -> Dict[str, float | int | bool | str]:
cfg = self.config
ti = float(max(0.0, min(1.0, float(time_importance))))
if np.isfinite(self.best_score):
improvement = float(self.best_score - best_score_now)
else:
improvement = float("inf")
if improvement > float(cfg.min_improvement):
self.stagnant_rounds = 0
else:
self.stagnant_rounds += 1
self.best_score = min(float(self.best_score), float(best_score_now))
epsilon_rel = float(max(cfg.epsilon_quality, cfg.acceptable_regret))
# Higher time importance permits slightly larger acceptable residual gain.
epsilon_rel *= float(1.0 + 0.5 * ti)
epsilon_abs = float(epsilon_rel * max(1.0, abs(float(self.best_score))))
remaining_gain = self._estimate_remaining_gain(
best_score=float(self.best_score),
expected_remaining_scores=expected_remaining_scores,
uncertainty_scores=uncertainty_scores,
uncertainty_multiplier=float(cfg.uncertainty_multiplier),
)
regret_ratio_proxy = float(remaining_gain / max(1.0, abs(float(self.best_score))))
budget_floor = int(max(1, cfg.min_budget))
budget_ceiling = int(min(cfg.max_budget, budget_cap))
budget_ready = int(n_evaluated) >= budget_floor
model_ready = float(model_weight) >= float(cfg.min_model_weight)
coverage_ready = bool(
float(cluster_coverage) >= float(cfg.min_cluster_coverage)
and float(hypercluster_coverage) >= float(cfg.min_hypercluster_coverage)
)
stagnation_ready = int(self.stagnant_rounds) >= int(cfg.patience_rounds)
hit_budget_ceiling = int(n_evaluated) >= int(budget_ceiling)
epsilon_ready = bool(np.isfinite(remaining_gain) and remaining_gain <= epsilon_abs)
stop = bool(hit_budget_ceiling or (budget_ready and model_ready and coverage_ready and stagnation_ready and epsilon_ready))
if hit_budget_ceiling:
reason = "max_budget_reached"
elif not budget_ready:
reason = "below_min_budget"
elif not model_ready:
reason = "model_not_ready"
elif not coverage_ready:
reason = "coverage_not_ready"
elif not stagnation_ready:
reason = "insufficient_stagnation_evidence"
elif not epsilon_ready:
reason = "remaining_gain_above_epsilon"
else:
reason = "epsilon_regret_stop"
rec = {
"round_idx": int(round_idx),
"n_evaluated": int(n_evaluated),
"best_score": float(self.best_score),
"recent_mean_score": self._mean_or_nan(recent_scores),
"model_weight": float(model_weight),
"cluster_coverage": float(cluster_coverage),
"hypercluster_coverage": float(hypercluster_coverage),
"stagnant_rounds": int(self.stagnant_rounds),
"epsilon_abs": float(epsilon_abs),
"estimated_remaining_gain": float(remaining_gain),
"regret_ratio_proxy": float(regret_ratio_proxy),
"budget_floor": int(budget_floor),
"budget_ceiling": int(budget_ceiling),
"budget_ready": bool(budget_ready),
"model_ready": bool(model_ready),
"coverage_ready": bool(coverage_ready),
"stagnation_ready": bool(stagnation_ready),
"epsilon_ready": bool(epsilon_ready),
"stop": bool(stop),
"reason": reason,
}
self.history.append(rec)
return rec