Skip to content

Survey Driver

One driver runs the survey for every backend. It owns the checkpoint cadence, the halt rule and the monitor, and a backend owns the search.

The next chunk of work goes to the device before the monitor runs, so host work in a monitor overlaps device work. The map read and the tree read come first, because the next chunk changes the archive.

The halt_rule parameter selects one of two halt rules. The driver decides the halt for every backend, so each parameter of each rule has one meaning on every engine.

  • "qd_score", the default. At each checkpoint the driver records the sum S, the count N and the running minimum m of the elite log-likelihoods. The survey halts when a doubling of effort multiplies the QD-score S - N m by 2**qd_tau or less. The rule judges no checkpoint before 2**HALT_QD_GUARD_DOUBLINGS times the variations of the first checkpoint. The rule is in hifuku.halt. When the budget ends first, the driver issues a RuntimeWarning that gives the growth exponent and three projections of the cost to reach qd_tau. A budget with too few checkpoints to pass the guard gives a RuntimeWarning before the run.
  • "rate". The survey halts when the trailing window of rate_window checkpoints that windowed_rates measures falls to or below rate_coverage_eps and rate_precision_eps. A budget with fewer checkpoints than rate_window gives a RuntimeWarning before the run.

The run parameters page lists the parameters of each rule and their defaults.

Every checkpoint also records a landscape row, a move tally and its row of (S, N, m), under either rule.

run_survey

run_survey(backend, ctx, params, *, monitor=None, task=None, resume=None) -> ArchiveResult

Run one survey on one backend and return the result.

Parameters:

Name Type Description Default
backend

An object that obeys the :class:~hifuku.backend.Backend protocol.

required
ctx RunContext

The trees, alignment, model and chart geometry for this survey. It is also what an engine sizes the run against.

required
params ArchiveParams

The resolved run parameters. A field left as "auto" is settled by backend.fit before anything reads a pass size from it, so the driver's checkpoint accounting and the backend's launch geometry are the same numbers.

required
monitor (callable, None or False)

A checkpoint callback. None selects the default reporter and False turns reporting off. See :mod:hifuku.monitor.

None
task SurveyTask

Passed to the monitor so that a caller can tell surveys apart.

None
resume RunSnapshot

Carry on a survey that stopped. The archive and the random state are restored in place of seeding, so the run continues rather than starting a similar one.

n_iters is the budget for this call, not a total: resuming with a budget of a million makes a million more variations. The history, the halt window and the QD-score rows continue across the break, so a resumed run reports one survey rather than two.

On both engines a resumed survey reaches the elites that an unbroken survey of the same total length reaches. This is true for a snapshot in hand and for a snapshot read back from a file. Both engines hold every tree they walk from in canonical form, so a restored archive has the numbering of the archive in the unbroken run.

None

Raises:

Type Description
ValueError

The monitor names an unknown value, or a value this backend cannot serve. The check runs before any survey work starts.

Source code in src/hifuku/driver.py
def run_survey(backend, ctx, params, *, monitor=None, task=None,
               resume=None) -> ArchiveResult:
    """Run one survey on one backend and return the result.

    Parameters
    ----------
    backend
        An object that obeys the :class:`~hifuku.backend.Backend` protocol.
    ctx : RunContext
        The trees, alignment, model and chart geometry for this survey.  It is
        also what an engine sizes the run against.
    params : ArchiveParams
        The resolved run parameters.  A field left as ``"auto"`` is settled by
        ``backend.fit`` before anything reads a pass size from it, so the
        driver's checkpoint accounting and the backend's launch geometry are
        the same numbers.
    monitor : callable, None or False
        A checkpoint callback.  None selects the default reporter and False
        turns reporting off.  See :mod:`hifuku.monitor`.
    task : SurveyTask, optional
        Passed to the monitor so that a caller can tell surveys apart.
    resume : RunSnapshot, optional
        Carry on a survey that stopped.  The archive and the random state are
        restored in place of seeding, so the run continues rather than starting
        a similar one.

        ``n_iters`` is the budget for this call, not a total: resuming with a
        budget of a million makes a million more variations.  The history, the
        halt window and the QD-score rows continue across the break, so a
        resumed run reports one survey rather than two.

        On both engines a resumed survey reaches the elites that an unbroken
        survey of the same total length reaches.  This is true for a snapshot
        in hand and for a snapshot read back from a file.  Both engines hold
        every tree they walk from in canonical form, so a restored archive has
        the numbering of the archive in the unbroken run.

    Raises
    ------
    ValueError
        The monitor names an unknown value, or a value this backend cannot
        serve.  The check runs before any survey work starts.
    """
    called = time.perf_counter()
    # The cell comes first, and it comes from the data rather than from the
    # engine: it is the step one nearest-neighbor interchange makes across this
    # chart for this gene.  Both engines are then given the same grid, which is
    # what keeps the host survey a parity oracle for the device survey.
    params = _resolve_cell(ctx, params)

    # The engine settles what is left.  A walker count is bounded by the memory
    # the machine has and by what the gene costs, and both are known only here,
    # so the driver asks rather than assumes.  Every line below reads the answer.
    params = backend.fit(ctx, params)

    per_checkpoint = params.passes_per_checkpoint * params.variations_per_pass
    n_checkpoints = max(1, params.n_iters // per_checkpoint)

    # Each rule needs a number of checkpoints before it can halt, and a budget
    # that holds fewer cannot fire it.  Say so before the run, because the
    # caller asked for a halt and would otherwise wait for one that cannot
    # come.
    asks_for_a_halt = params.converge and not params.force_full_run
    if (asks_for_a_halt and params.halt_rule == "rate"
            and n_checkpoints < params.rate_window):
        warnings.warn(
            f"this budget gives {n_checkpoints} checkpoints and the halt needs "
            f"a window of {params.rate_window}, so the survey cannot halt on "
            f"saturation and will run the full budget.  Raise n_iters, lower "
            f"checkpoint_every, or lower rate_window.",
            RuntimeWarning, stacklevel=2)
    # The QD-score rule judges no checkpoint before the guard.  A resume that
    # carries QD-score rows may be past the guard already.
    guard = 2 ** HALT_QD_GUARD_DOUBLINGS
    if (asks_for_a_halt and params.halt_rule == "qd_score"
            and (resume is None or resume.qd is None)
            and n_checkpoints < guard + 1):
        warnings.warn(
            f"this budget gives {n_checkpoints} checkpoints.  The QD-score "
            f"rule judges a checkpoint only at {guard} or more times the "
            f"variations of the first checkpoint, so this survey can halt at "
            f"{max(0, n_checkpoints - guard + 1)} checkpoints at most and "
            f"will probably run the full budget.  Raise n_iters or lower "
            f"checkpoint_every.",
            RuntimeWarning, stacklevel=2)

    # Validate the monitor before the run starts.  A typo must not surface
    # twenty minutes into a survey.
    bound = bind_monitor(monitor, caps=backend.caps, n_checkpoints=n_checkpoints,
                         rate_window=params.rate_window,
                         halt_rule=params.halt_rule)
    # The closing call repeats the last checkpoint the monitor saw.
    last_checkpoint = None

    # The gate scales with the alignment, so the site count is read once here
    # rather than at every checkpoint.
    n_sites = _site_count(ctx)

    n_restored = 0
    start_state = ""
    if resume is not None:
        from hifuku.seal import archive_state
        # Before the engine reads the snapshot, so the digest is of the state
        # as it was handed over.
        start_state = archive_state(
            resume.archive,
            np.zeros((0, 5)) if resume.history is None else resume.history,
            resume, landscape=resume.landscape, moves=resume.moves,
            qd=resume.qd)
        params = _shape_of(resume, params, backend)
        n_restored = resume.archive.n_filled
    handle = backend.prepare(ctx, params, n_restored=n_restored)
    if resume is None:
        backend.seed(handle)
    else:
        backend.resume(handle, resume.archive, resume.rng, gain=resume.gain,
                       moves=resume.moves_total)
    backend.sync()

    stats = backend.read_stats(handle)
    if resume is None:
        keys = backend.read_keys(handle, 0)
    else:
        # The saved list, in its order.  Reading the engine back instead would
        # give the same niches arranged as one sorted run, because a resume
        # places them all at once where the run that found them placed them a
        # pass at a time, and the order is what the parent draw indexes into.
        keys = np.asarray(resume.keys)
        if len(keys) != stats.n_keys:
            # Not a warning: a survey that continued from part of its snapshot
            # would record a start state it did not have.
            backend.finalize(handle)
            raise ValueError(
                f"the snapshot lists {len(keys)} niches and the engine holds "
                f"{stats.n_keys} after restoring it, so some elite did not land "
                f"on this run's grid.  A continuation starts from the whole "
                f"state of its parent, so the grid and the extent must be the "
                f"ones the parent ran with")
    n_copied = stats.n_keys

    if resume is None:
        history = [(0, stats.n_keys, stats.best, float("nan"), float("nan"))]
        seeded = _elites(backend, handle, _floor(params, stats.best, n_sites))
        landscape = [landscape_row(*seeded)]
        qd_rows = [_qd_row(seeded[1], [])]
        moves = (None if stats.moves is None
                 else [np.zeros_like(stats.moves, dtype=np.int64)])
        cp_new: list[int] = []
        cp_gain: list[float] = []
        total = 0
    else:
        # The earlier legs' rows and halt window carry over, so a resumed survey
        # reports one history rather than two and can halt on the checkpoints
        # either side of the break.
        history = ([] if resume.history is None
                   else [tuple(row) for row in np.asarray(resume.history)])
        landscape = ([] if resume.landscape is None
                     else [tuple(row) for row in np.asarray(resume.landscape)])
        # A parent with no QD-score rows gives none, and the rule then
        # decides over this run's own rows only.
        qd_rows = ([] if resume.qd is None
                   else [tuple(float(v) for v in row)
                         for row in np.asarray(resume.qd)])
        if stats.moves is None:
            moves = None
        else:
            moves = ([] if resume.moves is None
                     else [np.asarray(block, dtype=np.int64)
                           for block in np.asarray(resume.moves)])
        cp_new = list(resume.cp_new)
        cp_gain = list(resume.cp_gain)
        total = int(resume.variations)
    # Only the differences of the gain counter are read.  A resumed engine
    # starts its counter where the snapshot left it, so these differences are
    # the ones an unbroken run reads.
    prev_keys, prev_gain = stats.n_keys, stats.gain
    # The tally is read the same way: a resumed engine starts its counters at
    # the snapshot's tally, so these differences are the unbroken run's too.
    prev_moves = stats.moves
    converged, halt_iter = False, -1
    started = time.perf_counter()

    # A device engine times its own launches, and a checkpoint's seconds are
    # how far that timer moved.  On the host a chunk runs inside the submit
    # call, so the call is timed instead.
    device_work = getattr(backend, "device_work", None)
    device_seen = 0.0 if device_work is None else device_work.seconds
    checkpoint_seconds: list[float] = []

    def submit(floor):
        nonlocal chunk_seconds
        begun = time.perf_counter()
        backend.submit_batch(handle, keys, per_checkpoint, floor)
        chunk_seconds = time.perf_counter() - begun

    chunk_seconds = 0.0
    if keys.size:
        submit(_floor(params, stats.best, n_sites))

        for cp in range(n_checkpoints):
            backend.sync()
            stats = backend.read_stats(handle)
            total += per_checkpoint

            if device_work is None:
                checkpoint_seconds.append(chunk_seconds)
            else:
                seen = device_work.seconds
                checkpoint_seconds.append(seen - device_seen)
                device_seen = seen

            cp_new.append(stats.n_keys - prev_keys)
            cp_gain.append(stats.gain - prev_gain)
            prev_keys, prev_gain = stats.n_keys, stats.gain
            if moves is not None:
                moves.append(np.asarray(stats.moves - prev_moves,
                                        dtype=np.int64))
                prev_moves = stats.moves

            coverage, precision = windowed_rates(
                cp_new, cp_gain, stats.elite_range or 1.0, params.rate_window,
                stats.n_keys)
            history.append((total, stats.n_keys, stats.best, coverage, precision))
            elites = _elites(backend, handle, _floor(params, stats.best, n_sites))
            qd_rows.append(_qd_row(elites[1], qd_rows))

            if params.halt_rule == "rate":
                rule_met = survey_converged(coverage, precision,
                                            params.rate_coverage_eps,
                                            params.rate_precision_eps)
                beta = None
            else:
                rule_met, beta, _, _ = _qd_decision(
                    history, qd_rows, params.qd_tau)
            halting = asks_for_a_halt and rule_met
            if halting:
                converged, halt_iter = True, total

            if stats.n_keys > n_copied:
                fresh = backend.read_keys(handle, n_copied)
                keys = np.concatenate([keys, fresh]) if keys.size else fresh
                n_copied = stats.n_keys

            # The next chunk changes the archive, so every read comes first.
            logL_map = backend.read_map(handle) if bound and bound.wants_map else None
            trees = backend.read_trees(handle) if bound and bound.wants_trees else None

            more = (cp + 1 < n_checkpoints) and not halting and keys.size > 0
            if more:
                submit(_floor(params, stats.best, n_sites))

            # The row is built from the copies read above.  The host does this
            # work while the device runs the next chunk.
            landscape.append(landscape_row(*elites))

            if bound is not None:
                last_checkpoint = Checkpoint(
                    task=task, iters=total, n_filled=stats.n_keys,
                    best_logL=stats.best, coverage=coverage, precision=precision,
                    converged=converged, final=not more,
                    elapsed=time.perf_counter() - started,
                    logL_map=logL_map, trees=trees, beta=beta,
                    elite_ij=elites[0], elite_logL=elites[1],
                    grid=(float(params.origin), float(params.cell)))
                bound(last_checkpoint)

            if not more:
                break

    illuminated = time.perf_counter()

    # A budget that ends before the QD-score rule halts gets a warning.  It
    # gives the growth exponent at the last checkpoint and what three
    # accumulation functions fitted to this survey project.
    if (asks_for_a_halt and not converged and params.halt_rule == "qd_score"
            and qd_rows):
        _, beta, variations, qd = _qd_decision(history, qd_rows,
                                               params.qd_tau)
        warnings.warn(budget_message(variations, qd, beta, params.qd_tau),
                      RuntimeWarning, stacklevel=2)

    # The random state is read before finalize, because finalize is what a
    # backend is free to tear the handle down in.  An engine that keeps no
    # random state a survey could continue from offers no snapshot, and this is
    # the end of a run that may have taken an hour: refusing here would throw
    # the survey away over a thing it never needed.
    capture = getattr(backend, "rng_state", None)
    rng = None if capture is None else capture(handle)
    archive = backend.finalize(handle)
    shore = None
    if (bound is not None and bound.wants_shoreline
            and last_checkpoint is not None and _has_alignment(ctx)):
        try:
            shore = _closing_shoreline(archive, ctx, params, n_sites)
        except Exception as exc:
            # The survey is complete, and a report that fails must not lose
            # it.
            warnings.warn(f"the shoreline of this survey could not be "
                          f"computed: {exc!r}", RuntimeWarning, stacklevel=2)
        bound(dataclasses.replace(last_checkpoint, closing=True,
                                  shoreline=shore, logL_map=None, trees=None))
    rows = np.array(history, dtype=np.float64)
    landscape_rows = np.array(landscape, dtype=np.float64).reshape(
        -1, LANDSCAPE_WIDTH)
    moves_rows = moves_total = None
    if moves is not None:
        moves_total = np.array(prev_moves, dtype=np.int64)
        moves_rows = np.array(moves, dtype=np.int64).reshape(
            (-1,) + moves_total.shape)
    qd_array = np.array(qd_rows, dtype=np.float64).reshape(-1, 3)
    snapshot = None
    if rng is not None:
        snapshot = RunSnapshot(
            archive=archive, rng=rng, keys=np.asarray(keys),
            variations=total, cp_new=tuple(cp_new), cp_gain=tuple(cp_gain),
            gain=float(prev_gain), history=rows, landscape=landscape_rows,
            params=params, moves=moves_rows, moves_total=moves_total,
            qd=qd_array,
        )
    return ArchiveResult(
        archive=archive,
        history=rows,
        landscape=landscape_rows,
        moves=moves_rows,
        qd=qd_array,
        checkpoint_seconds=tuple(checkpoint_seconds),
        phase_seconds={"setup": started - called,
                       "illumination": illuminated - started,
                       "finish": time.perf_counter() - illuminated},
        converged=converged,
        halt_iter=halt_iter,
        params=params,
        snapshot=snapshot,
        start_state=start_state,
        shoreline=shore,
    )

ArchiveResult dataclass

A completed survey: the archive, its history, and the halt state.

history has one row per checkpoint of (iteration, n_filled, best_logL, coverage_rate, precision_rate), after a first row that records the seeded archive. The two rates are scale invariant. See :func:windowed_rates. They are NaN until a full window of checkpoints has run.

params is the shape the run actually had, which is not always the shape the caller passed: a parameter left as "auto" is settled by the engine against the memory it holds and the gene under survey. A caller that records what a survey cost records these rather than its own.

Source code in src/hifuku/driver.py
@dataclass
class ArchiveResult:
    """A completed survey: the archive, its history, and the halt state.

    ``history`` has one row per checkpoint of
    ``(iteration, n_filled, best_logL, coverage_rate, precision_rate)``, after a
    first row that records the seeded archive.  The two rates are scale
    invariant.  See :func:`windowed_rates`.  They are NaN until a full window of
    checkpoints has run.

    ``params`` is the shape the run actually had, which is not always the shape
    the caller passed: a parameter left as ``"auto"`` is settled by the engine
    against the memory it holds and the gene under survey.  A caller that
    records what a survey cost records these rather than its own.
    """

    archive: object
    history: np.ndarray
    #: One landscape row per history row; see :mod:`hifuku.landscape`.  A run
    #: resumed from a parent with no landscape holds rows for its own
    #: checkpoints only.  These rows match the last ``len(landscape)`` history
    #: rows.
    landscape: np.ndarray = None
    #: The move tally of each checkpoint, one ``(4, len(MOVE_COUNTERS))``
    #: int64 block per landscape row.  Each block is the difference of the
    #: engine's cumulative counters since the previous row, and the seed row is
    #: zero.  A run resumed from a parent with no tally holds blocks for its
    #: own checkpoints only.  None when the engine keeps no tally.
    moves: np.ndarray = None
    #: The QD-score rows: float64 of shape ``(n_rows, 3)``, with columns
    #: ``S, N, m``.  ``S`` is the exact sum of the elite log-likelihoods,
    #: ``N`` their count and ``m`` the lowest elite the survey has held.
    #: There is one row per landscape row, the seed row included.  A run
    #: resumed from a parent with no QD-score rows holds rows for its own
    #: checkpoints only.  These rows match the last ``len(qd)`` history rows.
    #: See :mod:`hifuku.halt`.
    qd: np.ndarray = None
    #: The seconds each checkpoint of this call took, one per checkpoint.  On
    #: a device engine this is device time; on the host it is the elapsed time
    #: of the chunk.  A resumed call lists its own checkpoints only.  This
    #: varies between runs, so it is a fact of a record and not its state.
    checkpoint_seconds: tuple = ()
    #: The elapsed seconds of the three phases of this call, the same on every
    #: engine: ``setup`` (the grid, the engine's preparation, the seed or the
    #: restore, and the first reads), ``illumination`` (the checkpoints) and
    #: ``finish`` (the final read of the archive and the result).  Like
    #: ``checkpoint_seconds``, these vary between runs.
    phase_seconds: dict = dataclasses.field(default_factory=dict)
    converged: bool = False
    halt_iter: int = -1
    params: object = None
    #: Everything a further call needs to carry this survey on.  See
    #: :class:`RunSnapshot`.
    snapshot: "RunSnapshot | None" = None
    #: The state digest of the snapshot this survey resumed, or empty when it
    #: seeded.  The driver computes it from the snapshot it was given, so a
    #: record takes where it started from the engine and not from its caller.
    #: See :func:`hifuku.seal.archive_state`.
    start_state: str = ""
    #: The shoreline of the final archive on the per-tree Kishino-Hasegawa
    #: scale, or None.  The driver computes it only for a monitor that names
    #: ``shoreline`` and a context that carries an alignment.  It is a report,
    #: not part of the record.  See :func:`hifuku.analysis.shoreline`.
    shoreline: object = None

windowed_rates

windowed_rates(cp_new, cp_gain, elite_range, rate_window, n_filled)

Trailing-window coverage and precision rates for the halt.

Both rates are scale invariant in the size of the domain. coverage is the growth of the filled set per checkpoint, as a fraction of the filled count. precision is the mean per-niche elite gain per checkpoint, as a fraction of the elite range.

The division by n_filled makes both rates settle toward zero whether the domain holds tens of niches or tens of thousands. One pair of thresholds therefore fits any cell size and any gate margin.

Both rates are NaN until rate_window checkpoints exist. A NaN compares False against a threshold, so a short run does not halt by accident.

Source code in src/hifuku/driver.py
def windowed_rates(cp_new, cp_gain, elite_range, rate_window, n_filled):
    """Trailing-window coverage and precision rates for the halt.

    Both rates are scale invariant in the size of the domain.  ``coverage`` is
    the growth of the filled set per checkpoint, as a fraction of the filled
    count.  ``precision`` is the mean per-niche elite gain per checkpoint, as a
    fraction of the elite range.

    The division by ``n_filled`` makes both rates settle toward zero whether the
    domain holds tens of niches or tens of thousands.  One pair of thresholds
    therefore fits any cell size and any gate margin.

    Both rates are NaN until ``rate_window`` checkpoints exist.  A NaN compares
    False against a threshold, so a short run does not halt by accident.
    """
    if len(cp_new) < rate_window or n_filled == 0:
        return float("nan"), float("nan")
    denom = rate_window * n_filled
    coverage_rate = sum(cp_new[-rate_window:]) / denom
    precision_rate = sum(cp_gain[-rate_window:]) / (denom * elite_range)
    return coverage_rate, precision_rate

survey_converged

survey_converged(coverage_rate, precision_rate, rate_coverage_eps, rate_precision_eps)

Discovery saturation: both windowed rates at or below their thresholds.

Coverage is the crisp signal. Precision uses a loose threshold because refinement inside a niche never fully stops.

Source code in src/hifuku/driver.py
def survey_converged(coverage_rate, precision_rate, rate_coverage_eps,
                     rate_precision_eps):
    """Discovery saturation: both windowed rates at or below their thresholds.

    Coverage is the crisp signal.  Precision uses a loose threshold because
    refinement inside a niche never fully stops.
    """
    return (coverage_rate <= rate_coverage_eps
            and precision_rate <= rate_precision_eps)