Skip to content

Elite Archive (GPU)

The device elite-archive survey: an unconditional K-step walk per block, merged into the device archive by winner-take-all placement. The CPU archive is the reference for parity.

run_archive_gpu

run_archive_gpu(r1, r2, r3, alignment, model, start_trees, triangle, taxon_table, *, monitor=False, **overrides) -> ArchiveResult

Run the GPU elite-archive survey for one alignment.

The device runs n_walkers blocks per pass. Each block walks walk_steps moves from an assigned niche and writes one candidate per move. A batched place then merges every candidate. The archive is seeded from the anchors and the start trees.

This function builds a :class:~hifuku.gpu_backend.CudaBackend and gives it to :func:~hifuku.driver.run_survey. The loop and the halt rules are in the driver, which the CPU survey also uses. The engine records the rows that each rule reads: the rate rows for the trailing window of rate_window checkpoints, and the (S, N, m) rows for the QD-score rule. Thus each rule has one meaning on both engines, and the CPU survey serves as the parity oracle for this one.

The returned EliteArchive and history match the CPU survey's shape.

Parameters:

Name Type Description Default
r1 HifukuTree

Anchor trees that fix the chart.

required
r2 HifukuTree

Anchor trees that fix the chart.

required
r3 HifukuTree

Anchor trees that fix the chart.

required
alignment

The alignment surveyed and its substitution model.

required
model

The alignment surveyed and its substitution model.

required
start_trees list[HifukuTree]

Extra seed trees, normally the anchor tree for the surveyed gene.

required
triangle AnchorTriangle

Anchor geometry. It carries the chart metric.

required
taxon_table TaxonTable

Shared namespace.

required
monitor (callable, None or False)

A checkpoint callback. False, the default, reports nothing. None selects the default reporter. See :mod:hifuku.monitor.

False
**overrides

Any field of :class:~hifuku.params.ArchiveParams or of :class:~hifuku.params.GpuParams, both of which document them. A name is routed to whichever class declares it, and a name neither declares raises. See :func:~hifuku.params.split_overrides.

{}

Returns:

Type Description
ArchiveResult

The archive, its per-checkpoint history, and the halt state.

Source code in src/hifuku/gpu_walk.py
def run_archive_gpu(
    r1, r2, r3, alignment, model, start_trees, triangle, taxon_table,
    *,
    monitor=False,
    **overrides,
) -> ArchiveResult:
    """Run the GPU elite-archive survey for one alignment.

    The device runs ``n_walkers`` blocks per pass.  Each block walks
    ``walk_steps`` moves from an assigned niche and writes one candidate per
    move.  A batched place then merges every candidate.  The archive is seeded
    from the anchors and the start trees.

    This function builds a :class:`~hifuku.gpu_backend.CudaBackend` and gives it
    to :func:`~hifuku.driver.run_survey`.  The loop and the halt rules are in
    the driver, which the CPU survey also uses.  The engine records the rows
    that each rule reads: the rate rows for the trailing window of
    ``rate_window`` checkpoints, and the ``(S, N, m)`` rows for the QD-score
    rule.  Thus each rule has one meaning on both engines, and the CPU survey
    serves as the parity oracle for this one.

    The returned ``EliteArchive`` and history match the CPU survey's shape.

    Parameters
    ----------
    r1, r2, r3 : HifukuTree
        Anchor trees that fix the chart.
    alignment, model
        The alignment surveyed and its substitution model.
    start_trees : list[HifukuTree]
        Extra seed trees, normally the anchor tree for the surveyed gene.
    triangle : AnchorTriangle
        Anchor geometry.  It carries the chart metric.
    taxon_table : TaxonTable
        Shared namespace.
    monitor : callable, None or False
        A checkpoint callback.  False, the default, reports nothing.  None
        selects the default reporter.  See :mod:`hifuku.monitor`.
    **overrides
        Any field of :class:`~hifuku.params.ArchiveParams` or of
        :class:`~hifuku.params.GpuParams`, both of which document them.  A name
        is routed to whichever class declares it, and a name neither declares
        raises.  See :func:`~hifuku.params.split_overrides`.

    Returns
    -------
    ArchiveResult
        The archive, its per-checkpoint history, and the halt state.
    """
    from hifuku.backend import RunContext
    from hifuku.driver import run_survey
    from hifuku.gpu_backend import CudaBackend
    from hifuku.params import ArchiveParams, GpuParams, split_overrides

    survey_overrides, device_overrides = split_overrides(overrides)
    backend = CudaBackend(GpuParams.resolve(device_overrides))
    params = ArchiveParams.resolve(backend.caps.defaults, survey_overrides)
    ctx = RunContext(anchors=(r1, r2, r3), alignment=alignment, model=model,
                     start_trees=list(start_trees), triangle=triangle,
                     taxon_table=taxon_table)
    return run_survey(backend, ctx, params, monitor=monitor)

evaluate_gpu

evaluate_gpu(trees, r1, r2, r3, alignment, model, triangle, taxon_table, cell: float = ARCHIVE_CELL, origin: float = 0.0, extent: float = ARCHIVE_GPU_EXTENT)

Evaluate each tree's log-likelihood and niche on the device.

Flattens the trees into archive state, then runs the seed-eval kernel, which unflattens and peels with no move. Isolates the device unflatten and Felsenstein path so it can be checked against the CPU oracle. Returns (logL, ij) where ij is an (M, 2) array of archive niche indices; a tree outside the device allocation gets the sentinel INT_MIN niche.

Source code in src/hifuku/gpu_walk.py
def evaluate_gpu(trees, r1, r2, r3, alignment, model, triangle, taxon_table,
                 cell: float = ARCHIVE_CELL, origin: float = 0.0,
                 extent: float = ARCHIVE_GPU_EXTENT):
    """Evaluate each tree's log-likelihood and niche on the device.

    Flattens the trees into archive state, then runs the seed-eval kernel, which
    unflattens and peels with no move.  Isolates the device unflatten and
    Felsenstein path so it can be checked against the CPU oracle.  Returns
    ``(logL, ij)`` where ``ij`` is an ``(M, 2)`` array of archive niche indices;
    a tree outside the device allocation gets the sentinel ``INT_MIN`` niche.
    """
    trees = list(trees)
    for t in (r1, r2, r3, *trees):
        _set_global_leaf_indices(t, taxon_table)
    M = len(trees)

    # The leaf order comes from a tree being evaluated, not from an anchor: the
    # alignment is read in that order, and an anchor need not carry the same
    # taxa.  The anchors keep their own order and enter only as reference
    # tables, which key on global taxon indices.
    canon = canon_leaf_names(trees[0], taxon_table)
    ctrees = [relabel_to(t, canon, taxon_table) for t in trees]

    ct = init_chain_trees_2d(
        ctrees, anchor_ref1=r1, anchor_ref2=r2, anchor_ref3=r3,
        global_seed=0, alignment=alignment, model=model,
    )
    n_nodes = ct.n_nodes
    n_leaves = ct.n_leaves
    n_internal = ct.n_internal
    n_patterns = ct.n_patterns
    sdim = state_dim(n_nodes)
    n_off, n_side, _grid_lo, sink = device_grid(cell, origin, extent)
    bin_origin, bin_offset = bin_frame(origin, n_off)
    tm = triangle.tree_metric
    metric_w = np.float64(tm.w)

    eval_kernel = _eval_kernel_for(model.n_states)
    d_model_U = cuda.to_device(model.U.astype(np.float64))
    d_model_eigvals = cuda.to_device(model.eigvals.astype(np.float64))
    d_model_inv_sqrt_pi = cuda.to_device(model.inv_sqrt_pi.astype(np.float64))
    d_model_sqrt_pi = cuda.to_device(model.sqrt_pi.astype(np.float64))
    d_freqs = cuda.to_device(model.freqs.astype(np.float64))
    d_weights = cuda.to_device(alignment.weights.astype(np.float64))
    A_inv, Mbary_inv, rhs_off, P3_arr = trilateration_arrays(triangle)

    hp = ct.parent.copy_to_host()
    hlc = ct.left_child.copy_to_host()
    hrc = ct.right_child.copy_to_host()
    hedge = ct.edge_len.copy_to_host()
    states = np.stack([
        flatten_host(hp[m], hlc[m], hrc[m], hedge[m], n_nodes)
        for m in range(M)
    ])
    d_state = cuda.to_device(states)
    d_assign = cuda.to_device(np.arange(M, dtype=np.int32))
    d_fit = cuda.device_array(M, dtype=np.float32)
    d_niche = cuda.device_array(M, dtype=np.int32)

    eval_kernel[M, _CUDA_BLOCK_SIZE](
        d_assign, d_state,
        ct.parent, ct.left_child, ct.right_child, ct.edge_len,
        ct.node_order, ct.node_order_pos, ct.subtree_leaf_cnt,
        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.leaf_global_idx, ct.clade_value, ct.run_len,
        ct.graft_below, ct.dfs_nd, ct.dfs_ph,
        ct.partials, ct.P_mat, ct.scratch, ct.scratch_log_scale,
        d_model_U, d_model_eigvals, d_model_inv_sqrt_pi, d_model_sqrt_pi,
        d_freqs, d_weights,
        cuda.to_device(A_inv), cuda.to_device(Mbary_inv),
        cuda.to_device(rhs_off), cuda.to_device(P3_arr),
        np.float64(ct.C1), np.float64(ct.C2), np.float64(ct.C3),
        metric_w,
        d_fit, d_niche,
        np.int32(n_leaves), np.int32(n_nodes), np.int32(n_internal),
        np.int32(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(bin_origin), np.int32(bin_offset), np.float64(cell),
        np.int32(n_side), np.int32(sink),
    )
    cuda.synchronize()
    flat = d_niche.copy_to_host().astype(np.int64)
    ij = np.stack([flat // n_side - n_off, flat % n_side - n_off], axis=1)
    ij[flat == sink] = np.iinfo(np.int64).min
    return d_fit.copy_to_host(), ij