File size: 4,147 Bytes
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from dataclasses import dataclass
from typing import Dict, List, Sequence

import numpy as np


@dataclass
class DynamicThresholdConfig:
    min_evaluated: int = 500
    patience_rounds: int = 8
    min_model_weight: float = 0.35
    quantile: float = 0.15
    uncertainty_weight: float = 0.20
    min_improvement: float = 0.02
    exploration_margin: float = 0.45
    exploitation_margin: float = 0.10
    reference_evaluations: int = 5000


class DynamicEarlyStopController:
    """
    Conservative early-stop controller for adaptive replay.

    Lower scores are considered better.
    """

    def __init__(self, config: DynamicThresholdConfig | None = None) -> None:
        self.config = config or DynamicThresholdConfig()
        self.best_score = np.inf
        self.stagnant_rounds = 0
        self.history: List[Dict[str, float | int | bool | str]] = []

    def update(
        self,
        *,
        round_idx: int,
        n_evaluated: int,
        all_scores: Sequence[float],
        recent_scores: Sequence[float],
        model_weight: float,
        mean_uncertainty: float,
    ) -> Dict[str, float | int | bool | str]:
        cfg = self.config
        scores = np.asarray(all_scores, dtype=float)
        recent = np.asarray(recent_scores, dtype=float)

        if scores.size == 0:
            rec = {
                "round_idx": int(round_idx),
                "n_evaluated": int(n_evaluated),
                "dynamic_threshold": np.nan,
                "score_quantile": np.nan,
                "best_score": np.nan,
                "recent_mean_score": np.nan,
                "mean_uncertainty": float(mean_uncertainty),
                "model_weight": float(model_weight),
                "stagnant_rounds": int(self.stagnant_rounds),
                "eligible_for_stop": False,
                "stop": False,
                "reason": "no_scores",
            }
            self.history.append(rec)
            return rec

        score_quantile = float(np.nanquantile(scores, cfg.quantile))
        best = float(np.nanmin(scores))
        recent_mean = float(np.nanmean(recent)) if recent.size else float(np.nan)
        uncertainty = float(max(0.0, mean_uncertainty))

        if np.isfinite(self.best_score):
            improvement = float(self.best_score - best)
        else:
            improvement = np.inf

        if improvement > cfg.min_improvement:
            self.stagnant_rounds = 0
        else:
            self.stagnant_rounds += 1
        self.best_score = min(self.best_score, best)

        coverage = float(min(1.0, n_evaluated / max(1.0, float(cfg.reference_evaluations))))
        margin = (1.0 - coverage) * cfg.exploration_margin + coverage * cfg.exploitation_margin
        dynamic_threshold = float(score_quantile + margin + cfg.uncertainty_weight * uncertainty)

        eligible = (
            int(n_evaluated) >= int(cfg.min_evaluated)
            and float(model_weight) >= float(cfg.min_model_weight)
        )
        plateau = self.stagnant_rounds >= int(cfg.patience_rounds)
        poor_recent = bool(np.isfinite(recent_mean) and recent_mean >= dynamic_threshold)
        should_stop = bool(eligible and plateau and poor_recent)

        if not eligible:
            reason = "not_eligible"
        elif not plateau:
            reason = "improving_or_not_stagnant"
        elif not poor_recent:
            reason = "recent_batch_still_competitive"
        else:
            reason = "stagnation_above_dynamic_threshold"

        rec = {
            "round_idx": int(round_idx),
            "n_evaluated": int(n_evaluated),
            "dynamic_threshold": dynamic_threshold,
            "score_quantile": score_quantile,
            "best_score": self.best_score,
            "recent_mean_score": recent_mean,
            "mean_uncertainty": uncertainty,
            "model_weight": float(model_weight),
            "stagnant_rounds": int(self.stagnant_rounds),
            "eligible_for_stop": bool(eligible),
            "stop": should_stop,
            "reason": reason,
        }
        self.history.append(rec)
        return rec