from __future__ import annotations from dataclasses import dataclass from typing import Sequence @dataclass class WeightScheduleConfig: sample_knots: tuple[int, int, int, int] = (20, 50, 100, 200) weight_knots: tuple[float, float, float, float] = (0.1, 0.3, 0.5, 0.8) max_weight: float = 0.9 min_weight: float = 0.05 instability_threshold: float = 2.0 instability_decay: float = 0.25 def _interp(x: float, xs: Sequence[float], ys: Sequence[float]) -> float: if x <= xs[0]: return float(ys[0]) if x >= xs[-1]: return float(ys[-1]) for i in range(1, len(xs)): if x <= xs[i]: x0, x1 = xs[i - 1], xs[i] y0, y1 = ys[i - 1], ys[i] t = (x - x0) / max(1e-9, (x1 - x0)) return float(y0 + t * (y1 - y0)) return float(ys[-1]) def compute_model_weight( n_samples: int, instability_ratio: float = 1.0, config: WeightScheduleConfig | None = None, ) -> float: cfg = config or WeightScheduleConfig() base = _interp(float(n_samples), cfg.sample_knots, cfg.weight_knots) if n_samples > cfg.sample_knots[-1]: extra = min(cfg.max_weight - base, 0.05 * (n_samples - cfg.sample_knots[-1]) / 100.0) base += max(0.0, extra) if instability_ratio > cfg.instability_threshold: base *= max(0.1, 1.0 - cfg.instability_decay) base = max(cfg.min_weight, min(cfg.max_weight, base)) return float(base)