Skip to content

Backend Protocol

A backend starts the kernels of one device and reads its archive. The driver is written once against this protocol, so a backend that meets it runs correctly.

Two rules make the protocol work. submit_batch returns without waiting, which lets the driver queue the next chunk before it calls the monitor. A backend draws its own parent niches, because the host engine draws a fresh parent at every step and the device engine draws one per walker per pass.

The pattern follows BEAGLE, which solves the same problem in the same field. Ayres et al. (2019).

Backend

Bases: Protocol

The device interface.

A handle is opaque to the driver. A backend returns one from prepare and gets it back on every later call.

Source code in src/hifuku/backend.py
@runtime_checkable
class Backend(Protocol):
    """The device interface.

    A handle is opaque to the driver.  A backend returns one from ``prepare``
    and gets it back on every later call.
    """

    caps: Capabilities

    def fit(self, ctx: RunContext, params):
        """Settle any parameter left to the engine, and return the parameters.

        The driver calls this before it allocates anything or counts a
        checkpoint, so the shape it plans against and the shape the backend
        launches are the same numbers.

        A backend that can measure what it holds asks for ``"auto"`` in its
        capability defaults and answers here, sizing the run to the memory of
        the machine and to the gene in ``ctx``.  A backend that cannot returns
        the parameters unchanged.  Either way the returned parameters must have
        nothing left as ``"auto"``.

        A parameter a layer named as a number is not fitted.  Only the fields
        the caller left open may be set here, which is what
        ``ArchiveParams.fitted`` enforces.

        Raise ``ValueError`` when the run does not fit at any shape.
        """

    def prepare(self, ctx: RunContext, params, *, n_restored: int = 0) -> Any:
        """Allocate the run and return its handle.  This does no survey work.

        ``n_restored`` is the number of elites that ``resume`` will place.  A
        backend with a fixed archive capacity must hold these elites as well as
        the niches that the budget can reach.  A fresh run gives zero.
        """

    def seed(self, handle) -> None:
        """Place the anchor trees and the start trees in the archive.

        A seed tree is placed without the log-likelihood gate.  Raise
        ``ValueError`` when no seed tree lands on the chart grid.
        """

    def resume(self, handle, archive, rng_state, gain: float = 0.0,
               moves=None) -> None:
        """Place a saved archive and restore the random state, in place of a seed.

        This is what makes a survey continuable.  A run is determined by the
        archive it walks from and the random state it draws with, because every
        pass draws its parents out of the archive and keeps no walker between
        passes, so restoring those two continues the survey rather than starting
        a similar one.

        The archive arrives as trees, which is how it is stored, so a device
        backend places them the way ``seed`` places the start trees.  Unlike a
        seed they carry their own log-likelihoods and are placed without
        recomputing one.

        ``rng_state`` is whatever ``rng_state`` returned, and is opaque to the
        driver.  ``gain`` is the value the elite gain counter had at the
        snapshot, and the counter continues from it.  ``moves`` is the
        cumulative move tally at the snapshot, shape
        ``(4, len(MOVE_COUNTERS))``.  The tally counters continue from it.
        When it is None, the counters start at zero.

        The driver reads the statistics directly after this call.  That read
        sets the best log-likelihood the move tally compares against, so a
        resumed run tallies against the best of the restored archive.
        """

    def rng_state(self, handle) -> dict:
        """Return the random state of this handle, for a later ``resume``.

        The contents are the backend's own.  A host backend has one generator; a
        device backend has that and the per-walker state the kernel advances.
        The value must survive a round trip through storage, so it holds arrays
        and plain numbers rather than live objects.
        """

    def submit_batch(self, handle, keys, n_variations: int,
                     logl_floor: float) -> None:
        """Run ``n_variations`` variations, or queue them.

        Draw the parents from ``keys``, which holds the niche keys the driver
        knows about.  Apply ``logl_floor`` as the log-likelihood gate: a
        variation below it does not make a niche.  Place every candidate before
        this call returns control to the driver, or queue the placement on the
        same stream.  A backend that can queue work returns without waiting,
        so that the driver can call the monitor while the device works; one
        that cannot may finish the work before it returns.  Either way, the
        driver calls ``sync`` before it reads.
        """

    def sync(self) -> None:
        """Wait for the queued work to finish."""

    def read_stats(self, handle) -> Stats:
        """Read the cumulative survey statistics.  Call after ``sync``."""

    def read_keys(self, handle, since: int) -> np.ndarray:
        """Return the niche keys added at or after index ``since``.

        The driver holds the full list and asks only for the new entries, so a
        device backend copies a small slice and not the whole array.  The key
        values are opaque to the driver, which gives them back to
        ``submit_batch``.
        """

    def read_map(self, handle) -> np.ndarray:
        """Return the dense log-likelihood grid, ``NaN`` where unoccupied.

        This is one bounded transfer.  The array is a copy, never a live buffer.
        """

    def read_elites(self, handle) -> tuple:
        """Return ``(ij, logl)`` for every occupied niche, in ascending ``(i, j)``.

        ``ij`` is an int64 array of shape (n, 2) in the coordinates of the
        archive keys; ``logl`` is float64 of shape (n,).  Call after ``sync``.
        The driver builds the landscape record from these at every checkpoint.
        Both arrays are copies.  The driver uses them after it submits the next
        chunk, so a later change to the archive must not change them.
        """

    def read_trees(self, handle) -> dict:
        """Return ``{(i, j): HifukuTree}`` for every occupied niche.

        The trees are copies.  The CPU archive changes during a run, so a
        reference to a live tree would show a later state than the checkpoint.
        """

    def finalize(self, handle) -> Any:
        """Return the completed ``EliteArchive``."""

fit

fit(ctx: RunContext, params)

Settle any parameter left to the engine, and return the parameters.

The driver calls this before it allocates anything or counts a checkpoint, so the shape it plans against and the shape the backend launches are the same numbers.

A backend that can measure what it holds asks for "auto" in its capability defaults and answers here, sizing the run to the memory of the machine and to the gene in ctx. A backend that cannot returns the parameters unchanged. Either way the returned parameters must have nothing left as "auto".

A parameter a layer named as a number is not fitted. Only the fields the caller left open may be set here, which is what ArchiveParams.fitted enforces.

Raise ValueError when the run does not fit at any shape.

Source code in src/hifuku/backend.py
def fit(self, ctx: RunContext, params):
    """Settle any parameter left to the engine, and return the parameters.

    The driver calls this before it allocates anything or counts a
    checkpoint, so the shape it plans against and the shape the backend
    launches are the same numbers.

    A backend that can measure what it holds asks for ``"auto"`` in its
    capability defaults and answers here, sizing the run to the memory of
    the machine and to the gene in ``ctx``.  A backend that cannot returns
    the parameters unchanged.  Either way the returned parameters must have
    nothing left as ``"auto"``.

    A parameter a layer named as a number is not fitted.  Only the fields
    the caller left open may be set here, which is what
    ``ArchiveParams.fitted`` enforces.

    Raise ``ValueError`` when the run does not fit at any shape.
    """

prepare

prepare(ctx: RunContext, params, *, n_restored: int = 0) -> Any

Allocate the run and return its handle. This does no survey work.

n_restored is the number of elites that resume will place. A backend with a fixed archive capacity must hold these elites as well as the niches that the budget can reach. A fresh run gives zero.

Source code in src/hifuku/backend.py
def prepare(self, ctx: RunContext, params, *, n_restored: int = 0) -> Any:
    """Allocate the run and return its handle.  This does no survey work.

    ``n_restored`` is the number of elites that ``resume`` will place.  A
    backend with a fixed archive capacity must hold these elites as well as
    the niches that the budget can reach.  A fresh run gives zero.
    """

seed

seed(handle) -> None

Place the anchor trees and the start trees in the archive.

A seed tree is placed without the log-likelihood gate. Raise ValueError when no seed tree lands on the chart grid.

Source code in src/hifuku/backend.py
def seed(self, handle) -> None:
    """Place the anchor trees and the start trees in the archive.

    A seed tree is placed without the log-likelihood gate.  Raise
    ``ValueError`` when no seed tree lands on the chart grid.
    """

resume

resume(handle, archive, rng_state, gain: float = 0.0, moves=None) -> None

Place a saved archive and restore the random state, in place of a seed.

This is what makes a survey continuable. A run is determined by the archive it walks from and the random state it draws with, because every pass draws its parents out of the archive and keeps no walker between passes, so restoring those two continues the survey rather than starting a similar one.

The archive arrives as trees, which is how it is stored, so a device backend places them the way seed places the start trees. Unlike a seed they carry their own log-likelihoods and are placed without recomputing one.

rng_state is whatever rng_state returned, and is opaque to the driver. gain is the value the elite gain counter had at the snapshot, and the counter continues from it. moves is the cumulative move tally at the snapshot, shape (4, len(MOVE_COUNTERS)). The tally counters continue from it. When it is None, the counters start at zero.

The driver reads the statistics directly after this call. That read sets the best log-likelihood the move tally compares against, so a resumed run tallies against the best of the restored archive.

Source code in src/hifuku/backend.py
def resume(self, handle, archive, rng_state, gain: float = 0.0,
           moves=None) -> None:
    """Place a saved archive and restore the random state, in place of a seed.

    This is what makes a survey continuable.  A run is determined by the
    archive it walks from and the random state it draws with, because every
    pass draws its parents out of the archive and keeps no walker between
    passes, so restoring those two continues the survey rather than starting
    a similar one.

    The archive arrives as trees, which is how it is stored, so a device
    backend places them the way ``seed`` places the start trees.  Unlike a
    seed they carry their own log-likelihoods and are placed without
    recomputing one.

    ``rng_state`` is whatever ``rng_state`` returned, and is opaque to the
    driver.  ``gain`` is the value the elite gain counter had at the
    snapshot, and the counter continues from it.  ``moves`` is the
    cumulative move tally at the snapshot, shape
    ``(4, len(MOVE_COUNTERS))``.  The tally counters continue from it.
    When it is None, the counters start at zero.

    The driver reads the statistics directly after this call.  That read
    sets the best log-likelihood the move tally compares against, so a
    resumed run tallies against the best of the restored archive.
    """

rng_state

rng_state(handle) -> dict

Return the random state of this handle, for a later resume.

The contents are the backend's own. A host backend has one generator; a device backend has that and the per-walker state the kernel advances. The value must survive a round trip through storage, so it holds arrays and plain numbers rather than live objects.

Source code in src/hifuku/backend.py
def rng_state(self, handle) -> dict:
    """Return the random state of this handle, for a later ``resume``.

    The contents are the backend's own.  A host backend has one generator; a
    device backend has that and the per-walker state the kernel advances.
    The value must survive a round trip through storage, so it holds arrays
    and plain numbers rather than live objects.
    """

submit_batch

submit_batch(handle, keys, n_variations: int, logl_floor: float) -> None

Run n_variations variations, or queue them.

Draw the parents from keys, which holds the niche keys the driver knows about. Apply logl_floor as the log-likelihood gate: a variation below it does not make a niche. Place every candidate before this call returns control to the driver, or queue the placement on the same stream. A backend that can queue work returns without waiting, so that the driver can call the monitor while the device works; one that cannot may finish the work before it returns. Either way, the driver calls sync before it reads.

Source code in src/hifuku/backend.py
def submit_batch(self, handle, keys, n_variations: int,
                 logl_floor: float) -> None:
    """Run ``n_variations`` variations, or queue them.

    Draw the parents from ``keys``, which holds the niche keys the driver
    knows about.  Apply ``logl_floor`` as the log-likelihood gate: a
    variation below it does not make a niche.  Place every candidate before
    this call returns control to the driver, or queue the placement on the
    same stream.  A backend that can queue work returns without waiting,
    so that the driver can call the monitor while the device works; one
    that cannot may finish the work before it returns.  Either way, the
    driver calls ``sync`` before it reads.
    """

sync

sync() -> None

Wait for the queued work to finish.

Source code in src/hifuku/backend.py
def sync(self) -> None:
    """Wait for the queued work to finish."""

read_stats

read_stats(handle) -> Stats

Read the cumulative survey statistics. Call after sync.

Source code in src/hifuku/backend.py
def read_stats(self, handle) -> Stats:
    """Read the cumulative survey statistics.  Call after ``sync``."""

read_keys

read_keys(handle, since: int) -> np.ndarray

Return the niche keys added at or after index since.

The driver holds the full list and asks only for the new entries, so a device backend copies a small slice and not the whole array. The key values are opaque to the driver, which gives them back to submit_batch.

Source code in src/hifuku/backend.py
def read_keys(self, handle, since: int) -> np.ndarray:
    """Return the niche keys added at or after index ``since``.

    The driver holds the full list and asks only for the new entries, so a
    device backend copies a small slice and not the whole array.  The key
    values are opaque to the driver, which gives them back to
    ``submit_batch``.
    """

read_map

read_map(handle) -> np.ndarray

Return the dense log-likelihood grid, NaN where unoccupied.

This is one bounded transfer. The array is a copy, never a live buffer.

Source code in src/hifuku/backend.py
def read_map(self, handle) -> np.ndarray:
    """Return the dense log-likelihood grid, ``NaN`` where unoccupied.

    This is one bounded transfer.  The array is a copy, never a live buffer.
    """

read_elites

read_elites(handle) -> tuple

Return (ij, logl) for every occupied niche, in ascending (i, j).

ij is an int64 array of shape (n, 2) in the coordinates of the archive keys; logl is float64 of shape (n,). Call after sync. The driver builds the landscape record from these at every checkpoint. Both arrays are copies. The driver uses them after it submits the next chunk, so a later change to the archive must not change them.

Source code in src/hifuku/backend.py
def read_elites(self, handle) -> tuple:
    """Return ``(ij, logl)`` for every occupied niche, in ascending ``(i, j)``.

    ``ij`` is an int64 array of shape (n, 2) in the coordinates of the
    archive keys; ``logl`` is float64 of shape (n,).  Call after ``sync``.
    The driver builds the landscape record from these at every checkpoint.
    Both arrays are copies.  The driver uses them after it submits the next
    chunk, so a later change to the archive must not change them.
    """

read_trees

read_trees(handle) -> dict

Return {(i, j): HifukuTree} for every occupied niche.

The trees are copies. The CPU archive changes during a run, so a reference to a live tree would show a later state than the checkpoint.

Source code in src/hifuku/backend.py
def read_trees(self, handle) -> dict:
    """Return ``{(i, j): HifukuTree}`` for every occupied niche.

    The trees are copies.  The CPU archive changes during a run, so a
    reference to a live tree would show a later state than the checkpoint.
    """

finalize

finalize(handle) -> Any

Return the completed EliteArchive.

Source code in src/hifuku/backend.py
def finalize(self, handle) -> Any:
    """Return the completed ``EliteArchive``."""

Capabilities dataclass

What a backend is and what it can do.

Attributes:

Name Type Description
name str

Backend name, for example "numba-cuda" or "cpu".

unified_memory bool

True when a state read is pointer arithmetic. On a discrete device this is False and the driver gives one warning for a trees monitor. The driver never refuses the request.

defaults Mapping[str, Any]

ArchiveParams field overrides that suit this device. The mapping holds only the fields the backend wants to change, because a full parameter object cannot show which values the backend meant to set. This is the first layer of ArchiveParams.resolve.

can_read_trees bool

True when read_trees works. A backend that cannot rebuild trees sets this False, and a trees monitor then raises at setup.

precision Mapping[str, str]

The precision of each quantity the backend stores, by name: logL, z and edge_len. Each value names the narrowest float type in the arithmetic that produced the stored value, storage included, as "float32" or "float64". A survey record copies this, and a comparison between two records reads it. An empty mapping records nothing, and a comparison refuses it.

resumes_from tuple of str

The other engines whose snapshots this backend continues. A snapshot carries its engine's random state, so a backend continues only a snapshot whose state it restores exactly. The CUDA and WebGPU engines hold the same host generator and the same xoroshiro128+ word pair per walker, so each continues the other's.

Source code in src/hifuku/backend.py
@dataclass(frozen=True)
class Capabilities:
    """What a backend is and what it can do.

    Attributes
    ----------
    name : str
        Backend name, for example ``"numba-cuda"`` or ``"cpu"``.
    unified_memory : bool
        True when a state read is pointer arithmetic.  On a discrete device this
        is False and the driver gives one warning for a ``trees`` monitor.  The
        driver never refuses the request.
    defaults : Mapping[str, Any]
        ``ArchiveParams`` field overrides that suit this device.  The mapping
        holds only the fields the backend wants to change, because a full
        parameter object cannot show which values the backend meant to set.
        This is the first layer of ``ArchiveParams.resolve``.
    can_read_trees : bool
        True when ``read_trees`` works.  A backend that cannot rebuild trees
        sets this False, and a ``trees`` monitor then raises at setup.
    precision : Mapping[str, str]
        The precision of each quantity the backend stores, by name: ``logL``,
        ``z`` and ``edge_len``.  Each value names the narrowest float type in
        the arithmetic that produced the stored value, storage included, as
        ``"float32"`` or ``"float64"``.  A survey record copies this, and a
        comparison between two records reads it.  An empty mapping records
        nothing, and a comparison refuses it.
    resumes_from : tuple of str
        The other engines whose snapshots this backend continues.  A snapshot
        carries its engine's random state, so a backend continues only a
        snapshot whose state it restores exactly.  The CUDA and WebGPU engines
        hold the same host generator and the same xoroshiro128+ word pair per
        walker, so each continues the other's.
    """

    name: str
    unified_memory: bool
    defaults: Mapping[str, Any] = field(default_factory=dict)
    can_read_trees: bool = True
    precision: Mapping[str, str] = field(default_factory=dict)
    resumes_from: tuple = ()

Stats dataclass

Survey statistics read at one checkpoint.

Every value is cumulative from the start of the run. The driver takes the difference between two checkpoints to get the coverage and precision rates, which is why a backend must not reset these counters.

Attributes:

Name Type Description
n_keys int

Occupied niches.

gain float

Total elite gain, summed over every replacement of an elite.

best float

Best log-likelihood found.

elite_range float

best minus the smallest occupied log-likelihood. This normalizes the precision rate. Only the backend can measure it cheaply, because on a device it is a reduction over the fitness array.

moves ndarray or None

Cumulative int64 counters per move type, shape (4, len(MOVE_COUNTERS)); see constants.MOVE_COUNTERS. A backend that does not tally moves leaves this as None. The records of such a backend cannot be sealed. The driver records a landscape, and digest.state_digest refuses a landscape without a move tally.

Source code in src/hifuku/backend.py
@dataclass(frozen=True)
class Stats:
    """Survey statistics read at one checkpoint.

    Every value is cumulative from the start of the run.  The driver takes the
    difference between two checkpoints to get the coverage and precision rates,
    which is why a backend must not reset these counters.

    Attributes
    ----------
    n_keys : int
        Occupied niches.
    gain : float
        Total elite gain, summed over every replacement of an elite.
    best : float
        Best log-likelihood found.
    elite_range : float
        ``best`` minus the smallest occupied log-likelihood.  This normalizes
        the precision rate.  Only the backend can measure it cheaply, because on
        a device it is a reduction over the fitness array.
    moves : np.ndarray or None
        Cumulative int64 counters per move type, shape
        ``(4, len(MOVE_COUNTERS))``; see ``constants.MOVE_COUNTERS``.  A
        backend that does not tally moves leaves this as ``None``.  The
        records of such a backend cannot be sealed.  The driver records a
        landscape, and ``digest.state_digest`` refuses a landscape without
        a move tally.
    """

    n_keys: int
    gain: float
    best: float
    elite_range: float
    moves: np.ndarray = None

RunContext dataclass

The live objects that one survey runs against.

A backend gets this once, in prepare. The context holds trees, an alignment and a model, so it does not travel between hosts. A SurveyTask holds labels and indices instead, and a worker rebuilds the context from the plan.

Attributes:

Name Type Description
anchors tuple

The three anchor trees that fix the chart.

alignment, model

The alignment under survey and its substitution model.

start_trees list

Extra seed trees, normally the NJ tree of the surveyed gene.

triangle AnchorTriangle

Anchor geometry. It carries the chart metric.

taxon_table TaxonTable

The shared namespace.

Source code in src/hifuku/backend.py
@dataclass(frozen=True)
class RunContext:
    """The live objects that one survey runs against.

    A backend gets this once, in ``prepare``.  The context holds trees, an
    alignment and a model, so it does not travel between hosts.  A
    ``SurveyTask`` holds labels and indices instead, and a worker rebuilds the
    context from the plan.

    Attributes
    ----------
    anchors : tuple
        The three anchor trees that fix the chart.
    alignment, model
        The alignment under survey and its substitution model.
    start_trees : list
        Extra seed trees, normally the NJ tree of the surveyed gene.
    triangle : AnchorTriangle
        Anchor geometry.  It carries the chart metric.
    taxon_table : TaxonTable
        The shared namespace.
    """

    anchors: tuple
    alignment: Any
    model: Any
    start_trees: list
    triangle: Any
    taxon_table: Any

CpuBackend

Run the survey on the host.

A state read is a dictionary lookup, so unified_memory is True and a trees monitor costs nothing beyond building the mapping.

Source code in src/hifuku/cpu_backend.py
class CpuBackend:
    """Run the survey on the host.

    A state read is a dictionary lookup, so ``unified_memory`` is True and a
    ``trees`` monitor costs nothing beyond building the mapping.
    """

    def __init__(self):
        self.caps = Capabilities(name="cpu", unified_memory=True,
                                 defaults=dict(_CPU_DEFAULTS),
                                 can_read_trees=True,
                                 # The partials are float32 on both engines.
                                 # The host keeps float64 branch lengths, and
                                 # its metric reads them at float64.
                                 precision={"logL": "float32", "z": "float64",
                                            "edge_len": "float64"})

    def fit(self, ctx: RunContext, params):
        """Return the parameters unchanged: the host survey has one shape.

        This engine holds one walker and one move per pass, which is the
        sequential survey, and it allocates a tree at a time rather than a whole
        population.  There is nothing here for a memory measurement to size, so
        its capability defaults name numbers and no field is left open.
        """
        return params

    def prepare(self, ctx: RunContext, params, *,
                n_restored: int = 0) -> CpuHandle:
        """Allocate the archive and the generator.  This does no survey work.

        The host archive grows as it fills, so ``n_restored`` changes nothing
        here.

        Refuses a chart that cannot measure the surveyed gene.  A walker holds
        the gene's taxa for the whole survey, so an anchor sharing too few of
        them yields an undefined distance for every candidate rather than for
        some of them.  The device backend refuses the same combination in its
        own ``prepare``, so neither engine reaches the undefined path.
        """
        if not ctx.start_trees:
            raise ValueError("a survey needs at least one start tree to seed")
        require_measurable_anchors(ctx.start_trees[0], ctx.anchors)
        from hifuku.tree_io import reference_leaf_order

        archive = EliteArchive(cell=params.cell, origin=params.origin,
                               anchors=ctx.triangle,
                               taxon_table=ctx.taxon_table,
                               metric=ctx.triangle.tree_metric,
                               leaf_order=reference_leaf_order(
                                   ctx.start_trees[0]))
        return CpuHandle(ctx=ctx, params=params, archive=archive,
                         rng=np.random.default_rng(params.seed),
                         moves=np.zeros((4, len(MOVE_COUNTERS)), dtype=np.int64))

    def seed(self, handle: CpuHandle) -> None:
        """Place the start trees without the gate.

        The seeds are trees over the surveyed gene's taxa.  An anchor tree
        carries its own taxa, so its likelihood covers a different number of
        them, and a likelihood over fewer taxa is larger for that reason alone.
        The archive ranks a niche by likelihood, so an anchor seed would hold
        the niche it lands in against every candidate that covers the gene.
        The anchors fix the chart's coordinates and are not candidates on it.
        """
        for tree in handle.ctx.start_trees:
            key, elite = self._evaluate(handle, tree)
            handle.archive.place(key, elite)
        if handle.archive.n_filled == 0:
            raise ValueError("no seed tree landed on the chart grid")

    def resume(self, handle: CpuHandle, archive, rng_state,
               gain: float = 0.0, moves=None) -> None:
        """Adopt a saved archive, generator, gain counter and move tally.

        This is done in place of seeding.  With ``moves`` None, the tally
        starts at zero.

        The elites are placed with the log-likelihoods they were saved with,
        rather than evaluated again.  Re-evaluating would give the same numbers
        at more cost, and would quietly hide a snapshot written under a
        different model.
        """
        from hifuku.archive import Elite, _set_global_leaf_indices

        for key in archive.keys:
            elite = archive.elites[key]
            # Through the accessor, not the elite: an archive read back from a
            # file holds its trees as newick and parses them on first touch.
            tree = archive.tree_at(key)
            _set_global_leaf_indices(tree, handle.ctx.taxon_table)
            handle.archive.place(key, Elite(logL=elite.logL, tree=tree,
                                            z=elite.z))
        if handle.archive.n_filled == 0:
            raise ValueError("the snapshot holds no elite to resume from")
        handle.rng.bit_generator.state = rng_state["host"]
        handle.gain = float(gain)
        if moves is not None:
            handle.moves = np.array(moves, dtype=np.int64).reshape(
                handle.moves.shape)

    def rng_state(self, handle: CpuHandle) -> dict:
        """The generator state, which is all the random state a host run has.

        The engine's name travels with it, because a survey continues on the
        engine that wrote it and the state is what says which that was.
        """
        return {"engine": self.caps.name,
                "host": handle.rng.bit_generator.state}

    def submit_batch(self, handle: CpuHandle, keys, n_variations: int,
                     logl_floor: float) -> None:
        """Run ``n_variations`` variations as whole passes.

        A host archive is always current, so this backend draws its parents
        from its own key list rather than from the ``keys`` the driver holds.  A
        parent therefore comes from the niches that exist at the moment of the
        draw, which is the sampling of the sequential survey.

        This method reads ``best`` and ``top_band`` once, from
        ``handle.last_best`` at the last checkpoint.  Every pass of this call
        uses the same two values.  The device does the same.  Its tally kernel
        reads one archive-wide best and one band for a whole queued batch.
        Neither engine refreshes them pass by pass.  A parent the batch itself
        promotes to the summit is not counted as summit-adjacent until the next
        checkpoint.
        """
        params = handle.params
        n_walkers, walk_steps = params.n_walkers, params.walk_steps
        passes = max(1, n_variations // (n_walkers * walk_steps))
        best = handle.last_best
        if math.isfinite(logl_floor):
            top_band = PARENT_TIER_TOP * (best - logl_floor)
        else:
            top_band = float("inf")
        for _ in range(passes):
            self._one_pass(handle, n_walkers, walk_steps, logl_floor, best,
                           top_band)

    def _one_pass(self, handle, n_walkers, walk_steps, logl_floor, best,
                 top_band) -> None:
        """Draw the parents, walk them, then place every candidate together.

        Every move that returns a tree counts as one proposal.  A move that
        returns no tree made no proposal, and the pass does not count it.
        Each proposal gets a flag: non-finite, below the floor, or valid.
        Only a valid proposal goes to the archive.  Its outcome there adds to
        the new-niche, improved, or lost count.  The host archive has no chart
        boundary, so this pass never flags a proposal off-chart.

        A non-finite proposal never goes to the archive, also when the gate is
        off and the floor is ``-inf``.  Thus a ``-inf`` tree cannot fill an
        empty niche.  The device engine also never places such a tree.
        """
        ctx, params, archive = handle.ctx, handle.params, handle.archive
        candidates = []
        proposals = []   # (kind, flag, parent_key, parent_logL, key, cand_pos)
        for _ in range(n_walkers):
            if not archive.keys:
                break
            parent = archive.keys[int(handle.rng.integers(len(archive.keys)))]
            parent_logL = archive.elites[parent].logL
            tree = archive.elites[parent].tree
            for _ in range(walk_steps):
                child, kind = _vary(tree, ctx.taxon_table, handle.rng,
                                    params.sigma_slide, params.scale_width,
                                    params.move_thresholds)
                if child is None:
                    continue
                tree = child
                key, elite = self._evaluate(handle, child)
                if not math.isfinite(elite.logL):
                    flag, cand_pos = 3, None
                elif elite.logL < logl_floor:
                    flag, cand_pos = 2, None
                else:
                    flag, cand_pos = 0, len(candidates)
                    candidates.append((key, elite))
                proposals.append((kind, flag, parent, parent_logL, key,
                                  cand_pos))
        if handle.on_candidates is not None:
            handle.on_candidates(candidates)
        _, gain, outcomes = archive.place_batch(candidates, outcomes=True)
        handle.gain += gain
        self._tally(handle.moves, proposals, outcomes, best, top_band)

    def _tally(self, moves, proposals, outcomes, best, top_band) -> None:
        """Add each proposal's outcome to ``moves``, mirroring ``tally_moves``.

        ``moves`` is the handle's ``(4, len(MOVE_COUNTERS))`` int64 array,
        updated in place.  ``outcomes`` holds one ``(code, gain)`` pair per
        valid proposal.  The order matches the order this method appended
        them to the batch handed to ``place_batch``.
        """
        for kind, flag, parent, parent_logL, key, cand_pos in proposals:
            row = moves[kind]
            row[0] += 1   # proposals
            if flag == 2:
                row[2] += 1   # below_floor
            elif flag == 3:
                row[3] += 1   # nonfinite
            else:
                code, item_gain = outcomes[cand_pos]
                if code == 1:
                    row[4] += 1   # new_niche
                elif code == 2:
                    row[5] += 1   # improved
                    row[7] += int(math.floor(item_gain * _GAIN_SCALE + 0.5))
                else:
                    row[6] += 1   # lost
                di = key[0] - parent[0]
                dj = key[1] - parent[1]
                row[9] += di
                row[10] += dj
                row[11] += di * di
                row[12] += dj * dj
                row[13] += di * dj
            if parent_logL >= best - top_band:
                row[8] += 1   # parent_top

    def _evaluate(self, handle, tree):
        """Return the ``(key, Elite)`` of one tree on this chart."""
        ctx = handle.ctx
        lam1, lam2, z = locate_tree(tree, ctx.taxon_table, ctx.triangle)
        logL = float(log_likelihood(tree, ctx.alignment, ctx.model))
        return handle.archive.niche_of(lam1, lam2), Elite(logL=logL, tree=tree,
                                                          z=z)

    def sync(self) -> None:
        """Return at once.  Host work is finished when it returns."""

    def read_stats(self, handle: CpuHandle) -> Stats:
        """Read the cumulative survey statistics.

        Non-finite elites are skipped, as they are in ``best_logL`` and in the
        device reduction.  ``max`` keeps the first item a comparison cannot
        beat, so a NaN among the values would set the best and the range by its
        position in the dictionary rather than by its magnitude.

        ``moves`` carries one counter set per move type.  See
        ``constants.MOVE_COUNTERS``.  Its ``off_chart`` column, index 1, stays
        zero.  The host archive's ``niche_of`` is unbounded, so no proposal
        here is ever off the chart.  The device's ``off_chart`` column counts
        proposals that landed outside its allocation.  A parity comparison of
        the two tallies must leave that column out.

        This also sets ``handle.last_best``, the reference the move tally reads
        for the near-the-summit count over every pass up to the next
        checkpoint.
        """
        vals = [elite.logL for elite in handle.archive.elites.values()
                if math.isfinite(elite.logL)]
        if not vals:
            handle.last_best = float("-inf")
            return Stats(n_keys=len(handle.archive.keys), gain=handle.gain,
                         best=float("-inf"), elite_range=0.0,
                         moves=handle.moves.copy())
        best = max(vals)
        handle.last_best = best
        return Stats(n_keys=len(handle.archive.keys), gain=handle.gain,
                     best=best, elite_range=best - min(vals),
                     moves=handle.moves.copy())

    def read_elites(self, handle: CpuHandle) -> tuple:
        """The occupied niches and their log-likelihoods, in key order."""
        keys = sorted(handle.archive.keys)
        ij = np.array(keys, dtype=np.int64).reshape(-1, 2)
        logl = np.array([handle.archive.elites[k].logL for k in keys],
                        dtype=np.float64)
        return ij, logl

    def read_keys(self, handle: CpuHandle, since: int) -> np.ndarray:
        """Return the positions of the keys added at or after ``since``.

        The values index ``archive.keys``, which only grows.  They are opaque to
        the driver.
        """
        return np.arange(since, len(handle.archive.keys), dtype=np.int64)

    def read_map(self, handle: CpuHandle) -> np.ndarray:
        """Return the elite log-likelihood grid, ``NaN`` where unoccupied."""
        return np.ma.filled(handle.archive.elevation_grid().astype(np.float64),
                            np.nan)

    def read_trees(self, handle: CpuHandle) -> dict:
        """Return ``{(i, j): HifukuTree}`` for every occupied niche.

        The mapping is a new dictionary.  A move returns a new tree and never
        changes its parent, so the tree objects of a snapshot stay as they were
        at the checkpoint.
        """
        return {key: handle.archive.tree_at(key) for key in handle.archive.keys}

    def finalize(self, handle: CpuHandle) -> EliteArchive:
        """Return the completed archive.

        Its trees are already in canonical form: the archive puts them there as
        they are placed, so a walk always draws its next parent from a tree
        numbered the same way a resumed survey would find it.  That is what
        makes carrying a survey on reach the same place as never stopping.
        """
        return handle.archive

fit

fit(ctx: RunContext, params)

Return the parameters unchanged: the host survey has one shape.

This engine holds one walker and one move per pass, which is the sequential survey, and it allocates a tree at a time rather than a whole population. There is nothing here for a memory measurement to size, so its capability defaults name numbers and no field is left open.

Source code in src/hifuku/cpu_backend.py
def fit(self, ctx: RunContext, params):
    """Return the parameters unchanged: the host survey has one shape.

    This engine holds one walker and one move per pass, which is the
    sequential survey, and it allocates a tree at a time rather than a whole
    population.  There is nothing here for a memory measurement to size, so
    its capability defaults name numbers and no field is left open.
    """
    return params

prepare

prepare(ctx: RunContext, params, *, n_restored: int = 0) -> CpuHandle

Allocate the archive and the generator. This does no survey work.

The host archive grows as it fills, so n_restored changes nothing here.

Refuses a chart that cannot measure the surveyed gene. A walker holds the gene's taxa for the whole survey, so an anchor sharing too few of them yields an undefined distance for every candidate rather than for some of them. The device backend refuses the same combination in its own prepare, so neither engine reaches the undefined path.

Source code in src/hifuku/cpu_backend.py
def prepare(self, ctx: RunContext, params, *,
            n_restored: int = 0) -> CpuHandle:
    """Allocate the archive and the generator.  This does no survey work.

    The host archive grows as it fills, so ``n_restored`` changes nothing
    here.

    Refuses a chart that cannot measure the surveyed gene.  A walker holds
    the gene's taxa for the whole survey, so an anchor sharing too few of
    them yields an undefined distance for every candidate rather than for
    some of them.  The device backend refuses the same combination in its
    own ``prepare``, so neither engine reaches the undefined path.
    """
    if not ctx.start_trees:
        raise ValueError("a survey needs at least one start tree to seed")
    require_measurable_anchors(ctx.start_trees[0], ctx.anchors)
    from hifuku.tree_io import reference_leaf_order

    archive = EliteArchive(cell=params.cell, origin=params.origin,
                           anchors=ctx.triangle,
                           taxon_table=ctx.taxon_table,
                           metric=ctx.triangle.tree_metric,
                           leaf_order=reference_leaf_order(
                               ctx.start_trees[0]))
    return CpuHandle(ctx=ctx, params=params, archive=archive,
                     rng=np.random.default_rng(params.seed),
                     moves=np.zeros((4, len(MOVE_COUNTERS)), dtype=np.int64))

seed

seed(handle: CpuHandle) -> None

Place the start trees without the gate.

The seeds are trees over the surveyed gene's taxa. An anchor tree carries its own taxa, so its likelihood covers a different number of them, and a likelihood over fewer taxa is larger for that reason alone. The archive ranks a niche by likelihood, so an anchor seed would hold the niche it lands in against every candidate that covers the gene. The anchors fix the chart's coordinates and are not candidates on it.

Source code in src/hifuku/cpu_backend.py
def seed(self, handle: CpuHandle) -> None:
    """Place the start trees without the gate.

    The seeds are trees over the surveyed gene's taxa.  An anchor tree
    carries its own taxa, so its likelihood covers a different number of
    them, and a likelihood over fewer taxa is larger for that reason alone.
    The archive ranks a niche by likelihood, so an anchor seed would hold
    the niche it lands in against every candidate that covers the gene.
    The anchors fix the chart's coordinates and are not candidates on it.
    """
    for tree in handle.ctx.start_trees:
        key, elite = self._evaluate(handle, tree)
        handle.archive.place(key, elite)
    if handle.archive.n_filled == 0:
        raise ValueError("no seed tree landed on the chart grid")

resume

resume(handle: CpuHandle, archive, rng_state, gain: float = 0.0, moves=None) -> None

Adopt a saved archive, generator, gain counter and move tally.

This is done in place of seeding. With moves None, the tally starts at zero.

The elites are placed with the log-likelihoods they were saved with, rather than evaluated again. Re-evaluating would give the same numbers at more cost, and would quietly hide a snapshot written under a different model.

Source code in src/hifuku/cpu_backend.py
def resume(self, handle: CpuHandle, archive, rng_state,
           gain: float = 0.0, moves=None) -> None:
    """Adopt a saved archive, generator, gain counter and move tally.

    This is done in place of seeding.  With ``moves`` None, the tally
    starts at zero.

    The elites are placed with the log-likelihoods they were saved with,
    rather than evaluated again.  Re-evaluating would give the same numbers
    at more cost, and would quietly hide a snapshot written under a
    different model.
    """
    from hifuku.archive import Elite, _set_global_leaf_indices

    for key in archive.keys:
        elite = archive.elites[key]
        # Through the accessor, not the elite: an archive read back from a
        # file holds its trees as newick and parses them on first touch.
        tree = archive.tree_at(key)
        _set_global_leaf_indices(tree, handle.ctx.taxon_table)
        handle.archive.place(key, Elite(logL=elite.logL, tree=tree,
                                        z=elite.z))
    if handle.archive.n_filled == 0:
        raise ValueError("the snapshot holds no elite to resume from")
    handle.rng.bit_generator.state = rng_state["host"]
    handle.gain = float(gain)
    if moves is not None:
        handle.moves = np.array(moves, dtype=np.int64).reshape(
            handle.moves.shape)

rng_state

rng_state(handle: CpuHandle) -> dict

The generator state, which is all the random state a host run has.

The engine's name travels with it, because a survey continues on the engine that wrote it and the state is what says which that was.

Source code in src/hifuku/cpu_backend.py
def rng_state(self, handle: CpuHandle) -> dict:
    """The generator state, which is all the random state a host run has.

    The engine's name travels with it, because a survey continues on the
    engine that wrote it and the state is what says which that was.
    """
    return {"engine": self.caps.name,
            "host": handle.rng.bit_generator.state}

submit_batch

submit_batch(handle: CpuHandle, keys, n_variations: int, logl_floor: float) -> None

Run n_variations variations as whole passes.

A host archive is always current, so this backend draws its parents from its own key list rather than from the keys the driver holds. A parent therefore comes from the niches that exist at the moment of the draw, which is the sampling of the sequential survey.

This method reads best and top_band once, from handle.last_best at the last checkpoint. Every pass of this call uses the same two values. The device does the same. Its tally kernel reads one archive-wide best and one band for a whole queued batch. Neither engine refreshes them pass by pass. A parent the batch itself promotes to the summit is not counted as summit-adjacent until the next checkpoint.

Source code in src/hifuku/cpu_backend.py
def submit_batch(self, handle: CpuHandle, keys, n_variations: int,
                 logl_floor: float) -> None:
    """Run ``n_variations`` variations as whole passes.

    A host archive is always current, so this backend draws its parents
    from its own key list rather than from the ``keys`` the driver holds.  A
    parent therefore comes from the niches that exist at the moment of the
    draw, which is the sampling of the sequential survey.

    This method reads ``best`` and ``top_band`` once, from
    ``handle.last_best`` at the last checkpoint.  Every pass of this call
    uses the same two values.  The device does the same.  Its tally kernel
    reads one archive-wide best and one band for a whole queued batch.
    Neither engine refreshes them pass by pass.  A parent the batch itself
    promotes to the summit is not counted as summit-adjacent until the next
    checkpoint.
    """
    params = handle.params
    n_walkers, walk_steps = params.n_walkers, params.walk_steps
    passes = max(1, n_variations // (n_walkers * walk_steps))
    best = handle.last_best
    if math.isfinite(logl_floor):
        top_band = PARENT_TIER_TOP * (best - logl_floor)
    else:
        top_band = float("inf")
    for _ in range(passes):
        self._one_pass(handle, n_walkers, walk_steps, logl_floor, best,
                       top_band)

sync

sync() -> None

Return at once. Host work is finished when it returns.

Source code in src/hifuku/cpu_backend.py
def sync(self) -> None:
    """Return at once.  Host work is finished when it returns."""

read_stats

read_stats(handle: CpuHandle) -> Stats

Read the cumulative survey statistics.

Non-finite elites are skipped, as they are in best_logL and in the device reduction. max keeps the first item a comparison cannot beat, so a NaN among the values would set the best and the range by its position in the dictionary rather than by its magnitude.

moves carries one counter set per move type. See constants.MOVE_COUNTERS. Its off_chart column, index 1, stays zero. The host archive's niche_of is unbounded, so no proposal here is ever off the chart. The device's off_chart column counts proposals that landed outside its allocation. A parity comparison of the two tallies must leave that column out.

This also sets handle.last_best, the reference the move tally reads for the near-the-summit count over every pass up to the next checkpoint.

Source code in src/hifuku/cpu_backend.py
def read_stats(self, handle: CpuHandle) -> Stats:
    """Read the cumulative survey statistics.

    Non-finite elites are skipped, as they are in ``best_logL`` and in the
    device reduction.  ``max`` keeps the first item a comparison cannot
    beat, so a NaN among the values would set the best and the range by its
    position in the dictionary rather than by its magnitude.

    ``moves`` carries one counter set per move type.  See
    ``constants.MOVE_COUNTERS``.  Its ``off_chart`` column, index 1, stays
    zero.  The host archive's ``niche_of`` is unbounded, so no proposal
    here is ever off the chart.  The device's ``off_chart`` column counts
    proposals that landed outside its allocation.  A parity comparison of
    the two tallies must leave that column out.

    This also sets ``handle.last_best``, the reference the move tally reads
    for the near-the-summit count over every pass up to the next
    checkpoint.
    """
    vals = [elite.logL for elite in handle.archive.elites.values()
            if math.isfinite(elite.logL)]
    if not vals:
        handle.last_best = float("-inf")
        return Stats(n_keys=len(handle.archive.keys), gain=handle.gain,
                     best=float("-inf"), elite_range=0.0,
                     moves=handle.moves.copy())
    best = max(vals)
    handle.last_best = best
    return Stats(n_keys=len(handle.archive.keys), gain=handle.gain,
                 best=best, elite_range=best - min(vals),
                 moves=handle.moves.copy())

read_elites

read_elites(handle: CpuHandle) -> tuple

The occupied niches and their log-likelihoods, in key order.

Source code in src/hifuku/cpu_backend.py
def read_elites(self, handle: CpuHandle) -> tuple:
    """The occupied niches and their log-likelihoods, in key order."""
    keys = sorted(handle.archive.keys)
    ij = np.array(keys, dtype=np.int64).reshape(-1, 2)
    logl = np.array([handle.archive.elites[k].logL for k in keys],
                    dtype=np.float64)
    return ij, logl

read_keys

read_keys(handle: CpuHandle, since: int) -> np.ndarray

Return the positions of the keys added at or after since.

The values index archive.keys, which only grows. They are opaque to the driver.

Source code in src/hifuku/cpu_backend.py
def read_keys(self, handle: CpuHandle, since: int) -> np.ndarray:
    """Return the positions of the keys added at or after ``since``.

    The values index ``archive.keys``, which only grows.  They are opaque to
    the driver.
    """
    return np.arange(since, len(handle.archive.keys), dtype=np.int64)

read_map

read_map(handle: CpuHandle) -> np.ndarray

Return the elite log-likelihood grid, NaN where unoccupied.

Source code in src/hifuku/cpu_backend.py
def read_map(self, handle: CpuHandle) -> np.ndarray:
    """Return the elite log-likelihood grid, ``NaN`` where unoccupied."""
    return np.ma.filled(handle.archive.elevation_grid().astype(np.float64),
                        np.nan)

read_trees

read_trees(handle: CpuHandle) -> dict

Return {(i, j): HifukuTree} for every occupied niche.

The mapping is a new dictionary. A move returns a new tree and never changes its parent, so the tree objects of a snapshot stay as they were at the checkpoint.

Source code in src/hifuku/cpu_backend.py
def read_trees(self, handle: CpuHandle) -> dict:
    """Return ``{(i, j): HifukuTree}`` for every occupied niche.

    The mapping is a new dictionary.  A move returns a new tree and never
    changes its parent, so the tree objects of a snapshot stay as they were
    at the checkpoint.
    """
    return {key: handle.archive.tree_at(key) for key in handle.archive.keys}

finalize

finalize(handle: CpuHandle) -> EliteArchive

Return the completed archive.

Its trees are already in canonical form: the archive puts them there as they are placed, so a walk always draws its next parent from a tree numbered the same way a resumed survey would find it. That is what makes carrying a survey on reach the same place as never stopping.

Source code in src/hifuku/cpu_backend.py
def finalize(self, handle: CpuHandle) -> EliteArchive:
    """Return the completed archive.

    Its trees are already in canonical form: the archive puts them there as
    they are placed, so a walk always draws its next parent from a tree
    numbered the same way a resumed survey would find it.  That is what
    makes carrying a survey on reach the same place as never stopping.
    """
    return handle.archive

Device engines

A device engine keeps the walkers, the elite pool and the survey counters on the device. DeviceBackend holds the host bookkeeping that every device engine shares, and implements the protocol from a small set of engine methods. An engine subclasses it, extends DeviceHandle with its own allocations, and supplies those methods.

The pool is a list of slots, and the slots are claimed in order. The driver draws parents by niche, because a niche is a function of the run parameters and a slot is not. DeviceBackend turns each drawn niche into its slot before it calls the engine.

The host side of a device survey, shared by every device engine.

A device engine holds the walkers, the elite pool and the survey counters on the device, and runs the walk and the placement there. What remains is host bookkeeping, and it is the same for every engine: the checks on the chart and the run shape, the shared leaf order, the niche grid, the seeds, the parent draw, the reads, and the archive that a survey finishes with.

:class:DeviceBackend implements the :class:~hifuku.backend.Backend protocol from that bookkeeping and from a small set of engine methods. An engine subclasses it and supplies these methods:

  • fit sizes a run to the device;
  • _allocate builds the handle and the device state of one survey;
  • _place places host-made elites in the pool;
  • _launch queues the passes of one chunk, and sync waits for them;
  • _n_slots, _read_pool and _each_state read the pool;
  • _counters, _set_counters, _min_occupied, _dropped and _capacity read and set the survey counters;
  • _walker_rng and _set_walker_rng read and set the walker generators.

The pool is a list of slots. A slot holds one niche, as a flat index into the niche grid, with its fitness, its residual and its flat tree state. Slots are claimed in order, so the occupied slots are the first _n_slots of them.

DeviceBackend

The survey bookkeeping of a device engine.

A subclass sets caps and supplies the engine methods: fit, _allocate, _place, _launch, sync, _n_slots, _read_pool, _each_state, _counters, _set_counters, _min_occupied, _dropped, _capacity, _walker_rng and _set_walker_rng. The methods here implement the rest of the :class:~hifuku.backend.Backend protocol.

Source code in src/hifuku/device_backend.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
class DeviceBackend:
    """The survey bookkeeping of a device engine.

    A subclass sets ``caps`` and supplies the engine methods: ``fit``,
    ``_allocate``, ``_place``, ``_launch``, ``sync``, ``_n_slots``,
    ``_read_pool``, ``_each_state``, ``_counters``, ``_set_counters``,
    ``_min_occupied``, ``_dropped``, ``_capacity``, ``_walker_rng`` and
    ``_set_walker_rng``.  The methods here implement the rest of the
    :class:`~hifuku.backend.Backend` protocol.
    """

    def __init__(self, gpu_params: GpuParams | None = None):
        self.gpu_params = gpu_params or GpuParams()

    # -- setup ------------------------------------------------------------

    def _extent(self, ctx: RunContext, origin: float) -> float:
        """Half-width of the device allocation, from the chart or from the caller.

        ``"auto"`` reads it off the chart: no two trees are further apart than
        ``R = 1``, so a barycentric coordinate cannot leave ``[1 - R/h, R/h]``
        and a wider allocation holds cells no survey can occupy.  A number
        given instead is a memory bound, and a tree outside it goes to the
        sink.
        """
        from hifuku.anchor_triangle import grid_extent

        extent = self.gpu_params.extent
        if extent != AUTO:
            return float(extent)
        return float(grid_extent(ctx.triangle, origin))

    def prepare(self, ctx: RunContext, params, *,
                n_restored: int = 0) -> DeviceHandle:
        """Check the chart and the shape, settle the leaf order, and allocate.

        ``n_restored`` is the number of elites that ``resume`` will place.  The
        engine's ``_allocate`` sizes the pool to hold these elites and the
        niches that the budget can reach.
        """
        from hifuku.archive import _set_global_leaf_indices
        from hifuku.metric.branch_score import require_measurable_anchors

        r1, r2, r3 = ctx.anchors

        # The seeds are trees over the surveyed gene's taxa.  An anchor tree
        # carries its own taxa, so its likelihood covers a different number of
        # them and cannot be ranked against a candidate that covers the gene.
        # The host engine seeds the same way, and the two are compared.
        seed_trees = list(ctx.start_trees)
        if not seed_trees:
            raise ValueError("a survey needs at least one start tree to seed")

        # A walker holds the gene's taxa for the whole survey, so an anchor
        # sharing too few of them gives an undefined distance for every
        # candidate rather than for some.  The host backend refuses the same
        # combination in its own prepare, so neither engine reaches the
        # undefined path and the two agree by construction.
        require_measurable_anchors(seed_trees[0], (r1, r2, r3))

        # Whether the chart can measure the gene is a property of the question,
        # so it is settled above, before anything about the machine.  The shape
        # of the run comes next.  ``fit`` settles any part of it the caller left
        # open, and the driver calls that before this, so a shape still holding
        # the word would allocate against a word rather than a count.
        if params.needs_fitting:
            raise ValueError(
                "these parameters leave the shape of the run to the engine and "
                "have not been sized yet; call backend.fit(ctx, params) first, "
                "as the driver does, and prepare with what it returns")

        # How many passes share one parent snapshot is a property of the settled
        # shape, so this reads the fitted cadence.  A sized run holds the passes
        # per checkpoint where the tuned pair put them and never trips this; a
        # run whose shape the caller stated can.
        _warn_if_parents_go_stale(params)

        grid = device_grid(params.cell, params.origin,
                           self._extent(ctx, params.origin))

        for t in (*seed_trees, r1, r2, r3):
            _set_global_leaf_indices(t, ctx.taxon_table)

        # One shared leaf order, so the single tip-partials and leaf-index
        # arrays of the walkers are correct for every walker.  It comes from a
        # seed rather than from an anchor, because the walkers carry the gene's
        # taxa and the alignment is read in that order.
        #
        # The anchors are not relabeled into that order.  An anchor is not a
        # walking tree: it never enters a walker, and an anchor holding a taxon
        # the gene lacks has no position in the gene's leaf order at all.  Its
        # only use is the per-anchor reference table and masked leaf values,
        # which the engine builds from the anchor restricted to the taxa it
        # shares with the gene.  Those key on global taxon indices, so they
        # need no shared leaf order.
        canon = canon_leaf_names(seed_trees[0], ctx.taxon_table)
        canon_seeds = [relabel_to(t, canon, ctx.taxon_table) for t in seed_trees]

        common = dict(
            ctx=ctx, params=params, canon=list(canon), canon_seeds=canon_seeds,
            anchors=(r1, r2, r3), grid=grid,
            rng=np.random.default_rng(params.seed),
            n_nodes=canon_seeds[0].n_nodes, n_leaves=canon_seeds[0].n_leaves)
        return self._allocate(ctx, params, common, n_restored)

    def seed(self, handle: DeviceHandle) -> None:
        """Place the start trees without the gate.

        The descriptor and the log-likelihood come from the host, so the seeded
        archive matches the CPU survey exactly.  That includes which trees are
        seeded: the anchors fix the chart's coordinates and are not candidates
        on it, so neither engine places them.
        """
        from hifuku.archive import EliteArchive, locate_tree

        ctx, params = handle.ctx, handle.params
        n_off, n_side, _grid_lo, _sink = handle.grid
        n_nodes, n_leaves = handle.n_nodes, handle.n_leaves

        scratch = EliteArchive(cell=params.cell, origin=params.origin)
        niches, fits, states, zs = [], [], [], []
        for tree in handle.canon_seeds:
            lam1, lam2, z = locate_tree(tree, ctx.taxon_table, ctx.triangle)
            i, j = scratch.niche_of(lam1, lam2)
            ci, cj = i + n_off, j + n_off
            if not (0 <= ci < n_side and 0 <= cj < n_side):
                continue          # outside the allocation; extreme, so skip
            niches.append(ci * n_side + cj)
            fits.append(float(log_likelihood(tree, ctx.alignment, ctx.model)))
            zs.append(float(z))
            # A walker holds its branch lengths as float32, with zero on the
            # root, which has no branch.  The pool holds every tree in
            # canonical form, so the seed is renumbered before it goes in.
            edge = np.where(np.isfinite(tree.edge_len), tree.edge_len, 0.0)
            states.append(canonical_flat(flatten_host(
                tree.parent, tree.left_child, tree.right_child, edge, n_nodes),
                n_nodes, n_leaves))
        if not niches:
            raise ValueError("no seed tree landed on the device allocation")
        self._place(handle, np.asarray(niches, dtype=np.int32),
                    np.asarray(fits, dtype=np.float32),
                    np.asarray(states, dtype=np.float32),
                    np.asarray(zs, dtype=np.float64))

    def resume(self, handle: DeviceHandle, archive, rng_state,
               gain: float = 0.0, moves=None) -> None:
        """Place a saved archive, restore both random states and the counters.

        The counters are the gain counter and the move tally.  With ``moves``
        None, the tally starts at zero.

        The same path ``seed`` takes, over the saved elites instead of the start
        trees.  A tree already carries the four per-node arrays the device state
        is packed from, so this relabels each to the shared leaf order and packs
        it.

        The elites keep the log-likelihoods they were saved with.  Recomputing
        them would cost one Felsenstein pass per elite, and would silently
        rewrite a snapshot taken under a different model rather than showing it.
        """
        ctx = handle.ctx
        n_off, n_side, _grid_lo, _sink = handle.grid
        n_nodes = handle.n_nodes

        # An archive that a survey wrote holds every tree in that survey's leaf
        # order already, because the archive puts each tree it places into that
        # order.  Only an archive in another order is relabeled, which costs a
        # pass over every node of every tree.
        in_order = (archive.leaf_order is not None
                    and list(archive.leaf_order) == list(handle.canon))
        niches, fits, states, zs = [], [], [], []
        for key in archive.keys:
            elite = archive.elites[key]
            ci, cj = key[0] + n_off, key[1] + n_off
            if not (0 <= ci < n_side and 0 <= cj < n_side):
                continue          # outside this allocation; extreme, so skip
            # Through the accessor, not the elite: an archive read back from a
            # file holds its trees as newick and parses them on first touch.
            tree = archive.tree_at(key)
            if not in_order:
                tree = relabel_to(tree, handle.canon, ctx.taxon_table)
            niches.append(ci * n_side + cj)
            fits.append(float(elite.logL))
            zs.append(float(elite.z))
            states.append(flatten_host(tree.parent, tree.left_child,
                                       tree.right_child, tree.edge_len,
                                       n_nodes))
        if not niches:
            raise ValueError(
                "no elite of the snapshot lands on this device allocation, so "
                "there is nothing to resume from; the grid or the extent must "
                "differ from the run that wrote it")
        self._place(handle, np.asarray(niches, dtype=np.int32),
                    np.asarray(fits, dtype=np.float32),
                    np.asarray(states, dtype=np.float32),
                    np.asarray(zs, dtype=np.float64))

        # Record where each restored niche landed.  ``submit_batch`` turns the
        # niches the driver draws back into pool slots through this table, and
        # it is filled as a side effect of reading keys out, which a resumed run
        # does not do: the driver takes its key list from the snapshot instead,
        # to keep the order the parent draw indexes into.
        self.read_keys(handle, 0)

        handle.rng.bit_generator.state = rng_state["host"]
        # The per-walker states the kernel advances.  A resumed run allocates
        # its own walkers, and a walker count fitted to the device can differ
        # between runs, so the saved states are laid over as many walkers as
        # this run has and any shortfall keeps what seeding gave it.
        device = np.asarray(rng_state["device"])
        live = self._walker_rng(handle)
        n = min(len(device), len(live))
        live[:n] = device[:n]
        self._set_walker_rng(handle, live)
        # A restored elite fills an empty niche and adds no gain, and the
        # placement tallies no move, so both counters are set after it.
        self._set_counters(handle, gain, moves)

    def rng_state(self, handle: DeviceHandle) -> dict:
        """The host generator, and the per-walker states the kernel advances.

        The device states come back as an ``(M, 2)`` array of unsigned 64-bit
        words, ``s0`` then ``s1``, so that the value stores as a plain array.
        """
        return {
            "engine": self.caps.name,
            "host": handle.rng.bit_generator.state,
            "device": self._walker_rng(handle),
        }

    # -- the survey loop --------------------------------------------------

    def submit_batch(self, handle: DeviceHandle, keys, n_variations: int,
                     logl_floor: float) -> None:
        """Draw the parents of whole passes and hand them to the engine.

        The assignments for the whole chunk are drawn at once and the gate holds
        for the chunk, so no pass waits on the host.  The engine's ``_launch``
        queues the passes, or runs them and waits when it cannot queue.
        """
        params = handle.params
        M, K = params.n_walkers, params.walk_steps
        passes = max(1, n_variations // (M * K))
        if keys.size == 0:
            return

        # The driver's list holds niches.  The kernel loads a parent straight
        # out of the pool, so each drawn niche is turned into the slot it lives
        # in.  The draw stays over niches, which is what keeps the parent
        # selection a function of the run parameters.  The niches also go to
        # the engine, because the move tally measures each step's displacement
        # from its parent.
        assigns = keys[handle.rng.integers(0, keys.size, size=(passes, M))]
        slots = handle.known_slot[
            np.searchsorted(handle.known_niche, assigns)]
        # A parent within this band below the best counts as near the summit.
        # With the gate off every parent counts, so the counter reads as not
        # measured.
        if np.isfinite(logl_floor):
            top_band = PARENT_TIER_TOP * (handle.last_best - logl_floor)
        else:
            top_band = np.inf
        self._launch(handle,
                     np.ascontiguousarray(slots, dtype=np.int32),
                     np.ascontiguousarray(assigns, dtype=np.int32),
                     logl_floor, top_band)

    # -- reads ------------------------------------------------------------

    def read_stats(self, handle: DeviceHandle) -> Stats:
        """Read the survey statistics from the device counters.

        The elite range is ``best`` less the smallest occupied fitness.  A rising
        relative floor can leave early elites below it, so the smallest elite is
        reduced on the device rather than taken as ``best - floor``.

        ``moves`` is the cumulative move tally.  It differs from the host
        tally in two cases.  A valid candidate that finds no free pool slot
        counts as lost, where the host archive places it.  A prune-regraft
        step that finds no valid prune or graft leaves the tree unchanged.
        It still writes a candidate and counts as one proposal, where the
        host makes no proposal.
        """
        n_keys = self._n_slots(handle)
        gain, best, moves = self._counters(handle)
        if n_keys == 0:
            handle.last_best = float("-inf")
            return Stats(n_keys=0, gain=gain, best=float("-inf"),
                         elite_range=0.0, moves=moves)
        handle.last_best = best
        elite_range = best - self._min_occupied(handle)
        return Stats(n_keys=n_keys, gain=gain, best=best,
                     elite_range=max(elite_range, 0.0), moves=moves)

    def read_keys(self, handle: DeviceHandle, since: int) -> np.ndarray:
        """Copy the niche keys appended at or after ``since``, in niche order.

        Only the new slice moves, so a checkpoint does not copy the whole key
        array.

        The slice is sorted before it is returned.  A cell is given its pool
        slot by whichever thread wins the claim, so the pool holds the niches of
        one pass in the order the threads finished.  The driver hands this list
        back for parent selection, so an unsorted list would feed the thread
        schedule into the search and a survey would differ from run to run.  The
        set of niches a pass adds is fixed, so sorting each slice makes the whole
        key list a function of the run parameters.

        The slot each niche lives in is remembered here rather than returned.
        Slots are handed out by an atomic counter and are therefore not a
        function of the run parameters, so they must not reach the driver;
        ``submit_batch`` turns the niches it draws back into slots for the
        kernel.
        """
        n_slots = self._n_slots(handle)
        if n_slots <= since:
            return np.empty(0, dtype=np.int32)
        fresh_niche = self._read_pool(handle, "niche", since, n_slots)
        fresh_slot = np.arange(since, n_slots, dtype=np.int32)
        order = np.argsort(fresh_niche, kind="stable")
        fresh_niche, fresh_slot = fresh_niche[order], fresh_slot[order]

        merged_niche = np.concatenate([handle.known_niche, fresh_niche])
        merged_slot = np.concatenate([handle.known_slot, fresh_slot])
        keep = np.argsort(merged_niche, kind="stable")
        handle.known_niche = merged_niche[keep]
        handle.known_slot = merged_slot[keep]
        return fresh_niche

    def _occupied(self, handle: DeviceHandle, n_slots: int | None = None):
        """``(slots, niches, fitness)`` for the niches that hold an elite.

        Read from the pool, so the cost follows what the survey found and not
        the resolution it was run at.  Only the occupied slots move to the
        host.  The driver calls this at every checkpoint while the device is
        idle.  A caller that has read the slot count already passes it as
        ``n_slots``, so the device is not read for it again.
        """
        if n_slots is None:
            n_slots = self._n_slots(handle)
        if n_slots == 0:
            empty = np.empty(0, dtype=np.int32)
            return empty, empty, np.empty(0, dtype=np.float32)
        niches = self._read_pool(handle, "niche", 0, n_slots)
        fits = self._read_pool(handle, "fitness", 0, n_slots)
        live = fits > _OCCUPIED
        return (np.nonzero(live)[0].astype(np.int32), niches[live], fits[live])

    def read_map(self, handle: DeviceHandle) -> np.ndarray:
        """Return the elite log-likelihood grid, ``NaN`` where unoccupied.

        The grid spans the bounding box of the filled niches, which is the same
        window the host backend reports.
        """
        n_off, n_side, _grid_lo, _sink = handle.grid
        _slots, niches, fits = self._occupied(handle)
        if niches.size == 0:
            return np.full((1, 1), np.nan)
        rows, cols = niches // n_side, niches % n_side
        r0, r1 = int(rows.min()), int(rows.max())
        c0, c1 = int(cols.min()), int(cols.max())
        grid = np.full((r1 - r0 + 1, c1 - c0 + 1), np.nan, dtype=np.float64)
        grid[rows - r0, cols - c0] = fits
        return grid

    def read_elites(self, handle: DeviceHandle) -> tuple:
        """Copy the occupied niches and their fitness to the host."""
        n_off, n_side, _grid_lo, _sink = handle.grid
        _slots, niches, fits = self._occupied(handle)
        ij = np.stack([niches // n_side - n_off, niches % n_side - n_off],
                      axis=1).astype(np.int64)
        order = np.lexsort((ij[:, 1], ij[:, 0]))
        return ij[order], np.asarray(fits, dtype=np.float64)[order]

    def read_trees(self, handle: DeviceHandle) -> dict:
        """Rebuild ``{(i, j): HifukuTree}`` from the device archive state."""
        n_off, n_side, _grid_lo, _sink = handle.grid
        slots, niches, _fits = self._occupied(handle)
        # Every elite is written in the same leaf order, so the node names and
        # the global index of each leaf are read once rather than per tree.
        layout = leaf_layout(handle.canon, handle.n_nodes, handle.n_leaves,
                             handle.ctx.taxon_table)
        out = {}
        rows = self._each_state(handle, slots)
        for (_slot, row), flat in zip(rows, niches):
            ci, cj = int(flat) // n_side, int(flat) % n_side
            out[(ci - n_off, cj - n_off)] = tree_from_state(
                row, handle.canon, handle.n_nodes, handle.n_leaves,
                handle.ctx.taxon_table, layout)
        return out

    def finalize(self, handle: DeviceHandle):
        """Rebuild the host archive from the device fitness and state."""
        from hifuku.archive import Elite, EliteArchive

        ctx, params = handle.ctx, handle.params
        n_off, n_side, _grid_lo, _sink = handle.grid
        n_slots = self._n_slots(handle)
        slots, niches, fits = self._occupied(handle, n_slots)

        dropped = self._dropped(handle)
        capacity = self._capacity(handle)
        archive = EliteArchive(cell=params.cell, origin=params.origin,
                               anchors=ctx.triangle, taxon_table=ctx.taxon_table,
                               metric=ctx.triangle.tree_metric,
                               n_dropped=dropped, capacity=capacity,
                               # The device writes every elite in one shared
                               # leaf order, so the archive settles the internal
                               # numbering as it places them.  See
                               # hifuku.tree_io.canonical.
                               leaf_order=list(handle.canon))
        if dropped:
            warnings.warn(
                f"the elite archive filled: it holds {capacity} niches and the "
                f"survey reached {dropped} more, which were dropped.  What it "
                f"holds is still a survey of the region it covered, and the "
                f"record says how much was lost.  The capacity is what the "
                f"device had left after the walkers and the grid index, so "
                f"lower n_walkers or raise cell to grow it.",
                RuntimeWarning, stacklevel=2)
        # Read once, not once a tree: every elite shares the leaf order.
        layout = leaf_layout(handle.canon, handle.n_nodes, handle.n_leaves,
                             ctx.taxon_table)
        # The residual of each elite is the kernel's own reading of its tree,
        # the same reading that chose its niche.  That reading sums float32
        # branch lengths, so a host reading of the same tree differs in the
        # last places; ``Capabilities.precision`` records which is which.
        zs =(self._read_pool(handle, "z", 0, n_slots)[slots]
              if n_slots else np.empty(0, dtype=np.float64))

        at_edge = False
        rows = self._each_state(handle, slots)
        for (_slot, row), flat, fit, z in zip(rows, niches, fits, zs):
            ci, cj = int(flat) // n_side, int(flat) % n_side
            if ci in (0, n_side - 1) or cj in (0, n_side - 1):
                at_edge = True
            # The kernel writes every elite in canonical form, and the archive
            # puts every tree it places into that form.  The second pass
            # changes nothing here, and it keeps one route into the archive.
            tree = tree_from_state(row, handle.canon, handle.n_nodes,
                                   handle.n_leaves, ctx.taxon_table, layout)
            archive.place((ci - n_off, cj - n_off),
                          Elite(logL=float(fit), tree=tree, z=float(z)))
        if at_edge:
            warnings.warn(
                "elite archive reached the device allocation edge; the "
                "log-likelihood contour exceeds `extent` and was clipped.  "
                "Increase `extent`.", RuntimeWarning, stacklevel=2)
        return archive

    # -- the engine -------------------------------------------------------

    def fit(self, ctx: RunContext, params):
        """Size the run to this device and this gene."""
        raise NotImplementedError

    def _allocate(self, ctx: RunContext, params, common: dict,
                  n_restored: int) -> DeviceHandle:
        """Allocate the device state, and return the handle.

        ``common`` holds the fields of :class:`DeviceHandle`, which the engine
        passes to its own handle type.  The engine refuses a shape the device
        cannot hold.
        """
        raise NotImplementedError

    def _place(self, handle, niches, fits, states, zs) -> None:
        """Place host-made elites in the pool: int32 flat niches, float32
        fitness, float32 flat states and float64 residuals.  A niche equal to
        the sink is dropped, and a niche held already keeps the better one."""
        raise NotImplementedError

    def _launch(self, handle, slots, parent_niches, logl_floor: float,
                top_band: float) -> None:
        """Run one pass per row of ``slots``, an int32 ``(passes, M)`` array of
        parent pool slots: queue the passes, or run them and wait when the
        engine cannot queue.  ``parent_niches`` holds the niche of each
        parent, for the move tally."""
        raise NotImplementedError

    def sync(self) -> None:
        """Wait for the queued passes to finish."""
        raise NotImplementedError

    def _n_slots(self, handle) -> int:
        """The number of claimed pool slots."""
        raise NotImplementedError

    def _read_pool(self, handle, name: str, lo: int, hi: int) -> np.ndarray:
        """Copy slots ``[lo, hi)`` of one pool field to the host: ``"niche"``
        (int32), ``"fitness"`` (float32) or ``"z"`` (float64)."""
        raise NotImplementedError

    def _each_state(self, handle, slots):
        """Yield ``(slot, row)`` of the flat tree state, for each slot."""
        raise NotImplementedError

    def _counters(self, handle) -> tuple:
        """``(gain, best, moves)``: the gain counter, the best fitness, and
        the cumulative move tally."""
        raise NotImplementedError

    def _set_counters(self, handle, gain: float, moves) -> None:
        """Set the gain counter, and the move tally unless ``moves`` is None."""
        raise NotImplementedError

    def _min_occupied(self, handle) -> float:
        """The smallest fitness of an occupied slot."""
        raise NotImplementedError

    def _dropped(self, handle) -> int:
        """The number of niches the survey reached and the full pool dropped."""
        raise NotImplementedError

    def _capacity(self, handle) -> int:
        """The number of slots in the pool."""
        raise NotImplementedError

    def _walker_rng(self, handle) -> np.ndarray:
        """The walker generator states, as a uint64 ``(M, 2)`` array."""
        raise NotImplementedError

    def _set_walker_rng(self, handle, words) -> None:
        """Set the walker generator states from a uint64 ``(M, 2)`` array."""
        raise NotImplementedError

prepare

prepare(ctx: RunContext, params, *, n_restored: int = 0) -> DeviceHandle

Check the chart and the shape, settle the leaf order, and allocate.

n_restored is the number of elites that resume will place. The engine's _allocate sizes the pool to hold these elites and the niches that the budget can reach.

Source code in src/hifuku/device_backend.py
def prepare(self, ctx: RunContext, params, *,
            n_restored: int = 0) -> DeviceHandle:
    """Check the chart and the shape, settle the leaf order, and allocate.

    ``n_restored`` is the number of elites that ``resume`` will place.  The
    engine's ``_allocate`` sizes the pool to hold these elites and the
    niches that the budget can reach.
    """
    from hifuku.archive import _set_global_leaf_indices
    from hifuku.metric.branch_score import require_measurable_anchors

    r1, r2, r3 = ctx.anchors

    # The seeds are trees over the surveyed gene's taxa.  An anchor tree
    # carries its own taxa, so its likelihood covers a different number of
    # them and cannot be ranked against a candidate that covers the gene.
    # The host engine seeds the same way, and the two are compared.
    seed_trees = list(ctx.start_trees)
    if not seed_trees:
        raise ValueError("a survey needs at least one start tree to seed")

    # A walker holds the gene's taxa for the whole survey, so an anchor
    # sharing too few of them gives an undefined distance for every
    # candidate rather than for some.  The host backend refuses the same
    # combination in its own prepare, so neither engine reaches the
    # undefined path and the two agree by construction.
    require_measurable_anchors(seed_trees[0], (r1, r2, r3))

    # Whether the chart can measure the gene is a property of the question,
    # so it is settled above, before anything about the machine.  The shape
    # of the run comes next.  ``fit`` settles any part of it the caller left
    # open, and the driver calls that before this, so a shape still holding
    # the word would allocate against a word rather than a count.
    if params.needs_fitting:
        raise ValueError(
            "these parameters leave the shape of the run to the engine and "
            "have not been sized yet; call backend.fit(ctx, params) first, "
            "as the driver does, and prepare with what it returns")

    # How many passes share one parent snapshot is a property of the settled
    # shape, so this reads the fitted cadence.  A sized run holds the passes
    # per checkpoint where the tuned pair put them and never trips this; a
    # run whose shape the caller stated can.
    _warn_if_parents_go_stale(params)

    grid = device_grid(params.cell, params.origin,
                       self._extent(ctx, params.origin))

    for t in (*seed_trees, r1, r2, r3):
        _set_global_leaf_indices(t, ctx.taxon_table)

    # One shared leaf order, so the single tip-partials and leaf-index
    # arrays of the walkers are correct for every walker.  It comes from a
    # seed rather than from an anchor, because the walkers carry the gene's
    # taxa and the alignment is read in that order.
    #
    # The anchors are not relabeled into that order.  An anchor is not a
    # walking tree: it never enters a walker, and an anchor holding a taxon
    # the gene lacks has no position in the gene's leaf order at all.  Its
    # only use is the per-anchor reference table and masked leaf values,
    # which the engine builds from the anchor restricted to the taxa it
    # shares with the gene.  Those key on global taxon indices, so they
    # need no shared leaf order.
    canon = canon_leaf_names(seed_trees[0], ctx.taxon_table)
    canon_seeds = [relabel_to(t, canon, ctx.taxon_table) for t in seed_trees]

    common = dict(
        ctx=ctx, params=params, canon=list(canon), canon_seeds=canon_seeds,
        anchors=(r1, r2, r3), grid=grid,
        rng=np.random.default_rng(params.seed),
        n_nodes=canon_seeds[0].n_nodes, n_leaves=canon_seeds[0].n_leaves)
    return self._allocate(ctx, params, common, n_restored)

seed

seed(handle: DeviceHandle) -> None

Place the start trees without the gate.

The descriptor and the log-likelihood come from the host, so the seeded archive matches the CPU survey exactly. That includes which trees are seeded: the anchors fix the chart's coordinates and are not candidates on it, so neither engine places them.

Source code in src/hifuku/device_backend.py
def seed(self, handle: DeviceHandle) -> None:
    """Place the start trees without the gate.

    The descriptor and the log-likelihood come from the host, so the seeded
    archive matches the CPU survey exactly.  That includes which trees are
    seeded: the anchors fix the chart's coordinates and are not candidates
    on it, so neither engine places them.
    """
    from hifuku.archive import EliteArchive, locate_tree

    ctx, params = handle.ctx, handle.params
    n_off, n_side, _grid_lo, _sink = handle.grid
    n_nodes, n_leaves = handle.n_nodes, handle.n_leaves

    scratch = EliteArchive(cell=params.cell, origin=params.origin)
    niches, fits, states, zs = [], [], [], []
    for tree in handle.canon_seeds:
        lam1, lam2, z = locate_tree(tree, ctx.taxon_table, ctx.triangle)
        i, j = scratch.niche_of(lam1, lam2)
        ci, cj = i + n_off, j + n_off
        if not (0 <= ci < n_side and 0 <= cj < n_side):
            continue          # outside the allocation; extreme, so skip
        niches.append(ci * n_side + cj)
        fits.append(float(log_likelihood(tree, ctx.alignment, ctx.model)))
        zs.append(float(z))
        # A walker holds its branch lengths as float32, with zero on the
        # root, which has no branch.  The pool holds every tree in
        # canonical form, so the seed is renumbered before it goes in.
        edge = np.where(np.isfinite(tree.edge_len), tree.edge_len, 0.0)
        states.append(canonical_flat(flatten_host(
            tree.parent, tree.left_child, tree.right_child, edge, n_nodes),
            n_nodes, n_leaves))
    if not niches:
        raise ValueError("no seed tree landed on the device allocation")
    self._place(handle, np.asarray(niches, dtype=np.int32),
                np.asarray(fits, dtype=np.float32),
                np.asarray(states, dtype=np.float32),
                np.asarray(zs, dtype=np.float64))

resume

resume(handle: DeviceHandle, archive, rng_state, gain: float = 0.0, moves=None) -> None

Place a saved archive, restore both random states and the counters.

The counters are the gain counter and the move tally. With moves None, the tally starts at zero.

The same path seed takes, over the saved elites instead of the start trees. A tree already carries the four per-node arrays the device state is packed from, so this relabels each to the shared leaf order and packs it.

The elites keep the log-likelihoods they were saved with. Recomputing them would cost one Felsenstein pass per elite, and would silently rewrite a snapshot taken under a different model rather than showing it.

Source code in src/hifuku/device_backend.py
def resume(self, handle: DeviceHandle, archive, rng_state,
           gain: float = 0.0, moves=None) -> None:
    """Place a saved archive, restore both random states and the counters.

    The counters are the gain counter and the move tally.  With ``moves``
    None, the tally starts at zero.

    The same path ``seed`` takes, over the saved elites instead of the start
    trees.  A tree already carries the four per-node arrays the device state
    is packed from, so this relabels each to the shared leaf order and packs
    it.

    The elites keep the log-likelihoods they were saved with.  Recomputing
    them would cost one Felsenstein pass per elite, and would silently
    rewrite a snapshot taken under a different model rather than showing it.
    """
    ctx = handle.ctx
    n_off, n_side, _grid_lo, _sink = handle.grid
    n_nodes = handle.n_nodes

    # An archive that a survey wrote holds every tree in that survey's leaf
    # order already, because the archive puts each tree it places into that
    # order.  Only an archive in another order is relabeled, which costs a
    # pass over every node of every tree.
    in_order = (archive.leaf_order is not None
                and list(archive.leaf_order) == list(handle.canon))
    niches, fits, states, zs = [], [], [], []
    for key in archive.keys:
        elite = archive.elites[key]
        ci, cj = key[0] + n_off, key[1] + n_off
        if not (0 <= ci < n_side and 0 <= cj < n_side):
            continue          # outside this allocation; extreme, so skip
        # Through the accessor, not the elite: an archive read back from a
        # file holds its trees as newick and parses them on first touch.
        tree = archive.tree_at(key)
        if not in_order:
            tree = relabel_to(tree, handle.canon, ctx.taxon_table)
        niches.append(ci * n_side + cj)
        fits.append(float(elite.logL))
        zs.append(float(elite.z))
        states.append(flatten_host(tree.parent, tree.left_child,
                                   tree.right_child, tree.edge_len,
                                   n_nodes))
    if not niches:
        raise ValueError(
            "no elite of the snapshot lands on this device allocation, so "
            "there is nothing to resume from; the grid or the extent must "
            "differ from the run that wrote it")
    self._place(handle, np.asarray(niches, dtype=np.int32),
                np.asarray(fits, dtype=np.float32),
                np.asarray(states, dtype=np.float32),
                np.asarray(zs, dtype=np.float64))

    # Record where each restored niche landed.  ``submit_batch`` turns the
    # niches the driver draws back into pool slots through this table, and
    # it is filled as a side effect of reading keys out, which a resumed run
    # does not do: the driver takes its key list from the snapshot instead,
    # to keep the order the parent draw indexes into.
    self.read_keys(handle, 0)

    handle.rng.bit_generator.state = rng_state["host"]
    # The per-walker states the kernel advances.  A resumed run allocates
    # its own walkers, and a walker count fitted to the device can differ
    # between runs, so the saved states are laid over as many walkers as
    # this run has and any shortfall keeps what seeding gave it.
    device = np.asarray(rng_state["device"])
    live = self._walker_rng(handle)
    n = min(len(device), len(live))
    live[:n] = device[:n]
    self._set_walker_rng(handle, live)
    # A restored elite fills an empty niche and adds no gain, and the
    # placement tallies no move, so both counters are set after it.
    self._set_counters(handle, gain, moves)

rng_state

rng_state(handle: DeviceHandle) -> dict

The host generator, and the per-walker states the kernel advances.

The device states come back as an (M, 2) array of unsigned 64-bit words, s0 then s1, so that the value stores as a plain array.

Source code in src/hifuku/device_backend.py
def rng_state(self, handle: DeviceHandle) -> dict:
    """The host generator, and the per-walker states the kernel advances.

    The device states come back as an ``(M, 2)`` array of unsigned 64-bit
    words, ``s0`` then ``s1``, so that the value stores as a plain array.
    """
    return {
        "engine": self.caps.name,
        "host": handle.rng.bit_generator.state,
        "device": self._walker_rng(handle),
    }

submit_batch

submit_batch(handle: DeviceHandle, keys, n_variations: int, logl_floor: float) -> None

Draw the parents of whole passes and hand them to the engine.

The assignments for the whole chunk are drawn at once and the gate holds for the chunk, so no pass waits on the host. The engine's _launch queues the passes, or runs them and waits when it cannot queue.

Source code in src/hifuku/device_backend.py
def submit_batch(self, handle: DeviceHandle, keys, n_variations: int,
                 logl_floor: float) -> None:
    """Draw the parents of whole passes and hand them to the engine.

    The assignments for the whole chunk are drawn at once and the gate holds
    for the chunk, so no pass waits on the host.  The engine's ``_launch``
    queues the passes, or runs them and waits when it cannot queue.
    """
    params = handle.params
    M, K = params.n_walkers, params.walk_steps
    passes = max(1, n_variations // (M * K))
    if keys.size == 0:
        return

    # The driver's list holds niches.  The kernel loads a parent straight
    # out of the pool, so each drawn niche is turned into the slot it lives
    # in.  The draw stays over niches, which is what keeps the parent
    # selection a function of the run parameters.  The niches also go to
    # the engine, because the move tally measures each step's displacement
    # from its parent.
    assigns = keys[handle.rng.integers(0, keys.size, size=(passes, M))]
    slots = handle.known_slot[
        np.searchsorted(handle.known_niche, assigns)]
    # A parent within this band below the best counts as near the summit.
    # With the gate off every parent counts, so the counter reads as not
    # measured.
    if np.isfinite(logl_floor):
        top_band = PARENT_TIER_TOP * (handle.last_best - logl_floor)
    else:
        top_band = np.inf
    self._launch(handle,
                 np.ascontiguousarray(slots, dtype=np.int32),
                 np.ascontiguousarray(assigns, dtype=np.int32),
                 logl_floor, top_band)

read_stats

read_stats(handle: DeviceHandle) -> Stats

Read the survey statistics from the device counters.

The elite range is best less the smallest occupied fitness. A rising relative floor can leave early elites below it, so the smallest elite is reduced on the device rather than taken as best - floor.

moves is the cumulative move tally. It differs from the host tally in two cases. A valid candidate that finds no free pool slot counts as lost, where the host archive places it. A prune-regraft step that finds no valid prune or graft leaves the tree unchanged. It still writes a candidate and counts as one proposal, where the host makes no proposal.

Source code in src/hifuku/device_backend.py
def read_stats(self, handle: DeviceHandle) -> Stats:
    """Read the survey statistics from the device counters.

    The elite range is ``best`` less the smallest occupied fitness.  A rising
    relative floor can leave early elites below it, so the smallest elite is
    reduced on the device rather than taken as ``best - floor``.

    ``moves`` is the cumulative move tally.  It differs from the host
    tally in two cases.  A valid candidate that finds no free pool slot
    counts as lost, where the host archive places it.  A prune-regraft
    step that finds no valid prune or graft leaves the tree unchanged.
    It still writes a candidate and counts as one proposal, where the
    host makes no proposal.
    """
    n_keys = self._n_slots(handle)
    gain, best, moves = self._counters(handle)
    if n_keys == 0:
        handle.last_best = float("-inf")
        return Stats(n_keys=0, gain=gain, best=float("-inf"),
                     elite_range=0.0, moves=moves)
    handle.last_best = best
    elite_range = best - self._min_occupied(handle)
    return Stats(n_keys=n_keys, gain=gain, best=best,
                 elite_range=max(elite_range, 0.0), moves=moves)

read_keys

read_keys(handle: DeviceHandle, since: int) -> np.ndarray

Copy the niche keys appended at or after since, in niche order.

Only the new slice moves, so a checkpoint does not copy the whole key array.

The slice is sorted before it is returned. A cell is given its pool slot by whichever thread wins the claim, so the pool holds the niches of one pass in the order the threads finished. The driver hands this list back for parent selection, so an unsorted list would feed the thread schedule into the search and a survey would differ from run to run. The set of niches a pass adds is fixed, so sorting each slice makes the whole key list a function of the run parameters.

The slot each niche lives in is remembered here rather than returned. Slots are handed out by an atomic counter and are therefore not a function of the run parameters, so they must not reach the driver; submit_batch turns the niches it draws back into slots for the kernel.

Source code in src/hifuku/device_backend.py
def read_keys(self, handle: DeviceHandle, since: int) -> np.ndarray:
    """Copy the niche keys appended at or after ``since``, in niche order.

    Only the new slice moves, so a checkpoint does not copy the whole key
    array.

    The slice is sorted before it is returned.  A cell is given its pool
    slot by whichever thread wins the claim, so the pool holds the niches of
    one pass in the order the threads finished.  The driver hands this list
    back for parent selection, so an unsorted list would feed the thread
    schedule into the search and a survey would differ from run to run.  The
    set of niches a pass adds is fixed, so sorting each slice makes the whole
    key list a function of the run parameters.

    The slot each niche lives in is remembered here rather than returned.
    Slots are handed out by an atomic counter and are therefore not a
    function of the run parameters, so they must not reach the driver;
    ``submit_batch`` turns the niches it draws back into slots for the
    kernel.
    """
    n_slots = self._n_slots(handle)
    if n_slots <= since:
        return np.empty(0, dtype=np.int32)
    fresh_niche = self._read_pool(handle, "niche", since, n_slots)
    fresh_slot = np.arange(since, n_slots, dtype=np.int32)
    order = np.argsort(fresh_niche, kind="stable")
    fresh_niche, fresh_slot = fresh_niche[order], fresh_slot[order]

    merged_niche = np.concatenate([handle.known_niche, fresh_niche])
    merged_slot = np.concatenate([handle.known_slot, fresh_slot])
    keep = np.argsort(merged_niche, kind="stable")
    handle.known_niche = merged_niche[keep]
    handle.known_slot = merged_slot[keep]
    return fresh_niche

read_map

read_map(handle: DeviceHandle) -> np.ndarray

Return the elite log-likelihood grid, NaN where unoccupied.

The grid spans the bounding box of the filled niches, which is the same window the host backend reports.

Source code in src/hifuku/device_backend.py
def read_map(self, handle: DeviceHandle) -> np.ndarray:
    """Return the elite log-likelihood grid, ``NaN`` where unoccupied.

    The grid spans the bounding box of the filled niches, which is the same
    window the host backend reports.
    """
    n_off, n_side, _grid_lo, _sink = handle.grid
    _slots, niches, fits = self._occupied(handle)
    if niches.size == 0:
        return np.full((1, 1), np.nan)
    rows, cols = niches // n_side, niches % n_side
    r0, r1 = int(rows.min()), int(rows.max())
    c0, c1 = int(cols.min()), int(cols.max())
    grid = np.full((r1 - r0 + 1, c1 - c0 + 1), np.nan, dtype=np.float64)
    grid[rows - r0, cols - c0] = fits
    return grid

read_elites

read_elites(handle: DeviceHandle) -> tuple

Copy the occupied niches and their fitness to the host.

Source code in src/hifuku/device_backend.py
def read_elites(self, handle: DeviceHandle) -> tuple:
    """Copy the occupied niches and their fitness to the host."""
    n_off, n_side, _grid_lo, _sink = handle.grid
    _slots, niches, fits = self._occupied(handle)
    ij = np.stack([niches // n_side - n_off, niches % n_side - n_off],
                  axis=1).astype(np.int64)
    order = np.lexsort((ij[:, 1], ij[:, 0]))
    return ij[order], np.asarray(fits, dtype=np.float64)[order]

read_trees

read_trees(handle: DeviceHandle) -> dict

Rebuild {(i, j): HifukuTree} from the device archive state.

Source code in src/hifuku/device_backend.py
def read_trees(self, handle: DeviceHandle) -> dict:
    """Rebuild ``{(i, j): HifukuTree}`` from the device archive state."""
    n_off, n_side, _grid_lo, _sink = handle.grid
    slots, niches, _fits = self._occupied(handle)
    # Every elite is written in the same leaf order, so the node names and
    # the global index of each leaf are read once rather than per tree.
    layout = leaf_layout(handle.canon, handle.n_nodes, handle.n_leaves,
                         handle.ctx.taxon_table)
    out = {}
    rows = self._each_state(handle, slots)
    for (_slot, row), flat in zip(rows, niches):
        ci, cj = int(flat) // n_side, int(flat) % n_side
        out[(ci - n_off, cj - n_off)] = tree_from_state(
            row, handle.canon, handle.n_nodes, handle.n_leaves,
            handle.ctx.taxon_table, layout)
    return out

finalize

finalize(handle: DeviceHandle)

Rebuild the host archive from the device fitness and state.

Source code in src/hifuku/device_backend.py
def finalize(self, handle: DeviceHandle):
    """Rebuild the host archive from the device fitness and state."""
    from hifuku.archive import Elite, EliteArchive

    ctx, params = handle.ctx, handle.params
    n_off, n_side, _grid_lo, _sink = handle.grid
    n_slots = self._n_slots(handle)
    slots, niches, fits = self._occupied(handle, n_slots)

    dropped = self._dropped(handle)
    capacity = self._capacity(handle)
    archive = EliteArchive(cell=params.cell, origin=params.origin,
                           anchors=ctx.triangle, taxon_table=ctx.taxon_table,
                           metric=ctx.triangle.tree_metric,
                           n_dropped=dropped, capacity=capacity,
                           # The device writes every elite in one shared
                           # leaf order, so the archive settles the internal
                           # numbering as it places them.  See
                           # hifuku.tree_io.canonical.
                           leaf_order=list(handle.canon))
    if dropped:
        warnings.warn(
            f"the elite archive filled: it holds {capacity} niches and the "
            f"survey reached {dropped} more, which were dropped.  What it "
            f"holds is still a survey of the region it covered, and the "
            f"record says how much was lost.  The capacity is what the "
            f"device had left after the walkers and the grid index, so "
            f"lower n_walkers or raise cell to grow it.",
            RuntimeWarning, stacklevel=2)
    # Read once, not once a tree: every elite shares the leaf order.
    layout = leaf_layout(handle.canon, handle.n_nodes, handle.n_leaves,
                         ctx.taxon_table)
    # The residual of each elite is the kernel's own reading of its tree,
    # the same reading that chose its niche.  That reading sums float32
    # branch lengths, so a host reading of the same tree differs in the
    # last places; ``Capabilities.precision`` records which is which.
    zs =(self._read_pool(handle, "z", 0, n_slots)[slots]
          if n_slots else np.empty(0, dtype=np.float64))

    at_edge = False
    rows = self._each_state(handle, slots)
    for (_slot, row), flat, fit, z in zip(rows, niches, fits, zs):
        ci, cj = int(flat) // n_side, int(flat) % n_side
        if ci in (0, n_side - 1) or cj in (0, n_side - 1):
            at_edge = True
        # The kernel writes every elite in canonical form, and the archive
        # puts every tree it places into that form.  The second pass
        # changes nothing here, and it keeps one route into the archive.
        tree = tree_from_state(row, handle.canon, handle.n_nodes,
                               handle.n_leaves, ctx.taxon_table, layout)
        archive.place((ci - n_off, cj - n_off),
                      Elite(logL=float(fit), tree=tree, z=float(z)))
    if at_edge:
        warnings.warn(
            "elite archive reached the device allocation edge; the "
            "log-likelihood contour exceeds `extent` and was clipped.  "
            "Increase `extent`.", RuntimeWarning, stacklevel=2)
    return archive

fit

fit(ctx: RunContext, params)

Size the run to this device and this gene.

Source code in src/hifuku/device_backend.py
def fit(self, ctx: RunContext, params):
    """Size the run to this device and this gene."""
    raise NotImplementedError

sync

sync() -> None

Wait for the queued passes to finish.

Source code in src/hifuku/device_backend.py
def sync(self) -> None:
    """Wait for the queued passes to finish."""
    raise NotImplementedError

DeviceHandle dataclass

The host bookkeeping of one device survey.

An engine extends this with the device state it allocates.

Source code in src/hifuku/device_backend.py
@dataclass(kw_only=True)
class DeviceHandle:
    """The host bookkeeping of one device survey.

    An engine extends this with the device state it allocates.
    """

    ctx: RunContext
    params: Any
    #: The shared leaf order, and the seeds relabeled into it.
    canon: list
    canon_seeds: list
    #: The three anchor trees, each in its own leaf order.  They fix the chart's
    #: coordinates and are not seeded, but the reference split tables a seed is
    #: measured against come from them.  An anchor covers its own taxa, which
    #: need be neither the gene's nor another anchor's, so there is no one leaf
    #: order to put them in.
    anchors: tuple
    grid: tuple                      # (n_off, n_side, grid_lo, sink)
    #: The host generator, which draws the parent niches.
    rng: Any
    #: The node and leaf count of every tree in the survey.
    n_nodes: int
    n_leaves: int
    #: Every niche the driver has been given, sorted, and the pool slot each one
    #: lives in.  The driver draws parents by niche, because a niche is a
    #: function of the run parameters and a slot is not, so ``submit_batch``
    #: turns the niches it drew back into slots for the kernel.
    known_niche: Any = field(default_factory=lambda: np.empty(0, dtype=np.int32))
    known_slot: Any = field(default_factory=lambda: np.empty(0, dtype=np.int32))
    #: The best log-likelihood at the last ``read_stats``.  The move tally
    #: measures each parent against it.  The driver reads the statistics after
    #: the seed and before every submit, so it is current at each draw.
    last_best: float = float("-inf")

CudaBackend

Bases: DeviceBackend

Run the survey on a CUDA device through the shared driver.

Source code in src/hifuku/gpu_backend.py
class CudaBackend(DeviceBackend):
    """Run the survey on a CUDA device through the shared driver."""

    def __init__(self, gpu_params: GpuParams | None = None):
        super().__init__(gpu_params)
        self.caps = Capabilities(name="numba-cuda",
                                 unified_memory=_unified_memory(),
                                 defaults=dict(_GPU_DEFAULTS),
                                 can_read_trees=True,
                                 # The pool stores each fitness as float32, the
                                 # packed state holds float32 branch lengths,
                                 # and the residual is read from those lengths.
                                 precision={"logL": "float32", "z": "float32",
                                            "edge_len": "float32"},
                                 # The same host generator and the same
                                 # xoroshiro128+ word pair per walker.
                                 resumes_from=("wgsl",))
        from hifuku.timing import CudaWork
        #: Adds up how long the device worked.  ``_launch`` wraps its launches
        #: in this and nothing else, so the total is the device's own rather
        #: than the host's wait for it.  A clock given this timer reports device
        #: time per survey.
        self.device_work = CudaWork()

    # -- setup ------------------------------------------------------------

    def fit(self, ctx: RunContext, params):
        """Size the run to this device and to this gene.

        What a survey allocates has two parts.  The niche allocation is fixed:
        it holds one flat tree state per niche whatever the walker count, and at
        the default cell and extent over a few thousand taxa it reaches several
        gibibytes.  The walkers are the variable part, and one of them carries
        the Felsenstein partials twice, so its cost runs with the taxon count
        and with the alignment width.

        Across nine markers of one gene family the alignment width can span more
        than a decade, which puts the same walker count anywhere from a tenth of
        the device to several times it.  A batch therefore cannot state one
        count that suits every gene in it, and this measures each one instead.

        A count that a layer stated is not measured.  It goes to ``prepare``,
        which refuses it if the device cannot hold it, so a caller who named a
        shape is told rather than quietly given another.
        """
        if not params.needs_fitting:
            return params
        if not ctx.start_trees:
            raise ValueError("a survey needs at least one start tree to seed")

        from hifuku.walk_state import device_grid

        free_bytes, _total = cuda.current_context().get_memory_info()
        _n_off, n_side, _grid_lo, _sink = device_grid(
            params.cell, params.origin, self._extent(ctx, params.origin))
        n_niche = n_side * n_side + 1
        n_leaves = ctx.start_trees[0].n_leaves

        # Room for the elites comes out of the budget before the walkers do.
        # Both come from one pool of memory, and a gene whose walkers are
        # expensive will otherwise take all of it and leave the survey nowhere to
        # put what it finds: the widest archaeal RNA polymerase marker, 1958 taxa
        # at 867 patterns, gave its walkers 93 of 94 GiB and had room for 2787
        # elites, having found 3352 by 24576 variations of a 500000 budget.
        #
        # The reserve is taken from the budget the caller asked for rather than
        # from the count the run will make, which is that budget rounded to whole
        # passes and so depends on the walker count this call is about to settle.
        # The two differ only for a budget shorter than one checkpoint, and this
        # is a floor rather than a bound, so the difference costs nothing.
        reserve = pool_reserve_slots(
            params.n_iters + len(ctx.start_trees), n_niche)

        walkers = fit_walker_count(
            free_bytes,
            n_leaves,
            int(ctx.alignment.patterns.shape[1]),
            int(ctx.model.n_states),
            n_niche=n_niche,
            walk_steps=params.walk_steps,
            ceiling=ARCHIVE_WALK_M,
            unified=self.caps.unified_memory,
            wave=self._walker_wave(),
            reserve_bytes=reserve * archive_slot_bytes(n_leaves))
        return params.fitted(walkers)

    @staticmethod
    def _walker_wave() -> int:
        """Walkers this device holds resident at once.

        One walker is one block, and throughput rises with the walker count only
        until every walker is resident, so the count a survey is fitted to is
        rounded to this.  The figure comes from the multiprocessor count and the
        register file, both read off the device here, against the block size and
        the register count the walk kernel is pinned to.
        """
        device = cuda.get_current_device()
        return walker_wave(device.MULTIPROCESSOR_COUNT,
                           device.MAX_REGISTERS_PER_MULTIPROCESSOR,
                           device.MAX_THREADS_PER_MULTI_PROCESSOR)

    def _allocate(self, ctx: RunContext, params, common: dict,
                  n_restored: int) -> CudaHandle:
        """Allocate the chains, the device archive and the buffers.

        This compiles the walk kernel for the model's state count.  It runs no
        survey work.
        """
        from hifuku.anchor_triangle import trilateration_arrays
        from hifuku.gpu_walk import _walk_kernel_for
        from hifuku.walk_state import state_dim

        r1, r2, r3 = common["anchors"]
        canon_seeds = common["canon_seeds"]
        n_off, n_side, grid_lo, sink = common["grid"]
        model, triangle = ctx.model, ctx.triangle
        M, K = params.n_walkers, params.walk_steps

        # The niche allocation and the candidate buffers are counted alongside
        # the walkers, so this check and the fit in ``fit`` agree about what
        # this run costs.  A shape that reaches here unfitted was stated by the
        # caller, and a stated shape that does not fit is refused rather than
        # lowered.
        free_bytes, _total = cuda.current_context().get_memory_info()
        require_supported_leaf_count(
            common["n_leaves"], free_bytes, M,
            int(ctx.alignment.patterns.shape[1]), int(model.n_states),
            n_niche=n_side * n_side + 1, walk_steps=K,
            unified=self.caps.unified_memory)

        # Every walker is overwritten from the archive at the head of each pass,
        # so these starting trees fix the array shapes rather than the search.
        start = [canon_seeds[i % len(canon_seeds)] for i in range(M)]
        chains = init_chain_trees_2d(
            start,
            anchor_ref1=r1, anchor_ref2=r2, anchor_ref3=r3,
            global_seed=params.seed, alignment=ctx.alignment, model=model,
        )

        sdim = state_dim(chains.n_nodes)

        A_inv, Mbary_inv, rhs_off, P3_arr = trilateration_arrays(triangle)
        tm = triangle.tree_metric
        device_arrays = {
            "model_U": cuda.to_device(model.U.astype(np.float64)),
            "model_eigvals": cuda.to_device(model.eigvals.astype(np.float64)),
            "model_inv_sqrt_pi": cuda.to_device(model.inv_sqrt_pi.astype(np.float64)),
            "model_sqrt_pi": cuda.to_device(model.sqrt_pi.astype(np.float64)),
            "freqs": cuda.to_device(model.freqs.astype(np.float64)),
            "weights": cuda.to_device(ctx.alignment.weights.astype(np.float64)),
            "A_inv": cuda.to_device(A_inv),
            "Mbary_inv": cuda.to_device(Mbary_inv),
            "rhs_off": cuda.to_device(rhs_off),
            "P3": cuda.to_device(P3_arr),
            "metric_w": np.float64(tm.w),
        }

        n_cand = M * K
        candidates = {
            "niche": cuda.device_array(n_cand, dtype=np.int32),
            "fit": cuda.device_array(n_cand, dtype=np.float32),
            "z": cuda.device_array(n_cand, dtype=np.float64),
            "state": cuda.device_array((n_cand, sdim), dtype=np.float32),
            # Where placement resolves each candidate's cell to a pool slot.
            "slot": cuda.device_array(n_cand, dtype=np.int32),
            # The fields the move tally reads.  The walk writes the move type,
            # the validity flag and the parent fitness; placement writes the
            # outcome and the fixed-point gain.
            "move": cuda.device_array(n_cand, dtype=np.int32),
            "flag": cuda.device_array(n_cand, dtype=np.int32),
            "parent_fit": cuda.device_array(n_cand, dtype=np.float32),
            "outcome": cuda.device_array(n_cand, dtype=np.int32),
            "gain": cuda.device_array(n_cand, dtype=np.int64),
        }

        # The grid says which cells are occupied and costs four bytes a cell.
        # The pool holds the trees, so it is what a large archive costs, and it
        # is sized to what this run can reach: one niche for each seed, one for
        # each elite a resume restores, and one for each variation the budget
        # makes, since a variation writes one candidate and a candidate occupies
        # at most one niche that was empty.  A leg's budget can be far smaller
        # than what the legs before it found, so the restored elites are counted
        # on their own.  The grid and what the walkers leave bound it from above.
        n_niche = n_side * n_side + 1
        capacity = fit_archive_capacity(
            free_bytes, common["n_leaves"],
            int(ctx.alignment.patterns.shape[1]), int(model.n_states),
            n_walkers=M, n_niche=n_niche, walk_steps=K,
            n_reachable=(params.variation_budget + len(canon_seeds)
                         + n_restored),
            unified=self.caps.unified_memory)

        return CudaHandle(
            **common, chains=chains,
            archive_dev=new_device_archive(n_niche, capacity, sdim),
            device_arrays=device_arrays,
            walk_kernel=_walk_kernel_for(model.n_states),
            candidates=candidates,
        )

    # -- the engine -------------------------------------------------------

    def _place(self, handle: CudaHandle, niches, fits, states, zs) -> None:
        place_candidates(
            handle.archive_dev,
            cuda.to_device(niches), cuda.to_device(fits),
            cuda.to_device(states), cuda.to_device(zs),
            cuda.device_array(len(niches), dtype=np.int32), handle.grid[3],
        )

    def _launch(self, handle: CudaHandle, slots, parent_niches,
                logl_floor: float, top_band: float) -> None:
        """Queue one walk, one placement and one move tally per pass."""
        params = handle.params
        M, K = params.n_walkers, params.walk_steps
        d_assigns = cuda.to_device(slots)
        d_parent_niche = cuda.to_device(parent_niches)

        ct = handle.chains
        da = handle.device_arrays
        cand = handle.candidates
        n_off, n_side, _grid_lo, sink = handle.grid
        from hifuku.walk_state import EMPTY_FITNESS, bin_frame
        bin_origin, bin_offset = bin_frame(params.origin, n_off)

        # The timer wraps the launches and nothing else.  An event takes its
        # timestamp when the device reaches it, so including host work here
        # would measure the device sitting idle between launches.
        with self.device_work:
            for bi in range(slots.shape[0]):
                handle.walk_kernel[M, _CUDA_BLOCK_SIZE](
                    d_assigns[bi], handle.archive_dev["state"],
                    handle.archive_dev["fitness"],
                    ct.parent, ct.left_child, ct.right_child, ct.edge_len,
                    ct.node_order, ct.node_order_pos, ct.subtree_leaf_cnt,
                    ct.rng_state,
                    ct.d_ref_hashes_1, ct.d_ref_lengths_1,
                    ct.d_ref_hashes_2, ct.d_ref_lengths_2,
                    ct.d_ref_hashes_3, ct.d_ref_lengths_3,
                    ct.d_leaf_value_1, ct.d_leaf_value_2, ct.d_leaf_value_3,
                    ct.partials, ct.P_mat, ct.scratch, ct.scratch_log_scale,
                    ct.leaf_global_idx, ct.clade_value, ct.run_len,
                    ct.graft_below, ct.dfs_nd, ct.dfs_ph, ct.canon_of,
                    da["model_U"], da["model_eigvals"], da["model_inv_sqrt_pi"],
                    da["model_sqrt_pi"], da["freqs"], da["weights"],
                    da["A_inv"], da["Mbary_inv"], da["rhs_off"], da["P3"],
                    np.float64(ct.C1), np.float64(ct.C2), np.float64(ct.C3),
                    da["metric_w"],
                    cand["niche"], cand["fit"], cand["z"], cand["state"],
                    cand["move"], cand["flag"], cand["parent_fit"],
                    np.int32(K), np.int32(ct.n_leaves), np.int32(ct.n_nodes),
                    np.int32(ct.n_internal), np.int32(ct.n_patterns),
                    np.int32(ct.n_ref1), np.int32(ct.n_ref2),
                    np.int32(ct.n_ref3),
                    np.int32(ct.n_shared1), np.int32(ct.n_shared2),
                    np.int32(ct.n_shared3),
                    np.float64(params.sigma_slide),
                    np.float64(params.scale_width),
                    *(np.float64(t) for t in params.move_thresholds),
                    np.float64(bin_origin), np.int32(bin_offset),
                    np.float64(params.cell), np.int32(n_side),
                    np.int32(sink), np.float32(EMPTY_FITNESS),
                    np.float64(logl_floor),
                )
                place_candidates(handle.archive_dev, cand["niche"],
                                 cand["fit"], cand["state"], cand["z"],
                                 cand["slot"], sink,
                                 cand_outcome=cand["outcome"],
                                 cand_gain=cand["gain"])
                n_cand = cand["move"].size
                tally_moves[(n_cand + _CUDA_BLOCK_SIZE - 1)
                            // _CUDA_BLOCK_SIZE, _CUDA_BLOCK_SIZE](
                    cand["move"], cand["flag"], cand["outcome"], cand["gain"],
                    cand["parent_fit"], cand["niche"], d_parent_niche[bi],
                    np.int32(K), np.int32(n_side),
                    np.float64(handle.last_best), np.float64(top_band),
                    handle.archive_dev["stat_moves"])

    def sync(self) -> None:
        """Wait for the queued passes to finish."""
        cuda.synchronize()

    def _n_slots(self, handle: CudaHandle) -> int:
        return occupied_slots(handle.archive_dev)

    def _read_pool(self, handle: CudaHandle, name: str, lo: int, hi: int):
        return handle.archive_dev[name][lo:hi].copy_to_host()

    def _each_state(self, handle: CudaHandle, slots):
        return _each_state(handle.archive_dev["state"], slots)

    def _counters(self, handle: CudaHandle) -> tuple:
        dev = handle.archive_dev
        return (float(dev["stat_gain"].copy_to_host()[0]),
                float(dev["stat_best"].copy_to_host()[0]),
                dev["stat_moves"].copy_to_host())

    def _set_counters(self, handle: CudaHandle, gain: float, moves) -> None:
        dev = handle.archive_dev
        dev["stat_gain"].copy_to_device(np.array([gain], dtype=np.float64))
        if moves is not None:
            tally = dev["stat_moves"]
            tally.copy_to_device(
                np.array(moves, dtype=np.int64).reshape(tally.shape))

    def _min_occupied(self, handle: CudaHandle) -> float:
        return min_occupied_fitness(handle.archive_dev)

    def _dropped(self, handle: CudaHandle) -> int:
        return saturated(handle.archive_dev)

    def _capacity(self, handle: CudaHandle) -> int:
        return handle.archive_dev["capacity"]

    def _walker_rng(self, handle: CudaHandle) -> np.ndarray:
        device = handle.chains.rng_state.copy_to_host()
        return np.stack([device["s0"], device["s1"]], axis=1)

    def _set_walker_rng(self, handle: CudaHandle, words) -> None:
        d_state = handle.chains.rng_state
        live = np.empty(d_state.shape, dtype=d_state.dtype)
        live["s0"] = words[:, 0]
        live["s1"] = words[:, 1]
        d_state.copy_to_device(live)

fit

fit(ctx: RunContext, params)

Size the run to this device and to this gene.

What a survey allocates has two parts. The niche allocation is fixed: it holds one flat tree state per niche whatever the walker count, and at the default cell and extent over a few thousand taxa it reaches several gibibytes. The walkers are the variable part, and one of them carries the Felsenstein partials twice, so its cost runs with the taxon count and with the alignment width.

Across nine markers of one gene family the alignment width can span more than a decade, which puts the same walker count anywhere from a tenth of the device to several times it. A batch therefore cannot state one count that suits every gene in it, and this measures each one instead.

A count that a layer stated is not measured. It goes to prepare, which refuses it if the device cannot hold it, so a caller who named a shape is told rather than quietly given another.

Source code in src/hifuku/gpu_backend.py
def fit(self, ctx: RunContext, params):
    """Size the run to this device and to this gene.

    What a survey allocates has two parts.  The niche allocation is fixed:
    it holds one flat tree state per niche whatever the walker count, and at
    the default cell and extent over a few thousand taxa it reaches several
    gibibytes.  The walkers are the variable part, and one of them carries
    the Felsenstein partials twice, so its cost runs with the taxon count
    and with the alignment width.

    Across nine markers of one gene family the alignment width can span more
    than a decade, which puts the same walker count anywhere from a tenth of
    the device to several times it.  A batch therefore cannot state one
    count that suits every gene in it, and this measures each one instead.

    A count that a layer stated is not measured.  It goes to ``prepare``,
    which refuses it if the device cannot hold it, so a caller who named a
    shape is told rather than quietly given another.
    """
    if not params.needs_fitting:
        return params
    if not ctx.start_trees:
        raise ValueError("a survey needs at least one start tree to seed")

    from hifuku.walk_state import device_grid

    free_bytes, _total = cuda.current_context().get_memory_info()
    _n_off, n_side, _grid_lo, _sink = device_grid(
        params.cell, params.origin, self._extent(ctx, params.origin))
    n_niche = n_side * n_side + 1
    n_leaves = ctx.start_trees[0].n_leaves

    # Room for the elites comes out of the budget before the walkers do.
    # Both come from one pool of memory, and a gene whose walkers are
    # expensive will otherwise take all of it and leave the survey nowhere to
    # put what it finds: the widest archaeal RNA polymerase marker, 1958 taxa
    # at 867 patterns, gave its walkers 93 of 94 GiB and had room for 2787
    # elites, having found 3352 by 24576 variations of a 500000 budget.
    #
    # The reserve is taken from the budget the caller asked for rather than
    # from the count the run will make, which is that budget rounded to whole
    # passes and so depends on the walker count this call is about to settle.
    # The two differ only for a budget shorter than one checkpoint, and this
    # is a floor rather than a bound, so the difference costs nothing.
    reserve = pool_reserve_slots(
        params.n_iters + len(ctx.start_trees), n_niche)

    walkers = fit_walker_count(
        free_bytes,
        n_leaves,
        int(ctx.alignment.patterns.shape[1]),
        int(ctx.model.n_states),
        n_niche=n_niche,
        walk_steps=params.walk_steps,
        ceiling=ARCHIVE_WALK_M,
        unified=self.caps.unified_memory,
        wave=self._walker_wave(),
        reserve_bytes=reserve * archive_slot_bytes(n_leaves))
    return params.fitted(walkers)

sync

sync() -> None

Wait for the queued passes to finish.

Source code in src/hifuku/gpu_backend.py
def sync(self) -> None:
    """Wait for the queued passes to finish."""
    cuda.synchronize()

WgslBackend

Bases: DeviceBackend

Run the survey on a WebGPU device through the shared driver.

Source code in src/hifuku/wgsl/backend.py
class WgslBackend(DeviceBackend):
    """Run the survey on a WebGPU device through the shared driver."""

    def __init__(self, gpu_params: GpuParams | None = None):
        super().__init__(gpu_params)
        self.caps = Capabilities(name="wgsl",
                                 # Every read maps a staging buffer, whatever
                                 # the adapter, so a read is never free.
                                 unified_memory=False,
                                 defaults=dict(_DEFAULTS),
                                 can_read_trees=True,
                                 # The pool stores each fitness and each branch
                                 # length as float32, and each residual as a
                                 # float-float pair.
                                 precision={"logL": "float32", "z": "float-float",
                                            "edge_len": "float32"},
                                 # The same host generator and the same
                                 # xoroshiro128+ word pair per walker.
                                 resumes_from=("numba-cuda",))

    # -- setup ------------------------------------------------------------

    def fit(self, ctx: RunContext, params):
        """Size the walker count to the device's bindings.

        WebGPU reports no device memory.  The count starts at the largest
        whose per-walker buffers stay within one storage binding and whose
        walkers stay within one dispatch dimension, capped at
        ``ARCHIVE_WALK_M``.  The walkers' largest buffers are then allocated,
        and the count is halved on each out-of-memory error until they
        allocate.  A count the caller stated is not measured; ``prepare``
        refuses it if the device cannot hold it.
        """
        if not params.needs_fitting:
            return params
        if not ctx.start_trees:
            raise ValueError("a survey needs at least one start tree to seed")
        import wgpu

        limit = storage_limit()
        sizes = _walker_bytes(ctx, params.walk_steps)
        per_walker = max(sizes.values())
        walkers = min(ARCHIVE_WALK_M, workgroup_limit(), limit // per_walker)
        if walkers < 1:
            raise ValueError(f"one walker needs {per_walker} bytes in one binding, and "
                             f"this device's bindings hold {limit}")
        # WebGPU reports no device memory, so the count is found by allocating
        # the walkers' largest buffers, halving it on each out-of-memory error.
        while True:
            try:
                _probe(walkers, sizes)
                break
            except wgpu.GPUOutOfMemoryError:
                if walkers == 1:
                    raise ValueError(
                        f"one walker's buffers ({sum(sizes.values())} bytes) do not "
                        f"allocate on this device") from None
                walkers //= 2
        return params.fitted(int(walkers))

    def _allocate(self, ctx: RunContext, params, common: dict,
                  n_restored: int) -> WgslHandle:
        """Make the elite pool and the walkers, and seed the walker generators."""
        from hifuku.walk_state import state_dim
        from hifuku.wgsl.archive import WgslArchive
        from hifuku.wgsl.walk import WgslWalk
        from hifuku.wgsl.xoroshiro import initial_states

        M, K = params.n_walkers, params.walk_steps
        limit = storage_limit()
        for what, nbytes in _walker_bytes(ctx, K).items():
            if M * nbytes > limit:
                raise ValueError(
                    f"the {what} of {M} walkers need {M * nbytes} bytes, and one "
                    f"storage binding of this device holds {limit}.  Lower n_walkers.")
        n_off, n_side, _grid_lo, sink = common["grid"]
        sdim = state_dim(common["n_nodes"])
        n_seeds = len(common["canon_seeds"])
        # The pool holds what the run can reach: each seed, each restored elite
        # and one niche per variation, within what one binding holds.
        reachable = params.variation_budget + n_seeds + n_restored
        capacity = min(reachable, limit // (4 * sdim))
        if capacity < n_seeds + n_restored:
            raise ValueError(f"the pool would hold {capacity} trees, fewer than the "
                             f"{n_seeds + n_restored} seeds and restored elites; one "
                             f"storage binding of this device holds {limit} bytes")
        # A seed or resume placement is one batch, as on the CUDA engine, so the
        # candidate buffer holds the largest of the three.  WebGPU reports no
        # device memory, so a pool the device cannot hold is halved until it
        # allocates, but never below the trees it must place.
        import wgpu

        needed = n_seeds + n_restored
        while True:
            try:
                archive = WgslArchive(n_niche=n_side * n_side + 1, capacity=capacity,
                                      state_dim=sdim,
                                      n_cand=max(M * K, n_seeds, n_restored))
                break
            except wgpu.GPUOutOfMemoryError:
                if capacity <= needed:
                    raise ValueError(
                        f"a pool of {capacity} trees of {sdim} words, the seeds and "
                        f"restored elites, does not allocate on this device") from None
                capacity = max(needed, capacity // 2)
        r1, r2, r3 = common["anchors"]
        try:
            walk = WgslWalk(archive, common["canon_seeds"][0], (r1, r2, r3),
                            ctx.triangle, ctx.alignment, ctx.model, params, M, K,
                            params.cell, params.origin, self._extent(ctx, params.origin),
                            arithmetic=archive.arithmetic)
        except wgpu.GPUOutOfMemoryError:
            archive.resident.release()
            raise ValueError(
                f"the buffers of {M} walkers do not allocate on this device beside a "
                f"pool of {capacity} trees.  Lower n_walkers, or leave it to the "
                f"engine.") from None
        walk.set_rng(initial_states(M, params.seed))
        return WgslHandle(**common, archive=archive, walk=walk)

    # -- the engine -------------------------------------------------------

    def _place(self, handle: WgslHandle, niches, fits, states, zs) -> None:
        handle.archive.place_candidates(niches, fits, states, zs, sink=handle.grid[3])

    def _launch(self, handle: WgslHandle, slots, parent_niches, logl_floor: float,
                top_band: float) -> None:
        """Run each pass of the chunk as one submission, and wait for it.

        A pass is about ten dispatches per step.  One submission per pass,
        not per chunk, keeps each submission short, because a browser or the
        Metal and Direct3D 12 drivers stop a GPU task that runs too long.
        The parents of the chunk were drawn from slots claimed before it, so
        the count of claimed slots that checks them is read once.
        """
        walk = handle.walk
        claimed = handle.archive.occupied_slots()
        for b in range(slots.shape[0]):
            handle.archive.resident.run(walk.pass_steps(
                slots[b], parent_niches[b], logl_floor, handle.last_best, top_band,
                claimed=claimed))

    def sync(self) -> None:
        """Nothing to wait for: each submission waits for its work."""

    def _n_slots(self, handle: WgslHandle) -> int:
        return handle.archive.occupied_slots()

    def _read_pool(self, handle: WgslHandle, name: str, lo: int, hi: int):
        return handle.archive.read(name, lo, hi)

    def _each_state(self, handle: WgslHandle, slots):
        """Yield ``(slot, row)`` in blocks of contiguous slots."""
        slots = np.asarray(slots, dtype=np.int64)
        for start in range(0, slots.size, _READBACK_SLOTS):
            chunk = slots[start:start + _READBACK_SLOTS]
            lo, hi = int(chunk[0]), int(chunk[-1]) + 1
            if hi - lo > 4 * chunk.size:
                for slot in chunk:            # scattered; the span is not worth it
                    yield int(slot), handle.archive.read_state(int(slot))
                continue
            rows = handle.archive.read_states(lo, hi)
            for slot in chunk:
                yield int(slot), rows[int(slot) - lo]

    def _counters(self, handle: WgslHandle) -> tuple:
        return handle.archive.counters()

    def _set_counters(self, handle: WgslHandle, gain: float, moves) -> None:
        handle.archive.set_counters(gain, moves)

    def _min_occupied(self, handle: WgslHandle) -> float:
        return handle.archive.min_occupied_fitness()

    def _dropped(self, handle: WgslHandle) -> int:
        return handle.archive.saturated()

    def _capacity(self, handle: WgslHandle) -> int:
        return handle.archive.capacity

    def _walker_rng(self, handle: WgslHandle) -> np.ndarray:
        return handle.walk.rng()

    def _set_walker_rng(self, handle: WgslHandle, words) -> None:
        handle.walk.set_rng(words)

fit

fit(ctx: RunContext, params)

Size the walker count to the device's bindings.

WebGPU reports no device memory. The count starts at the largest whose per-walker buffers stay within one storage binding and whose walkers stay within one dispatch dimension, capped at ARCHIVE_WALK_M. The walkers' largest buffers are then allocated, and the count is halved on each out-of-memory error until they allocate. A count the caller stated is not measured; prepare refuses it if the device cannot hold it.

Source code in src/hifuku/wgsl/backend.py
def fit(self, ctx: RunContext, params):
    """Size the walker count to the device's bindings.

    WebGPU reports no device memory.  The count starts at the largest
    whose per-walker buffers stay within one storage binding and whose
    walkers stay within one dispatch dimension, capped at
    ``ARCHIVE_WALK_M``.  The walkers' largest buffers are then allocated,
    and the count is halved on each out-of-memory error until they
    allocate.  A count the caller stated is not measured; ``prepare``
    refuses it if the device cannot hold it.
    """
    if not params.needs_fitting:
        return params
    if not ctx.start_trees:
        raise ValueError("a survey needs at least one start tree to seed")
    import wgpu

    limit = storage_limit()
    sizes = _walker_bytes(ctx, params.walk_steps)
    per_walker = max(sizes.values())
    walkers = min(ARCHIVE_WALK_M, workgroup_limit(), limit // per_walker)
    if walkers < 1:
        raise ValueError(f"one walker needs {per_walker} bytes in one binding, and "
                         f"this device's bindings hold {limit}")
    # WebGPU reports no device memory, so the count is found by allocating
    # the walkers' largest buffers, halving it on each out-of-memory error.
    while True:
        try:
            _probe(walkers, sizes)
            break
        except wgpu.GPUOutOfMemoryError:
            if walkers == 1:
                raise ValueError(
                    f"one walker's buffers ({sum(sizes.values())} bytes) do not "
                    f"allocate on this device") from None
            walkers //= 2
    return params.fitted(int(walkers))

sync

sync() -> None

Nothing to wait for: each submission waits for its work.

Source code in src/hifuku/wgsl/backend.py
def sync(self) -> None:
    """Nothing to wait for: each submission waits for its work."""

The CUDA and WebGPU engines hold the same random state: the host generator that draws parents, and one xoroshiro128+ word pair per walker. Each names the other in Capabilities.resumes_from, so a snapshot that either one writes continues on the other. A host snapshot does not continue on a device, and a device snapshot does not continue on the host.

Walk state

hifuku.walk_state packs a tree into the flat row that a walker and a pool slot hold, and lays out the niche grid. It loads no CUDA module, so every engine uses it.

walk_state

The flat form of a walker's tree, and the niche grid, on the host.

A device survey holds each tree as a flat float32 row: the parent, both children and the edge length of every node, with the root at node n_nodes - 1. Every walker and every elite of one survey shares one leaf order. This module packs and unpacks that row, puts it in canonical numbering, relabels trees into the shared leaf order, and lays out the niche grid. It imports no device code, so every engine shares it.

state_dim

state_dim(n_nodes: int) -> int

Length of the flat float32 state vector for a tree with n_nodes nodes.

The vector holds the parent, both children and the edge length of every node. It is the form a tree takes in an archive niche and in a candidate buffer, so it also fixes what those cost.

Source code in src/hifuku/walk_state.py
def state_dim(n_nodes: int) -> int:
    """Length of the flat float32 state vector for a tree with ``n_nodes`` nodes.

    The vector holds the parent, both children and the edge length of every
    node. It is the form a tree takes in an archive niche and in a candidate
    buffer, so it also fixes what those cost.
    """
    return 4 * n_nodes

flatten_host

flatten_host(parent, left_child, right_child, edge_len, n_nodes: int) -> np.ndarray

Pack one chain's host arrays into the flat float32 state vector.

Source code in src/hifuku/walk_state.py
def flatten_host(parent, left_child, right_child, edge_len,
                 n_nodes: int) -> np.ndarray:
    """Pack one chain's host arrays into the flat float32 state vector."""
    out = np.empty(state_dim(n_nodes), dtype=np.float32)
    out[0 * n_nodes:1 * n_nodes] = parent
    out[1 * n_nodes:2 * n_nodes] = left_child
    out[2 * n_nodes:3 * n_nodes] = right_child
    out[3 * n_nodes:4 * n_nodes] = edge_len
    return out

canonical_flat

canonical_flat(state, n_nodes: int, n_leaves: int) -> np.ndarray

Return a flat state renumbered into canonical form.

This is the form of :func:hifuku.tree_io.canonical, for a tree whose leaves are already in the shared leaf order. The kernel writes every candidate in this form. A tree that enters the pool by another route, such as a seed, goes through this function, so every tree in the pool has one numbering.

Source code in src/hifuku/walk_state.py
def canonical_flat(state, n_nodes: int, n_leaves: int) -> np.ndarray:
    """Return a flat state renumbered into canonical form.

    This is the form of :func:`hifuku.tree_io.canonical`, for a tree whose
    leaves are already in the shared leaf order.  The kernel writes every
    candidate in this form.  A tree that enters the pool by another route, such
    as a seed, goes through this function, so every tree in the pool has one
    numbering.
    """
    from hifuku.tree_io import _canonical_permutation

    parent = np.rint(state[0 * n_nodes:1 * n_nodes]).astype(np.int64)
    lc = np.rint(state[1 * n_nodes:2 * n_nodes]).astype(np.int64)
    rc = np.rint(state[2 * n_nodes:3 * n_nodes]).astype(np.int64)
    root = int(np.flatnonzero(parent < 0)[0])
    new_of = _canonical_permutation(lc, rc, root, n_leaves, n_nodes)
    out = np.empty_like(state)
    for block, links in enumerate((parent, lc, rc)):
        out[block * n_nodes + new_of] = np.where(
            links >= 0, new_of[np.maximum(links, 0)], -1)
    out[3 * n_nodes + new_of] = state[3 * n_nodes:4 * n_nodes]
    return out

canon_leaf_names

canon_leaf_names(tree, taxon_table=None)

The shared leaf order for a survey.

One definition, in :func:~hifuku.tree_io.reference_leaf_order, because both engines have to number their trees alike for the host survey to be a reference for the device survey. taxon_table is accepted and unused, so that a caller that has one need not know which order is used.

Source code in src/hifuku/walk_state.py
def canon_leaf_names(tree, taxon_table=None):
    """The shared leaf order for a survey.

    One definition, in :func:`~hifuku.tree_io.reference_leaf_order`, because
    both engines have to number their trees alike for the host survey to be a
    reference for the device survey.  ``taxon_table`` is accepted and unused,
    so that a caller that has one need not know which order is used.
    """
    from hifuku.tree_io import reference_leaf_order

    return reference_leaf_order(tree)

relabel_to

relabel_to(tree, canon_names, taxon_table)

Return the same tree with leaf position i bound to canon_names[i].

A pure re-indexing of the leaf nodes: the topology, the taxa, the branch lengths, and the label-based tree distance are unchanged. Every tree in a device survey is relabeled to one shared order, because the walkers share one tip-partials array and one leaf-global-index array, so leaf position must mean the same taxon in every walker.

Source code in src/hifuku/walk_state.py
def relabel_to(tree, canon_names, taxon_table):
    """Return the same tree with leaf position ``i`` bound to ``canon_names[i]``.

    A pure re-indexing of the leaf nodes: the topology, the taxa, the branch
    lengths, and the label-based tree distance are unchanged.  Every tree in a
    device survey is relabeled to one shared order, because the walkers share
    one tip-partials array and one leaf-global-index array, so leaf position
    must mean the same taxon in every walker.
    """
    n_nodes, n_leaves = tree.n_nodes, tree.n_leaves
    canon_pos = {nm: i for i, nm in enumerate(canon_names)}
    new_of = np.arange(n_nodes, dtype=np.int64)   # internals and root unchanged
    for j in range(n_leaves):
        new_of[j] = canon_pos[tree.names[j]]
    parent = np.full(n_nodes, -1, dtype=np.int32)
    lc = np.full(n_nodes, -1, dtype=np.int32)
    rc = np.full(n_nodes, -1, dtype=np.int32)
    edge = np.empty(n_nodes, dtype=np.float64)
    names = [""] * n_nodes
    for old in range(n_nodes):
        ni = int(new_of[old])
        p = int(tree.parent[old])
        parent[ni] = int(new_of[p]) if p >= 0 else -1
        cl = int(tree.left_child[old])
        lc[ni] = int(new_of[cl]) if cl >= 0 else -1
        cr = int(tree.right_child[old])
        rc[ni] = int(new_of[cr]) if cr >= 0 else -1
        edge[ni] = float(tree.edge_len[old])
        names[ni] = tree.names[old]
    glidx = np.full(n_nodes, -1, dtype=np.int32)
    for i in range(n_leaves):
        glidx[i] = taxon_table.index_of(names[i])
    out = HifukuTree(
        parent=parent, left_child=lc, right_child=rc, edge_len=edge,
        names=names, n_nodes=n_nodes, n_leaves=n_leaves, root=int(new_of[tree.root]),
    )
    out.global_leaf_indices = glidx
    out.node_order = out.compute_node_order()
    return out

leaf_layout

leaf_layout(leaf_names, n_nodes, n_leaves, taxon_table)

(names, global_indices) that every tree of one leaf order shares.

A walker carries the gene's taxa for the whole survey and every elite it leaves behind is written in the same leaf order, so the node names and the global index of each leaf are the same for all of them. Reading them once saves the taxon table a lookup per leaf per tree, which over a full archive is millions of them.

Source code in src/hifuku/walk_state.py
def leaf_layout(leaf_names, n_nodes, n_leaves, taxon_table):
    """``(names, global_indices)`` that every tree of one leaf order shares.

    A walker carries the gene's taxa for the whole survey and every elite it
    leaves behind is written in the same leaf order, so the node names and the
    global index of each leaf are the same for all of them.  Reading them once
    saves the taxon table a lookup per leaf per tree, which over a full archive
    is millions of them.
    """
    names = [leaf_names[i] if i < n_leaves else "" for i in range(n_nodes)]
    glidx = np.full(n_nodes, -1, dtype=np.int32)
    for i in range(n_leaves):
        glidx[i] = taxon_table.index_of(names[i])
    return names, glidx

tree_from_state

tree_from_state(state, leaf_names, n_nodes, n_leaves, taxon_table, layout=None)

Rebuild a HifukuTree from a flat state.

Unpacks the topology and branch-length arrays into a HifukuTree, sets node_order from compute_node_order (which reads the topology, so any valid index order works), and fills global_leaf_indices from the taxon table.

layout is what :func:leaf_layout returns, for a caller rebuilding many trees of one leaf order. The names are shared between them, which is safe because a tree does not rename its nodes; the index array is copied, so anything that writes into one tree's cannot reach another's.

Source code in src/hifuku/walk_state.py
def tree_from_state(state, leaf_names, n_nodes, n_leaves, taxon_table,
                    layout=None):
    """Rebuild a HifukuTree from a flat state.

    Unpacks the topology and branch-length arrays into a HifukuTree, sets
    ``node_order`` from ``compute_node_order`` (which reads the topology, so any
    valid index order works), and fills ``global_leaf_indices`` from the taxon
    table.

    ``layout`` is what :func:`leaf_layout` returns, for a caller rebuilding many
    trees of one leaf order.  The names are shared between them, which is safe
    because a tree does not rename its nodes; the index array is copied, so
    anything that writes into one tree's cannot reach another's.
    """
    parent = np.rint(state[0 * n_nodes:1 * n_nodes]).astype(np.int32)
    lc = np.rint(state[1 * n_nodes:2 * n_nodes]).astype(np.int32)
    rc = np.rint(state[2 * n_nodes:3 * n_nodes]).astype(np.int32)
    edge = state[3 * n_nodes:4 * n_nodes].astype(np.float64)
    edge[n_nodes - 1] = np.nan
    if layout is None:
        layout = leaf_layout(leaf_names, n_nodes, n_leaves, taxon_table)
    names, glidx = layout
    tree = HifukuTree(
        parent=parent, left_child=lc, right_child=rc, edge_len=edge,
        names=names, n_nodes=n_nodes, n_leaves=n_leaves, root=n_nodes - 1,
    )
    tree.node_order = tree.compute_node_order()
    tree.global_leaf_indices = glidx.copy()
    tree._keyed_by = taxon_table
    return tree

device_grid

device_grid(cell, origin, extent)

Dense device allocation for the unbounded niche map.

Returns (n_off, n_side, grid_lo, sink). An archive niche (i, j) maps to the device cell (i + n_off, j + n_off), a flat index in [0, n_side**2); sink = n_side**2 receives niches outside the allocation. The allocation is a memory bound, not a domain: the log-likelihood gate stops the fill inside it.

Source code in src/hifuku/walk_state.py
def device_grid(cell, origin, extent):
    """Dense device allocation for the unbounded niche map.

    Returns ``(n_off, n_side, grid_lo, sink)``.  An archive niche ``(i, j)`` maps
    to the device cell ``(i + n_off, j + n_off)``, a flat index in
    ``[0, n_side**2)``; ``sink = n_side**2`` receives niches outside the
    allocation.  The allocation is a memory bound, not a domain: the
    log-likelihood gate stops the fill inside it.
    """
    n_off = int(round(extent / cell))
    n_side = 2 * n_off
    grid_lo = origin - n_off * cell
    return n_off, n_side, grid_lo, n_side * n_side

bin_frame

bin_frame(origin, n_off)

(bin_origin, bin_offset) for a device's niche binning.

A point bins as floor((lambda - origin) / cell), the key the host gives it, and the allocation then shifts the key by n_off. The key depends on the point, the origin and the cell, and not on the size of the allocation.

Source code in src/hifuku/walk_state.py
def bin_frame(origin, n_off):
    """``(bin_origin, bin_offset)`` for a device's niche binning.

    A point bins as ``floor((lambda - origin) / cell)``, the key the host
    gives it, and the allocation then shifts the key by ``n_off``.  The key
    depends on the point, the origin and the cell, and not on the size of the
    allocation.
    """
    return float(origin), int(n_off)