Skip to content

Checkpoint Monitors

A monitor is a plain callable that names the values it wants as its parameters. The driver reads the signature once, at setup, and then calls the monitor by keyword with exactly those values.

def watch(iters, n_filled, best_logL):    # free
    bar.update(iters)

def watch(iters, elite_ij, elite_logL, grid):   # free: read for the landscape
    chart.show(elite_ij, elite_logL)

def watch(iters, logL_map):               # one bounded transfer
    queue.put((iters, logL_map))

def watch(iters, trees):                  # state read and rebuild
    popup.update(iters, trees)

A value that costs a device read is read only when a monitor names it. An unknown name raises before any survey work starts. Every snapshot is a copy and can be pickled, so a monitor that sends checkpoints to another process is one line.

The default reporter shows the growth exponent beta under the QD-score rule, and the coverage and precision rates under the rate rule.

bind_monitor

bind_monitor(monitor, *, caps, n_checkpoints: int, rate_window: int = 1, halt_rule: str = 'qd_score') -> BoundMonitor | None

Resolve a monitor against the vocabulary and the backend.

monitor=None selects the default reporter for halt_rule. monitor=False gives None, and the driver then calls nothing. Any other value must be a callable.

Raises:

Type Description
ValueError

An unknown parameter name, or a trees request that the backend cannot serve.

Source code in src/hifuku/monitor.py
def bind_monitor(monitor, *, caps, n_checkpoints: int,
                 rate_window: int = 1,
                 halt_rule: str = "qd_score") -> BoundMonitor | None:
    """Resolve a monitor against the vocabulary and the backend.

    ``monitor=None`` selects the default reporter for ``halt_rule``.
    ``monitor=False`` gives None, and the driver then calls nothing.  Any
    other value must be a callable.

    Raises
    ------
    ValueError
        An unknown parameter name, or a ``trees`` request that the backend
        cannot serve.
    """
    if monitor is False:
        return None
    if monitor is None:
        monitor = default_reporter(n_checkpoints, rate_window,
                                   halt_rule=halt_rule)
    if not callable(monitor):
        raise TypeError(
            f"monitor must be callable, None or False, got {type(monitor).__name__}")

    names = _requested_names(monitor)
    unknown = names - MONITOR_NAMES
    if unknown:
        raise ValueError(
            f"unknown monitor parameter {sorted(unknown)}; "
            f"use one of {sorted(MONITOR_NAMES)}")

    wants_trees = "trees" in names
    if wants_trees and not caps.can_read_trees:
        raise ValueError(
            f"the {caps.name} backend cannot serve 'trees' to a monitor")
    if wants_trees and not caps.unified_memory:
        warnings.warn(
            f"the {caps.name} backend has no unified memory, so a 'trees' "
            "monitor copies the archive state at every checkpoint.  Lower "
            "checkpoint_every or drop 'trees' if the run slows down.",
            RuntimeWarning, stacklevel=3)

    return BoundMonitor(fn=monitor, names=names, wants_map="logL_map" in names,
                        wants_trees=wants_trees,
                        wants_shoreline="shoreline" in names)

Checkpoint dataclass

One checkpoint of a running survey.

logL_map and trees are None unless a monitor named them.

beta is the growth exponent of the QD-score at this checkpoint. See :mod:hifuku.halt. It is None under the rate rule, before the guard, and when the exponent is undecided.

closing is True only on the closing call. The driver makes that call once, after the run ends, and only to a monitor that names shoreline and runs with an alignment. The call repeats the free values of the final checkpoint, including final=True. It gives logL_map and trees as None, and adds shoreline, the :class:~hifuku.analysis.Shoreline of the final archive, or None when it cannot be computed. A monitor that names shoreline must also name closing, or it cannot tell the closing call from the final checkpoint.

Source code in src/hifuku/monitor.py
@dataclass(frozen=True)
class Checkpoint:
    """One checkpoint of a running survey.

    ``logL_map`` and ``trees`` are None unless a monitor named them.

    ``beta`` is the growth exponent of the QD-score at this checkpoint.  See
    :mod:`hifuku.halt`.  It is None under the rate rule, before the guard,
    and when the exponent is undecided.

    ``closing`` is True only on the closing call.  The driver makes that call
    once, after the run ends, and only to a monitor that names
    ``shoreline`` and runs with an alignment.  The call repeats the free
    values of the final checkpoint, including ``final=True``.  It gives
    ``logL_map`` and ``trees`` as None, and adds ``shoreline``, the
    :class:`~hifuku.analysis.Shoreline` of the final archive, or None when it
    cannot be computed.  A monitor that names ``shoreline`` must also name
    ``closing``, or it cannot tell the closing call from the final
    checkpoint.
    """

    task: Any
    iters: int
    n_filled: int
    best_logL: float
    coverage: float
    precision: float
    converged: bool
    final: bool
    elapsed: float
    logL_map: np.ndarray | None = None
    trees: dict | None = None
    #: The occupied niches ``(i, j)``, shape ``(n, 2)``, and the
    #: log-likelihood of each, as the driver read them for the landscape row
    #: of this checkpoint.  They are copies.
    elite_ij: np.ndarray | None = None
    elite_logL: np.ndarray | None = None
    #: The origin and the cell side of the niche grid.
    grid: tuple | None = None
    beta: float | None = None
    closing: bool = False
    shoreline: Any = None

BoundMonitor dataclass

A monitor with its parameter names resolved.

Attributes:

Name Type Description
fn callable

The monitor.

names frozenset[str]

The values to pass. A **kwargs monitor gets FREE_NAMES.

wants_map bool

True when the driver must read the log-likelihood grid.

wants_trees bool

True when the driver must read the archive state and rebuild the trees.

wants_shoreline bool

True when the driver must compute the shoreline of the final archive and make the closing call.

Source code in src/hifuku/monitor.py
@dataclass(frozen=True)
class BoundMonitor:
    """A monitor with its parameter names resolved.

    Attributes
    ----------
    fn : callable
        The monitor.
    names : frozenset[str]
        The values to pass.  A ``**kwargs`` monitor gets ``FREE_NAMES``.
    wants_map : bool
        True when the driver must read the log-likelihood grid.
    wants_trees : bool
        True when the driver must read the archive state and rebuild the trees.
    wants_shoreline : bool
        True when the driver must compute the shoreline of the final archive
        and make the closing call.
    """

    fn: Any
    names: frozenset
    wants_map: bool
    wants_trees: bool
    wants_shoreline: bool = False

    def __call__(self, checkpoint: Checkpoint) -> None:
        self.fn(**{name: getattr(checkpoint, name) for name in self.names})

default_reporter

default_reporter(n_checkpoints: int, rate_window: int = 1, stream=None, halt_rule: str = 'qd_score')

Build the monitor that runs when the caller gives none.

The reporter writes survey statistics to stderr. It is an ordinary monitor, so it goes through the same signature check as any other monitor. It names free values and shoreline.

Each run's lines are headed by the gene and the chart they measure, so a batch that surveys nine markers into one log says which block is which. See :func:_survey_heading.

The cadence comes from the budget. The reporter writes one line every max(1, n_checkpoints // 8) checkpoints and always writes the last one. A run of any size therefore gives about five to ten lines per gene. Output goes to stderr so that stdout stays clean.

Each line also reports the quantity the halt rule reads. Under the QD-score rule this is the growth exponent beta. Before the guard, or while the exponent is undecided, the line shows beta (guard).

Under the rate rule the line shows the two rates. The rates need a trailing window of rate_window checkpoints. Until that many exist the rates have no value, and the line reports how much of the window has filled instead. A reader then sees progress toward a halt rather than a column of nan.

At the closing call the reporter writes one more line. It gives the edge z of the final archive on the per-tree Kishino-Hasegawa scale, the niche that sets it, and the z at the gate when there is one::

shorelines close below z = 1.22 (edge niche (31, 40)); gate at z = 4.43

When the shoreline cannot be computed, the line reads no shoreline for this archive. See :func:hifuku.analysis.shoreline.

Source code in src/hifuku/monitor.py
def default_reporter(n_checkpoints: int, rate_window: int = 1, stream=None,
                     halt_rule: str = "qd_score"):
    """Build the monitor that runs when the caller gives none.

    The reporter writes survey statistics to stderr.  It is an ordinary monitor,
    so it goes through the same signature check as any other monitor.  It names
    free values and ``shoreline``.

    Each run's lines are headed by the gene and the chart they measure, so a
    batch that surveys nine markers into one log says which block is which.  See
    :func:`_survey_heading`.

    The cadence comes from the budget.  The reporter writes one line every
    ``max(1, n_checkpoints // 8)`` checkpoints and always writes the last one.
    A run of any size therefore gives about five to ten lines per gene.  Output
    goes to stderr so that stdout stays clean.

    Each line also reports the quantity the halt rule reads.  Under the
    QD-score rule this is the growth exponent ``beta``.  Before the guard, or
    while the exponent is undecided, the line shows ``beta (guard)``.

    Under the rate rule the line shows the two rates.  The rates need a
    trailing window of ``rate_window`` checkpoints.  Until that many exist the
    rates have no value, and the line reports how much of the window has
    filled instead.  A reader then sees progress toward a halt rather than a
    column of ``nan``.

    At the closing call the reporter writes one more line.  It gives the
    edge z of the final archive on the per-tree Kishino-Hasegawa scale, the
    niche that sets it, and the z at the gate when there is one::

        shorelines close below z = 1.22 (edge niche (31, 40)); gate at z = 4.43

    When the shoreline cannot be computed, the line reads ``no shoreline for
    this archive``.  See :func:`hifuku.analysis.shoreline`.
    """
    every = max(1, n_checkpoints // _DEFAULT_REPORTS)
    seen = [0]

    def report(task, iters, n_filled, best_logL, coverage, precision, final,
               beta=None, closing=False, shoreline=None):
        out = sys.stderr if stream is None else stream
        if closing:
            if shoreline is None:
                print("  no shoreline for this archive", file=out)
                return
            line = (f"  shorelines close below z = {shoreline.edge_z:.2f} "
                    f"(edge niche {shoreline.edge_key})")
            if shoreline.gate_z is not None:
                line += f"; gate at z = {shoreline.gate_z:.2f}"
            print(line, file=out)
            return
        seen[0] += 1
        # A batch surveys one gene after another through one reporter each, so
        # the first checkpoint of a run is where its block of lines begins.  The
        # heading goes to the same stream as the lines it heads, which is what
        # keeps the two together in a log that holds both streams.
        if seen[0] == 1:
            print(_survey_heading(task), file=out, flush=True)
        if not final and seen[0] % every:
            return
        line = (f"  iters={iters:>10d}  niches={n_filled:>7d}  "
                f"best={best_logL:>14.3f}")
        if halt_rule == "qd_score":
            line += ("  beta (guard)" if beta is None
                     else f"  beta={beta:.3f}")
        elif math.isnan(coverage) or math.isnan(precision):
            line += f"  halt window {min(seen[0], rate_window)}/{rate_window}"
        else:
            line += f"  coverage={coverage:.3e}  precision={precision:.3e}"
        print(line, file=out)

    return report