Skip to content

Learning-rate search

See the guide.

LRSearchConfig dataclass

LRSearchConfig(probe_steps=150, probe_eval_steps=None, confirm=True, early_stop=True, max_probes=12, resolution='coarse', factor=10.0, min_ratio=None, lr_bounds=(1e-12, 10.0), center_window=True, max_window_probes=4, probe_seeds=1, keep_probe_artifacts=False, verbose=False)

Options of the learning-rate search.

Set it as TrainingArguments(learning_rate="tune", lr_search_config=LRSearchConfig(...)) or pass single fields to trainer.tune_learning_rate(...). factor, min_ratio, max_probes, resolution, lr_bounds, center_window and max_window_probes are those of :class:LRSearch.

center_window class-attribute instance-attribute

center_window = True

confirm class-attribute instance-attribute

confirm = True

Re-run a converged probe at the full max_steps before accepting it (one extra full run).

early_stop class-attribute instance-attribute

early_stop = True

End a probe as soon as it is decisively collapsed or diverged.

factor class-attribute instance-attribute

factor = 10.0

keep_probe_artifacts class-attribute instance-attribute

keep_probe_artifacts = False

Keep the probe checkpoints (default: only each probe's training.json).

lr_bounds class-attribute instance-attribute

lr_bounds = (1e-12, 10.0)

max_probes class-attribute instance-attribute

max_probes = 12

max_window_probes class-attribute instance-attribute

max_window_probes = 4

min_ratio class-attribute instance-attribute

min_ratio = None

probe_eval_steps class-attribute instance-attribute

probe_eval_steps = None

Evaluation interval inside a probe (default: probe_steps // 6).

probe_seeds class-attribute instance-attribute

probe_seeds = 1

Seeds a probe may try. Some regimes (the GRADIEND pair) drift to a common pole for one seed and converge for another, so a single-seed probe can report collapsed or degrading at a learning rate that multi-seed training (max_seeds > 1) converges at. With probe_seeds > 1 a probe that ends collapsed or degrading is repeated with the next seeds (seed + 1, ...) and the best run is kept (converged first, then the highest score). frozen, slow and diverged probes are not repeated: another seed does not change their verdict.

probe_steps class-attribute instance-attribute

probe_steps = 150

Steps of each short probe run. None trains every probe for the full max_steps.

resolution class-attribute instance-attribute

resolution = 'coarse'

verbose class-attribute instance-attribute

verbose = False

Show the full training log of every probe. By default the search logs one line per probe.

__post_init__

__post_init__()
Source code in gradiend/trainer/core/lr_search.py
def __post_init__(self) -> None:
    self.lr_bounds = (float(self.lr_bounds[0]), float(self.lr_bounds[1]))
    if self.resolution not in ("coarse", "fine"):
        raise ValueError(f"resolution must be 'coarse' or 'fine', got {self.resolution!r}")
    if self.probe_steps is not None and self.probe_steps < 1:
        raise ValueError(f"probe_steps must be >= 1 or None, got {self.probe_steps}")
    if self.probe_seeds < 1:
        raise ValueError(f"probe_seeds must be >= 1, got {self.probe_seeds}")

tune_learning_rate

tune_learning_rate(trainer, initial_lr, *, experiment_dir, config=None, precheck=None, metadata=None, **train_overrides)

Search the learning rate of trainer and write lr_search.json into experiment_dir.

Most users call :meth:Trainer.tune_learning_rate() <gradiend.trainer.trainer.Trainer.tune_learning_rate> or set TrainingArguments(learning_rate="tune") instead; this is the function behind both.

Each probe trains one seed into <experiment_dir>/lr_search/<probe|confirm>_<lr> (no cache reuse), always from the trainer's original base model, with max_steps=config.probe_steps. With config.confirm a converged probe is re-run at the trainer's configured max_steps before it is accepted. With config.early_stop a probe ends as soon as it is decisively collapsed or diverged (:class:ProbeStopCallback). precheck runs once before the first probe (use :func:~gradiend.trainer.core.signal_checks.assert_signal_diverse on stacked inputs) for extra checks. Probe checkpoints are deleted after each probe (only training.json is kept) unless config.keep_probe_artifacts. metadata (e.g. the first guess and probe length) is stored next to the result in lr_search.json so a later run can tell whether a finished search still applies. The search options are those of :class:LRSearchConfig (probe_seeds > 1 repeats a collapsed or degrading probe with the next seeds); train_overrides are passed to every probe's trainer.train.

Source code in gradiend/trainer/core/lr_search.py
def tune_learning_rate(
    trainer: Any,
    initial_lr: float,
    *,
    experiment_dir: str,
    config: Optional[LRSearchConfig] = None,
    precheck: Optional[Callable[[], None]] = None,
    metadata: Optional[Mapping[str, Any]] = None,
    **train_overrides: Any,
) -> LRSearchResult:
    """Search the learning rate of ``trainer`` and write ``lr_search.json`` into ``experiment_dir``.

    Most users call :meth:`Trainer.tune_learning_rate() <gradiend.trainer.trainer.Trainer.tune_learning_rate>` or set
    ``TrainingArguments(learning_rate="tune")`` instead; this is the function behind both.

    Each probe trains one seed into ``<experiment_dir>/lr_search/<probe|confirm>_<lr>`` (no cache
    reuse), always from the trainer's original base model, with ``max_steps=config.probe_steps``. With
    ``config.confirm`` a converged probe is re-run at the trainer's configured ``max_steps`` before it
    is accepted. With ``config.early_stop`` a probe ends as soon as it is decisively collapsed or
    diverged (:class:`ProbeStopCallback`). ``precheck`` runs once before the first probe (use
    :func:`~gradiend.trainer.core.signal_checks.assert_signal_diverse` on stacked inputs) for extra checks.
    Probe checkpoints are deleted after each probe (only ``training.json`` is kept) unless
    ``config.keep_probe_artifacts``. ``metadata`` (e.g. the first guess and probe length) is stored next to the
    result in ``lr_search.json`` so a later run can tell whether a finished search still applies. The search options
    are those of :class:`LRSearchConfig` (``probe_seeds`` > 1 repeats a ``collapsed`` or ``degrading`` probe with
    the next seeds); ``train_overrides`` are passed to every probe's ``trainer.train``.
    """
    cfg = config or LRSearchConfig()
    misplaced = sorted(set(train_overrides) & {f.name for f in fields(LRSearchConfig)})
    if misplaced:
        raise TypeError(f"tune_learning_rate got search option(s) {misplaced}: pass them as config=LRSearchConfig(...)")
    os.makedirs(experiment_dir, exist_ok=True)
    if precheck is not None:
        precheck()

    base_args = getattr(trainer, "training_args", None) or getattr(trainer, "_training_args", None)
    full_steps = getattr(base_args, "max_steps", None)
    full_eval = getattr(base_args, "eval_steps", None)

    base_seed = int(getattr(base_args, "seed", 0) or 0)
    seed_dependent = (RunState.COLLAPSED, RunState.DEGRADING)

    def _one_seed(lr: float, steps: Optional[int], eval_steps: Optional[int], tag: str, k: int) -> ProbeResult:
        probe_dir = os.path.join(experiment_dir, "lr_search", f"{tag}_{lr:.3g}" + (f"_seed{k}" if k else ""))
        overrides: Dict[str, Any] = dict(train_overrides)
        overrides.update(
            learning_rate=lr, experiment_dir=probe_dir, max_seeds=1, use_cache=False,
        )
        if k:
            overrides["seed"] = base_seed + k
        if steps is not None:
            overrides["max_steps"] = int(steps)
        if eval_steps is not None:
            overrides["eval_steps"] = int(eval_steps)
        # the diversity guard is free (it reads statistics every evaluation computes) and stays on
        overrides["callbacks"] = [SignalDiversityCallback()] + ([ProbeStopCallback()] if cfg.early_stop else [])
        with _isolated_probe(trainer), _quiet_logs(not cfg.verbose):
            trainer.train(**overrides)
            result = _read_probe(probe_dir)
        if not cfg.keep_probe_artifacts:
            _prune_probe_dir(probe_dir)
        return result

    def _train_and_read(lr: float, steps: Optional[int], eval_steps: Optional[int], tag: str) -> ProbeResult:
        best: Optional[ProbeResult] = None
        for k in range(cfg.probe_seeds):
            result = _one_seed(lr, steps, eval_steps, tag, k)
            if best is None or _better_probe(result, best):
                best = result
            if classify_probe(best) not in seed_dependent:
                break  # converged, frozen, slow or diverged: another seed cannot change that verdict
            if k + 1 < cfg.probe_seeds:
                logger.info("lr_search: lr=%g seed %d ended %s; trying the next seed", lr, k,
                            classify_probe(result).value)
        assert best is not None
        return best

    eval_steps = cfg.probe_eval_steps
    if eval_steps is None and cfg.probe_steps is not None:
        eval_steps = max(1, int(cfg.probe_steps) // 6)

    def run(lr: float) -> ProbeResult:
        return _train_and_read(lr, cfg.probe_steps, eval_steps, "probe")

    confirm_fn = None
    if cfg.confirm and cfg.probe_steps is not None and cfg.probe_steps != full_steps:
        def confirm_fn(lr: float) -> ProbeResult:  # noqa: E306
            return _train_and_read(lr, full_steps, full_eval, "confirm")

    search = LRSearch(
        run, initial_lr, factor=cfg.factor, min_ratio=cfg.min_ratio, max_probes=cfg.max_probes,
        resolution=cfg.resolution, lr_bounds=cfg.lr_bounds, confirm=confirm_fn,
        center_window=cfg.center_window, max_window_probes=cfg.max_window_probes,
    )
    result = search.search()
    payload = {**dict(metadata or {}), "initial_lr": float(initial_lr), **result.to_dict()}
    with open(os.path.join(experiment_dir, "lr_search.json"), "w", encoding="utf-8") as fh:
        json.dump(payload, fh, indent=2)
    return result

LRSearch

LRSearch(run, initial_lr, *, factor=10.0, min_ratio=None, max_probes=12, resolution='coarse', lr_bounds=(1e-12, 10.0), confirm=None, classify=classify_probe, center_window=True, max_window_probes=4, refine_fine=True, max_refine_probes=3, confirm_slow=True)

Bracket-and-bisect controller over a probe function.

Parameters:

Name Type Description Default
run Callable[[float], ProbeResult]

run(lr) -> ProbeResult; must be deterministic enough that repeating an LR is not needed.

required
initial_lr float

first guess (use a readable value such as 1e-6).

required
factor float

expansion step while no bracket exists (10 by default).

10.0
min_ratio Optional[float]

optional extra stop: the bracket is also closed once high / low <= min_ratio. None (default) closes it only when no untried grid value lies strictly inside, so the grid (resolution) alone sets the finest spacing.

None
max_probes int

budget for the bracketing phase. On exhaustion the status is budget_exhausted.

12
resolution str

"coarse" (1/2/5) or "fine" (1/1.5/2/3/5/7) grid for bisection candidates and window edges.

'coarse'
lr_bounds Tuple[float, float]

never propose an LR outside (lo, hi).

(1e-12, 10.0)
confirm Optional[Callable[[float], ProbeResult]]

optional confirm(lr) -> ProbeResult re-run (e.g. at the full budget) of a converged probe. A failed confirmation is classified like any probe and the search continues.

None
center_window bool

once a probe converges, walk outward along the grid until the neighbours stop converging and return the convergent LR closest (in log space) to the window's centre, instead of the first hit, which may sit on the edge of the stable range.

True
max_window_probes int

extra probes allowed for that walk (separate from max_probes), split evenly between the two sides (upward gets the odd one); the worst case is therefore max_probes + max_window_probes probes.

4
refine_fine bool

when a "coarse" search closes its bracket without a convergent LR, continue bisecting inside that bracket on the "fine" grid before giving up (gemma-3-27b GRADIEND: bracket 1e-6 slow / 2e-6 degrading had no coarse value in between).

True
max_refine_probes int

probe budget for that fine refinement.

3
confirm_slow bool

before reporting no_convergent_lr, re-run the highest-LR slow probe that was still at its best score when the probe ended through confirm (the full budget): a short probe cannot tell "too low" from "converges, but needs the full run".

True
Source code in gradiend/trainer/core/lr_search.py
def __init__(
    self,
    run: Callable[[float], ProbeResult],
    initial_lr: float,
    *,
    factor: float = 10.0,
    min_ratio: Optional[float] = None,
    max_probes: int = 12,
    resolution: str = "coarse",
    lr_bounds: Tuple[float, float] = (1e-12, 10.0),
    confirm: Optional[Callable[[float], ProbeResult]] = None,
    classify: Callable[[ProbeResult], RunState] = classify_probe,
    center_window: bool = True,
    max_window_probes: int = 4,
    refine_fine: bool = True,
    max_refine_probes: int = 3,
    confirm_slow: bool = True,
) -> None:
    if initial_lr <= 0:
        raise ValueError("initial_lr must be positive")
    if factor <= 1:
        raise ValueError("factor must be > 1")
    if resolution not in ("coarse", "fine"):
        raise ValueError(f"resolution must be 'coarse' or 'fine', got {resolution!r}")
    if min_ratio is not None and min_ratio <= 1:
        raise ValueError("min_ratio must be > 1 (or None)")
    self.run = run
    self.initial_lr = self._norm(initial_lr)
    self.factor = float(factor)
    self.min_ratio = None if min_ratio is None else float(min_ratio)
    self.max_probes = int(max_probes)
    self.resolution = resolution
    self.lr_bounds = lr_bounds
    self.confirm = confirm
    self.classify = classify
    self.center_window = bool(center_window)
    self.max_window_probes = int(max_window_probes)
    self.refine_fine = bool(refine_fine)
    self.max_refine_probes = int(max_refine_probes)
    self.confirm_slow = bool(confirm_slow)
    self.probes: List[Probe] = []

center_window instance-attribute

center_window = bool(center_window)

classify instance-attribute

classify = classify

confirm instance-attribute

confirm = confirm

confirm_slow instance-attribute

confirm_slow = bool(confirm_slow)

factor instance-attribute

factor = float(factor)

initial_lr instance-attribute

initial_lr = self._norm(initial_lr)

lr_bounds instance-attribute

lr_bounds = lr_bounds

max_probes instance-attribute

max_probes = int(max_probes)

max_refine_probes instance-attribute

max_refine_probes = int(max_refine_probes)

max_window_probes instance-attribute

max_window_probes = int(max_window_probes)

min_ratio instance-attribute

min_ratio = None if min_ratio is None else float(min_ratio)

probes instance-attribute

probes = []

refine_fine instance-attribute

refine_fine = bool(refine_fine)

resolution instance-attribute

resolution = resolution

run instance-attribute

run = run

_bracket

_bracket()

(highest 'too low' LR below the lowest 'too high' LR, lowest 'too high' LR).

Source code in gradiend/trainer/core/lr_search.py
def _bracket(self) -> Tuple[Optional[float], Optional[float]]:
    """(highest 'too low' LR below the lowest 'too high' LR, lowest 'too high' LR)."""
    highs = [p.lr for p in self.probes if p.state.direction < 0]
    high = min(highs) if highs else None
    lows = [p.lr for p in self.probes if p.state.direction > 0 and (high is None or p.lr < high)]
    low = max(lows) if lows else None
    return low, high

_converged_result

_converged_result(first_lr)
Source code in gradiend/trainer/core/lr_search.py
def _converged_result(self, first_lr: float) -> LRSearchResult:
    convergent = [first_lr]
    if self.center_window:
        # each side gets its own budget: a walk that spends everything upward would return the centre of
        # a truncated window (found on Qwen-2B: 1e-6 .. 2e-5 probed only upward)
        budgets = {+1: (self.max_window_probes + 1) // 2, -1: self.max_window_probes // 2}
        for direction in (+1, -1):
            found, _ = self._walk_window(first_lr, direction, budgets[direction])
            convergent.extend(found)
    lo, hi = min(convergent), max(convergent)
    centre = 0.5 * (math.log(lo) + math.log(hi))
    # ties go to the lower LR: the upper edge of the window is where runs collapse
    best = min(convergent, key=lambda c: (round(abs(math.log(c) - centre), 9), c))
    return LRSearchResult("converged", best, list(self.probes), window=(lo, hi))

_next_lr

_next_lr()
Source code in gradiend/trainer/core/lr_search.py
def _next_lr(self) -> Optional[float]:
    low, high = self._bracket()
    tried = self._tried()
    lo_b, hi_b = self.lr_bounds
    if low is None and high is None:
        return self.initial_lr
    # Expansion clamps to the bound instead of stopping short of it: gemma-3-270m AGIEND one-pole
    # was "slow" at 0.5, the x10 step (5.0) lies above the 1.0 bound, and the search used to end
    # after that single probe without ever trying 1.0.
    if high is None:  # only "too low" so far: expand upward
        nxt = self._norm(min(low * self.factor, hi_b))
        return nxt if nxt > low and nxt not in tried else None
    if low is None:  # only "too high" so far: expand downward
        nxt = self._norm(max(high / self.factor, lo_b))
        return nxt if nxt < high and nxt not in tried else None
    # bracket exists: bisect on the readable grid
    if self.min_ratio is not None and high / low <= self.min_ratio * (1 + 1e-9):
        return None
    inside = [c for c in nice_lr_grid(low, high, self.resolution) if self._norm(c) not in tried]
    if not inside:
        return None
    target = math.sqrt(low * high)
    return min(inside, key=lambda c: abs(math.log(c) - math.log(target)))

_norm staticmethod

_norm(lr)

Canonical float for an LR, so 1e-6 / 10 and the grid value 1e-7 compare equal.

Source code in gradiend/trainer/core/lr_search.py
@staticmethod
def _norm(lr: float) -> float:
    """Canonical float for an LR, so 1e-6 / 10 and the grid value 1e-7 compare equal."""
    return float(f"{lr:.9g}")

_probe

_probe(lr)
Source code in gradiend/trainer/core/lr_search.py
def _probe(self, lr: float) -> Probe:
    result = self.run(lr)
    state = self.classify(result)
    best = max(result.scores) if result.scores else None
    final = result.scores[-1] if result.scores else None
    probe = Probe(
        lr=lr, state=state, final_score=final, best_score=best, orientation=result.orientation,
        steps_run=result.steps[-1] if result.steps else None, **_probe_evidence(result),
    )
    if state is RunState.CONVERGED and self.confirm is not None:
        confirmed = self.confirm(lr)
        cstate = self.classify(confirmed)
        probe.confirmed = cstate is RunState.CONVERGED
        if not probe.confirmed:
            probe.state = cstate
            probe.note = f"probe converged but the confirmation run was {cstate.value}"
            probe.final_score = confirmed.scores[-1] if confirmed.scores else None
            probe.best_score = max(confirmed.scores) if confirmed.scores else None
            probe.orientation = confirmed.orientation
            for name, value in _probe_evidence(confirmed).items():
                setattr(probe, name, value)
    logger.info(
        "lr_search: lr=%g -> %s (final=%s best=%s)%s%s",
        lr, probe.state.value, probe.final_score, probe.best_score,
        " [scores negated: the encoder learned the anti-aligned sign]" if probe.orientation < 0 else "",
        f" [{probe.note}]" if probe.note else "",
    )
    return probe

_still_improving_slow_probe

_still_improving_slow_probe()

Highest-LR slow probe below the bracket's high end whose score ended at its best.

Source code in gradiend/trainer/core/lr_search.py
def _still_improving_slow_probe(self) -> Optional[Probe]:
    """Highest-LR ``slow`` probe below the bracket's high end whose score ended at its best."""
    _, high = self._bracket()
    candidates = [
        p for p in self.probes
        if p.state is RunState.SLOW and p.confirmed is None
        and (high is None or p.lr < high)
        and p.final_score is not None and p.best_score is not None
        and p.final_score >= p.best_score - 0.02
    ]
    return max(candidates, key=lambda p: p.lr) if candidates else None

_tried

_tried()
Source code in gradiend/trainer/core/lr_search.py
def _tried(self) -> Dict[float, Probe]:
    return {self._norm(p.lr): p for p in self.probes}

_walk_window

_walk_window(first_lr, direction, budget)

Follow the grid from first_lr while neighbours keep converging; return (LRs, budget left).

Source code in gradiend/trainer/core/lr_search.py
def _walk_window(self, first_lr: float, direction: int, budget: int) -> Tuple[List[float], int]:
    """Follow the grid from ``first_lr`` while neighbours keep converging; return (LRs, budget left)."""
    found: List[float] = []
    edge = first_lr
    lo_b, hi_b = self.lr_bounds
    while True:
        nxt = self._norm(grid_neighbor(edge, direction, self.resolution))
        if not lo_b <= nxt <= hi_b:
            break
        known = self._tried().get(nxt)
        if known is None:
            if budget <= 0:
                break
            known = self._probe(nxt)
            self.probes.append(known)
            budget -= 1
        if known.state is not RunState.CONVERGED:
            break
        found.append(nxt)
        edge = nxt
    return found, budget

search

search()
Source code in gradiend/trainer/core/lr_search.py
def search(self) -> LRSearchResult:
    while len(self.probes) < self.max_probes:
        lr = self._next_lr()
        if lr is None:
            break
        probe = self._probe(lr)
        self.probes.append(probe)
        if probe.state is RunState.CONVERGED:
            return self._converged_result(probe.lr)
    bracket_closed = self._next_lr() is None
    if bracket_closed and self.refine_fine and self.resolution == "coarse":
        low, high = self._bracket()
        if low is not None and high is not None:
            self.resolution = "fine"
            logger.info("lr_search: coarse bracket (%g, %g) closed without convergence; refining on the fine grid", low, high)
            for _ in range(self.max_refine_probes):
                lr = self._next_lr()
                if lr is None:
                    break
                probe = self._probe(lr)
                self.probes.append(probe)
                if probe.state is RunState.CONVERGED:
                    return self._converged_result(probe.lr)
    if self._next_lr() is None and self.confirm_slow and self.confirm is not None:
        slow = self._still_improving_slow_probe()
        if slow is not None:
            logger.info("lr_search: lr=%g was still improving when its probe ended; running it at the full budget", slow.lr)
            confirmed = self.confirm(slow.lr)
            cstate = self.classify(confirmed)
            slow.confirmed = cstate is RunState.CONVERGED
            slow.note = f"slow probe re-run at the full budget: {cstate.value}"
            slow.final_score = confirmed.scores[-1] if confirmed.scores else slow.final_score
            slow.best_score = max(confirmed.scores) if confirmed.scores else slow.best_score
            slow.orientation = confirmed.orientation
            logger.info("lr_search: lr=%g at the full budget -> %s", slow.lr, cstate.value)
            if slow.confirmed:
                slow.state = RunState.CONVERGED
                return LRSearchResult("converged", slow.lr, list(self.probes), window=(slow.lr, slow.lr))
    low, high = self._bracket()
    bracket = (low, high) if low is not None and high is not None else None
    exhausted = len(self.probes) >= self.max_probes and self._next_lr() is not None
    status = "budget_exhausted" if exhausted else "no_convergent_lr"
    return LRSearchResult(status, None, list(self.probes), bracket)

LRSearchResult dataclass

LRSearchResult(status, best_lr, probes, bracket=None, window=None)

best_lr instance-attribute

best_lr

bracket class-attribute instance-attribute

bracket = None

probes instance-attribute

probes

status instance-attribute

status

window class-attribute instance-attribute

window = None

from_dict classmethod

from_dict(d)

Inverse of :meth:to_dict (e.g. for a stored lr_search.json).

Source code in gradiend/trainer/core/lr_search.py
@classmethod
def from_dict(cls, d: Mapping[str, Any]) -> "LRSearchResult":
    """Inverse of :meth:`to_dict` (e.g. for a stored ``lr_search.json``)."""
    probes = [
        Probe(
            lr=p["lr"], state=RunState(p["state"]), final_score=p.get("final_score"), best_score=p.get("best_score"),
            confirmed=p.get("confirmed"), steps_run=p.get("steps_run"), note=p.get("note", ""),
            metric=p.get("metric"), threshold=p.get("threshold"), min_class_mean=p.get("min_class_mean"),
            class_mean_threshold=p.get("class_mean_threshold"), orientation=p.get("orientation", 1),
        )
        for p in d.get("probes", [])
    ]
    bracket, window = d.get("bracket"), d.get("window")
    return cls(d["status"], d.get("best_lr"), probes, tuple(bracket) if bracket else None, tuple(window) if window else None)

plot

plot(*, output=None, show=True, title=None)

Plot what the search did.

Every probe (a short training run) is one dot at its learning rate, numbered in the order it ran and coloured by its state: blue too low, green converged, orange/red too high. The top panel shows the convergence score (the correlation of the encoded value with the class) the probe reached; the bottom panel the weaker of the two class means. A probe converges only if both reach their threshold (dotted lines). The green band is the convergent range, the dashed line the chosen learning rate, and a ring marks a probe that was re-run for the full max_steps. Needs matplotlib.

Parameters:

Name Type Description Default
output Optional[str]

Optional path to save the figure to.

None
show bool

Whether to call plt.show().

True
title Optional[str]

Optional title (default: the search status and the chosen learning rate).

None

Returns:

Type Description
Any

The matplotlib figure.

Source code in gradiend/trainer/core/lr_search.py
def plot(self, *, output: Optional[str] = None, show: bool = True, title: Optional[str] = None) -> Any:
    """Plot what the search did.

    Every probe (a short training run) is one dot at its learning rate, numbered in the order it ran and coloured by
    its state: blue too low, green converged, orange/red too high. The top panel shows the convergence score
    (the correlation of the encoded value with the class) the probe reached; the bottom panel the weaker of the two
    class means. A probe converges only if both reach their threshold (dotted lines). The green band is the
    convergent range, the dashed line the chosen learning rate, and a ring marks a probe that was re-run for the full
    ``max_steps``. Needs matplotlib.

    Args:
        output: Optional path to save the figure to.
        show: Whether to call ``plt.show()``.
        title: Optional title (default: the search status and the chosen learning rate).

    Returns:
        The matplotlib figure.
    """
    try:
        import matplotlib.pyplot as plt
        from matplotlib.ticker import FuncFormatter, LogLocator
    except ImportError as exc:  # pragma: no cover - matplotlib is a dependency of the plotting extras
        raise ImportError("LRSearchResult.plot needs matplotlib: pip install matplotlib") from exc

    colors = {
        RunState.FROZEN: ("#9ecae1", "frozen (too low)"),
        RunState.SLOW: ("#1f77b4", "slow (too low)"),
        RunState.CONVERGED: ("#2ca02c", "converged"),
        RunState.DEGRADING: ("#fdae6b", "degrading (too high)"),
        RunState.COLLAPSED: ("#e6550d", "collapsed (too high)"),
        RunState.DIVERGED: ("#a50f15", "diverged (too high)"),
    }

    def first(values):
        return next((v for v in values if v is not None), None)

    metric = first(p.metric for p in self.probes) or "score"
    threshold = first(p.threshold for p in self.probes)
    mean_threshold = first(p.class_mean_threshold for p in self.probes)
    with_means = any(p.min_class_mean is not None for p in self.probes)

    scores = [p.best_score for p in self.probes if p.best_score is not None]
    score_floor = min([0.5 if threshold is None else threshold - 0.1, *scores]) - 0.1
    panels = [("best " + metric + " in the probe", lambda p: p.best_score, score_floor, 1.18, threshold,
               "convergence threshold")]
    if with_means:
        panels.append(("weaker class mean |m|\nat that evaluation", lambda p: p.min_class_mean, 0.0, 1.1, mean_threshold,
                       "class-mean threshold"))
    fig, axes = plt.subplots(len(panels), 1, sharex=True, squeeze=False, figsize=(8.8, 2.9 * len(panels) + 0.5),
                             gridspec_kw={"height_ratios": [3, 2][: len(panels)], "hspace": 0.12})
    for row, (label, value, floor, top, line, line_label) in enumerate(panels):
        ax = axes[row][0]
        if self.window:
            ax.axvspan(*self.window, color="#2ca02c", alpha=0.12, label="convergent range", zorder=0)
        if line is not None:
            ax.axhline(line, color="0.45", ls=":", lw=1.2, zorder=1)
            ax.annotate(line_label, (0.005, line), xycoords=("axes fraction", "data"), textcoords="offset points",
                        xytext=(3, 3), fontsize=8, color="0.35")
        points = [(p, floor if value(p) is None else value(p)) for p in self.probes]
        for state, (color, state_label) in colors.items():
            xs = [(p.lr, y) for p, y in points if p.state == state and (value(p) is not None or row == 0)]
            if xs:
                ax.scatter(*zip(*xs), s=70, color=color, edgecolor="white", label=state_label, zorder=3)
        if row == 0:
            confirmed = [(p.lr, y) for p, y in points if p.confirmed]
            if confirmed:
                ax.scatter(*zip(*confirmed), s=190, facecolors="none", edgecolors="black", linewidths=1.2,
                           label="re-run for the full max_steps", zorder=2)
            for order, (p, y) in enumerate(points, start=1):
                ax.annotate(str(order), (p.lr, y), textcoords="offset points", xytext=(0, 9), ha="center", fontsize=9)
        if self.best_lr is not None:
            ax.axvline(self.best_lr, color="black", ls="--", lw=1, zorder=0)
            if row == len(panels) - 1:
                ax.annotate(f"chosen {_format_lr(self.best_lr)}", (self.best_lr, 0.03), xycoords=("data", "axes fraction"),
                            textcoords="offset points", xytext=(4, 0), ha="left", va="bottom", fontsize=9)
        ax.set_ylim(floor, top)
        ax.set_ylabel(label)
        ax.grid(alpha=0.25)
    ax = axes[-1][0]
    ax.set_xscale("log")
    ax.xaxis.set_major_locator(LogLocator(base=10, subs=(1.0, 2.0, 5.0)))  # the 1/2/5 grid of the search
    ax.xaxis.set_major_formatter(FuncFormatter(lambda value, _: _format_lr(value)))
    ax.tick_params(axis="x", labelsize=8)
    ax.set_xlabel("learning rate")
    axes[0][0].set_title(title or (f"Learning-rate search: {self.status}"
                                   + (f", chosen {_format_lr(self.best_lr)}" if self.best_lr else "")))
    axes[0][0].legend(loc="center left", bbox_to_anchor=(1.01, 0.0 if len(panels) > 1 else 0.5), fontsize=8, frameon=False)
    if output:
        os.makedirs(os.path.dirname(os.path.abspath(output)), exist_ok=True)
        fig.savefig(output, dpi=200, bbox_inches="tight")
    if show:
        plt.show()
    return fig

to_dict

to_dict()
Source code in gradiend/trainer/core/lr_search.py
def to_dict(self) -> Dict[str, Any]:
    return {
        "status": self.status,
        "best_lr": self.best_lr,
        "bracket": list(self.bracket) if self.bracket else None,
        "window": list(self.window) if self.window else None,
        "probes": [p.to_dict() for p in self.probes],
    }