File size: 1,452 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
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)