Skip to content

WGSL Kernels

The WGSL engine runs its kernels through wgpu, on Metal, Vulkan or Direct3D 12. WGSL has no 64-bit float, so the kernels carry the quantities that need more than float32 precision as float-float values: the unevaluated sum of two float32 values.

Float-float arithmetic rests on two error-free transformations, TwoSum and TwoProduct, which return a rounded result and its exact error. The WGSL specification lets a compiler reassociate floating-point operations, and a compiler that does so can remove the error. Each transformation therefore comes in more than one form, and a variant of the library names one form of each. ARITHMETICS lists the variants a host tries, fastest first.

The WGSL specification also lets a device flush subnormal values to zero, and it does not specify a rounding mode. The error-free transformations are therefore exact on stated domains, FF_TWO_SUM_MIN and FF_TWO_PROD_MIN in hifuku.constants, and on a device that rounds to nearest, which rounds_to_nearest checks.

hifuku.wgsl.arithmetic needs only the standard library. hifuku.wgsl.device and hifuku.wgsl.likelihood need the extra hifuku[wgsl].

The likelihood kernels

hifuku.wgsl.likelihood computes the log-likelihood of a tree in two kernels. The pruning kernel runs one invocation per site pattern. It keeps the partial likelihoods in float32 and scales them by powers of two, which is exact, so the exponent is an integer. It returns the scaled site likelihood and the exponent of each pattern, and the host takes the float64 log, as the CPU engine does. The product kernel raises each site likelihood to the weight of its pattern and multiplies the results in float-float. The host takes one float64 log per workgroup.

At first use, choose_arithmetic runs the product kernel in each variant on a fixed input. It keeps the fastest variant whose total lies within the derived error bound of the host's float64 sum of the same values.

The tolerances between the engines come from pruning_log_error and weighted_product_log_error in hifuku.precision. Their derivations are in docs/theory/algebra/.

The float-float library and the device

Arithmetic dataclass

One variant of the float-float library: a TwoSum and a TwoProduct form.

Attributes:

Name Type Description
two_sum str

"fast" or "int".

two_prod str

"fma" or "split".

Source code in src/hifuku/wgsl/arithmetic.py
@dataclass(frozen=True)
class Arithmetic:
    """One variant of the float-float library: a TwoSum and a TwoProduct form.

    Attributes
    ----------
    two_sum : str
        ``"fast"`` or ``"int"``.
    two_prod : str
        ``"fma"`` or ``"split"``.
    """

    two_sum: str
    two_prod: str

    @property
    def needs_runtime(self) -> bool:
        """True when the library reads the runtime zero of bind group 1."""
        return self.two_sum == "fast"

    def __str__(self) -> str:
        return f"{self.two_sum}-{self.two_prod}"

needs_runtime property

needs_runtime: bool

True when the library reads the runtime zero of bind group 1.

ARITHMETICS module-attribute

ARITHMETICS: tuple = (Arithmetic('fast', 'fma'), Arithmetic('fast', 'split'), Arithmetic('int', 'split'))

wgsl_source

wgsl_source(arithmetic: Arithmetic) -> str

Return the WGSL source of the float-float library for one variant.

A kernel puts its own code after this source and calls ff_prelude() first in its entry point.

Raises:

Type Description
ValueError

If either form of arithmetic is not one this library holds.

Source code in src/hifuku/wgsl/arithmetic.py
def wgsl_source(arithmetic: Arithmetic) -> str:
    """Return the WGSL source of the float-float library for one variant.

    A kernel puts its own code after this source and calls ``ff_prelude()``
    first in its entry point.

    Raises
    ------
    ValueError
        If either form of ``arithmetic`` is not one this library holds.
    """
    if arithmetic.two_sum not in _TWO_SUM_FORMS:
        raise ValueError(f"{arithmetic.two_sum!r} is not a TwoSum form.  The forms are "
                         f"{', '.join(_TWO_SUM_FORMS)}.")
    if arithmetic.two_prod not in _TWO_PROD_FORMS:
        raise ValueError(f"{arithmetic.two_prod!r} is not a TwoProduct form.  The forms "
                         f"are {', '.join(_TWO_PROD_FORMS)}.")
    parts = ["runtime.wgsl" if arithmetic.needs_runtime else "no_runtime.wgsl",
             f"two_sum_{arithmetic.two_sum}.wgsl",
             f"two_prod_{arithmetic.two_prod}.wgsl",
             "ff.wgsl"]
    return "\n".join(_read(part) for part in parts)

default_device

default_device()

Return the process's wgpu device, and create it on first use.

The adapter is the one :func:choose_adapter picks from all that wgpu finds.

Raises:

Type Description
ImportError

If wgpu-py is not installed. The message names the extra.

RuntimeError

If wgpu finds no adapter that :func:choose_adapter accepts.

Source code in src/hifuku/wgsl/device.py
def default_device():
    """Return the process's wgpu device, and create it on first use.

    The adapter is the one :func:`choose_adapter` picks from all that wgpu
    finds.

    Raises
    ------
    ImportError
        If wgpu-py is not installed.  The message names the extra.
    RuntimeError
        If wgpu finds no adapter that :func:`choose_adapter` accepts.
    """
    global _DEVICE
    if _DEVICE is None:
        wgpu = _wgpu()
        adapter = choose_adapter(wgpu.gpu.enumerate_adapters_sync())
        _DEVICE = adapter.request_device_sync()
        clear_pipeline_cache()      # a pipeline belongs to one device
    return _DEVICE

choose_adapter

choose_adapter(adapters)

Return the adapter to run the kernels on.

An OpenGL adapter is never chosen: wgpu's OpenGL backend may lack compute shaders, and a request for a high-performance adapter can return one in place of a Vulkan adapter on the same machine. Of the others, a discrete GPU comes first, then an integrated GPU, a virtual GPU and a CPU adapter.

Raises:

Type Description
RuntimeError

If no adapter other than an OpenGL one is present.

Source code in src/hifuku/wgsl/device.py
def choose_adapter(adapters):
    """Return the adapter to run the kernels on.

    An OpenGL adapter is never chosen: wgpu's OpenGL backend may lack compute
    shaders, and a request for a high-performance adapter can return one in
    place of a Vulkan adapter on the same machine.  Of the others, a discrete
    GPU comes first, then an integrated GPU, a virtual GPU and a CPU adapter.

    Raises
    ------
    RuntimeError
        If no adapter other than an OpenGL one is present.
    """
    usable = [a for a in adapters if a.info["backend_type"] != "OpenGL"]
    if not usable:
        raise RuntimeError("wgpu found no adapter other than OpenGL, which may lack "
                           "compute shaders.")

    def rank(adapter):
        kind = adapter.info["adapter_type"]
        return _ADAPTER_ORDER.index(kind) if kind in _ADAPTER_ORDER else len(_ADAPTER_ORDER)
    return min(usable, key=rank)

run_kernel

run_kernel(code: str, inputs: Sequence[ndarray], out_nbytes: int, workgroups: int, arithmetic: Arithmetic | None = None, scratch: Sequence[int] = (), name: str | None = None) -> bytes

Run the entry point main of code once, and return its output.

Group 0 holds the inputs at bindings 0 to len(inputs) - 1, as read-only storage, and the output at binding len(inputs), as read-write storage of out_nbytes bytes. Each entry of scratch adds a read-write buffer of that many bytes, filled with zeros, at the bindings after the output. The host does not read the scratch buffers.

Group :data:~hifuku.constants.WGSL_RUNTIME_GROUP, binding 0, holds the runtime zero when arithmetic.needs_runtime. When arithmetic is None, the code holds no float-float library and no runtime group is bound.

A pipeline is compiled once for each source and reused. name labels the :class:KernelRecord that :func:profiling collects.

Source code in src/hifuku/wgsl/device.py
def run_kernel(code: str, inputs: Sequence[np.ndarray], out_nbytes: int,
               workgroups: int, arithmetic: Arithmetic | None = None,
               scratch: Sequence[int] = (), name: str | None = None) -> bytes:
    """Run the entry point ``main`` of ``code`` once, and return its output.

    Group 0 holds the inputs at bindings 0 to ``len(inputs) - 1``, as read-only
    storage, and the output at binding ``len(inputs)``, as read-write storage of
    ``out_nbytes`` bytes.  Each entry of ``scratch`` adds a read-write buffer of
    that many bytes, filled with zeros, at the bindings after the output.  The
    host does not read the scratch buffers.

    Group :data:`~hifuku.constants.WGSL_RUNTIME_GROUP`, binding 0, holds the
    runtime zero when ``arithmetic.needs_runtime``.  When ``arithmetic`` is
    None, the code holds no float-float library and no runtime group is bound.

    A pipeline is compiled once for each source and reused.  ``name`` labels
    the :class:`KernelRecord` that :func:`profiling` collects.
    """
    wgpu = _wgpu()
    device = default_device()
    storage = wgpu.BufferUsage.STORAGE
    start = time.perf_counter()
    pipeline, compiled = compute_pipeline(device, code)
    compiled_at = time.perf_counter()
    buffers = [device.create_buffer_with_data(data=np.ascontiguousarray(a), usage=storage)
               for a in inputs]
    output = device.create_buffer(size=out_nbytes, usage=storage | wgpu.BufferUsage.COPY_SRC)
    buffers.append(output)
    buffers.extend(device.create_buffer(size=nbytes, usage=storage) for nbytes in scratch)

    def bind(group, members):
        return device.create_bind_group(
            layout=pipeline.get_bind_group_layout(group),
            entries=[{"binding": i, "resource": {"buffer": b, "offset": 0, "size": b.size}}
                     for i, b in enumerate(members)])

    groups = [(0, bind(0, buffers))]
    if arithmetic is not None and arithmetic.needs_runtime:
        groups.append((WGSL_RUNTIME_GROUP, runtime_group(device, pipeline)))
    uploaded_at = time.perf_counter()
    encoder = device.create_command_encoder()
    compute_pass = encoder.begin_compute_pass()
    compute_pass.set_pipeline(pipeline)
    for index, group in groups:
        compute_pass.set_bind_group(index, group)
    compute_pass.dispatch_workgroups(workgroups)
    compute_pass.end()
    device.queue.submit([encoder.finish()])
    result = bytes(device.queue.read_buffer(output))
    record(KernelRecord(name or "kernel", compiled, compiled_at - start,
                        uploaded_at - compiled_at, time.perf_counter() - uploaded_at))
    return result

rounds_to_nearest

rounds_to_nearest() -> bool

Return True when the device rounds float32 addition to nearest.

WGSL does not specify a rounding mode. The library's error-free transformations, and the error bounds it uses, assume rounding to nearest. The probe adds 0.75 and 0.25 units in the last place of 1 to 1 and to -1. Rounding to nearest gives 1 + ulp, 1, -(1 + ulp) and -1; rounding toward zero, upward or downward gives at least one other result.

Source code in src/hifuku/wgsl/device.py
def rounds_to_nearest() -> bool:
    """Return True when the device rounds float32 addition to nearest.

    WGSL does not specify a rounding mode.  The library's error-free
    transformations, and the error bounds it uses, assume rounding to nearest.
    The probe adds 0.75 and 0.25 units in the last place of 1 to 1 and to -1.
    Rounding to nearest gives 1 + ulp, 1, -(1 + ulp) and -1; rounding toward
    zero, upward or downward gives at least one other result.
    """
    arithmetic = Arithmetic("int", "split")
    ulp = 2.0 ** -23
    addends = np.array([1.0, 0.75 * ulp, 1.0, 0.25 * ulp,
                        -1.0, -0.75 * ulp, -1.0, -0.25 * ulp], dtype=np.float32)
    raw = run_kernel(wgsl_source(arithmetic) + _ROUNDING_PROBE, [addends], 16, 1, arithmetic)
    expected = np.array([1.0 + ulp, 1.0, -(1.0 + ulp), -1.0], dtype=np.float32)
    return bool(np.array_equal(np.frombuffer(raw, dtype=np.float32), expected))

fused_fma

fused_fma() -> bool

Return True when the device fuses fma.

The probe multiplies 1 + 2^-12 by itself. The exact product is 1 + 2^-11 + 2^-24, and rounding to float32 drops the 2^-24. A fused fma returns that 2^-24 as the residual; an unfused one returns zero.

Source code in src/hifuku/wgsl/device.py
def fused_fma() -> bool:
    """Return True when the device fuses ``fma``.

    The probe multiplies 1 + 2^-12 by itself.  The exact product is
    1 + 2^-11 + 2^-24, and rounding to float32 drops the 2^-24.  A fused fma
    returns that 2^-24 as the residual; an unfused one returns zero.
    """
    arithmetic = Arithmetic("int", "split")
    factor = np.float32(1.0 + 2.0 ** -12)
    raw = run_kernel(wgsl_source(arithmetic) + _FMA_PROBE,
                     [np.array([factor, factor], dtype=np.float32)], 4, 1, arithmetic)
    return float(np.frombuffer(raw, dtype=np.float32)[0]) != 0.0

adapter_summary

adapter_summary() -> str

Return the adapter's device name, backend and type, for a log or a test.

Source code in src/hifuku/wgsl/device.py
def adapter_summary() -> str:
    """Return the adapter's device name, backend and type, for a log or a test."""
    info = default_device().adapter.info
    return f"{info['device']} ({info['backend_type']}, {info['adapter_type']})"

storage_limit

storage_limit() -> int

Return the largest storage buffer, in bytes, that one binding can hold.

Source code in src/hifuku/wgsl/device.py
def storage_limit() -> int:
    """Return the largest storage buffer, in bytes, that one binding can hold."""
    return _capped("storage",
                   int(default_device().limits["max-storage-buffer-binding-size"]))

workgroup_limit

workgroup_limit() -> int

Return the largest workgroup count that one dispatch dimension can hold.

Source code in src/hifuku/wgsl/device.py
def workgroup_limit() -> int:
    """Return the largest workgroup count that one dispatch dimension can hold."""
    return _capped("workgroups",
                   int(default_device().limits["max-compute-workgroups-per-dimension"]))

profiling

profiling()

Collect one :class:KernelRecord for each run_kernel call inside.

A profiling inside another one collects its own records, and passes them to the outer one when it ends.

Source code in src/hifuku/wgsl/device.py
@contextmanager
def profiling():
    """Collect one :class:`KernelRecord` for each ``run_kernel`` call inside.

    A ``profiling`` inside another one collects its own records, and passes
    them to the outer one when it ends.
    """
    global _RECORDS
    outer, _RECORDS = _RECORDS, []
    inner = _RECORDS
    try:
        yield inner
    finally:
        _RECORDS = outer
        if outer is not None:
            outer.extend(inner)

KernelRecord dataclass

The time one run_kernel call spent in each phase, in seconds.

compiled is True when the call created the pipeline, and False when it reused one from the cache. run_s runs from the submission of the dispatch to the end of the read of the output, so it holds the kernel and the copy back to the host. The times are host wall time.

Source code in src/hifuku/wgsl/device.py
@dataclass(frozen=True)
class KernelRecord:
    """The time one ``run_kernel`` call spent in each phase, in seconds.

    ``compiled`` is True when the call created the pipeline, and False when it
    reused one from the cache.  ``run_s`` runs from the submission of the
    dispatch to the end of the read of the output, so it holds the kernel and
    the copy back to the host.  The times are host wall time.
    """

    name: str
    compiled: bool
    compile_s: float
    upload_s: float
    run_s: float

clear_pipeline_cache

clear_pipeline_cache() -> None

Forget every compiled pipeline.

Source code in src/hifuku/wgsl/device.py
def clear_pipeline_cache() -> None:
    """Forget every compiled pipeline."""
    _PIPELINES.clear()

cached_pipeline_count

cached_pipeline_count() -> int

Return how many compiled pipelines the cache holds.

Source code in src/hifuku/wgsl/device.py
def cached_pipeline_count() -> int:
    """Return how many compiled pipelines the cache holds."""
    return len(_PIPELINES)

Survey primitives

The survey engine keys splits by 64-bit values and draws from a generator with 64-bit state. WGSL has no 64-bit integer, so u64.wgsl holds one as vec2<u32>(low, high), with exact addition, subtraction, the low half of a product, shifts, rotations and comparisons.

xoroshiro.wgsl advances the xoroshiro128+ generator of the CUDA engine and draws its float32 uniform, the top 24 bits of a word times 2^-24. The host seeds the walkers with initial_states, as Numba seeds them, so the WGSL and CUDA engines draw the same words from the same seed. A walker's state is the two words that the CUDA engine saves in a checkpoint.

splits.wgsl computes leaf values, clade values and split keys as hifuku.tree_io does, and split_search.wgsl searches an anchor's sorted key table. library assembles these files with their dependencies.

A browser allows 8 storage buffers for each shader stage. pack lays many typed arrays in one buffer, and wgsl_offsets gives the start of each as a WGSL constant.

run_kernel compiles each kernel source once. Inside profiling, it records the time of each call in a KernelRecord.

library

library(*names: str) -> str

Return the WGSL source of names and their dependencies, each once.

A dependency comes before every file that uses it. A file that reads a value of :mod:hifuku.constants gets it as a WGSL constant at its head.

Raises:

Type Description
KeyError

If a name is not a file this module knows.

Source code in src/hifuku/wgsl/library.py
def library(*names: str) -> str:
    """Return the WGSL source of ``names`` and their dependencies, each once.

    A dependency comes before every file that uses it.  A file that reads a
    value of :mod:`hifuku.constants` gets it as a WGSL constant at its head.

    Raises
    ------
    KeyError
        If a name is not a file this module knows.
    """
    ordered: list[str] = []

    def visit(name):
        if name in ordered:
            return
        for dependency in _DEPENDS[name]:
            visit(dependency)
        ordered.append(name)

    for name in names:
        visit(name)
    return "\n".join(_constants(name)
                     + (files("hifuku.wgsl") / f"{name}.wgsl").read_text(encoding="utf-8")
                     for name in ordered)

wgsl_f32

wgsl_f32(value: float) -> str

Return value as a WGSL hexadecimal f32 literal, without rounding.

Raises:

Type Description
ValueError

If float32 cannot hold value exactly.

Source code in src/hifuku/wgsl/library.py
def wgsl_f32(value: float) -> str:
    """Return ``value`` as a WGSL hexadecimal f32 literal, without rounding.

    Raises
    ------
    ValueError
        If float32 cannot hold ``value`` exactly.
    """
    if float(np.float32(value)) != float(value):
        raise ValueError(f"{value!r} is not exactly a float32 value")
    return float(value).hex() + "f"

pack

pack(arrays: dict) -> Packed

Lay arrays one after another in one buffer of 32-bit words.

Each array starts on a multiple of 4 words. A uint64 element takes two words, the low word first. A name becomes part of a WGSL constant, so it must be an identifier, and two names may not differ only in case.

Raises:

Type Description
ValueError

If an array's type is not float32, int32, uint32 or uint64, if a name is not an identifier, or if two names give the same constant.

Source code in src/hifuku/wgsl/packing.py
def pack(arrays: dict) -> Packed:
    """Lay ``arrays`` one after another in one buffer of 32-bit words.

    Each array starts on a multiple of 4 words.  A uint64 element takes two
    words, the low word first.  A name becomes part of a WGSL constant, so it
    must be an identifier, and two names may not differ only in case.

    Raises
    ------
    ValueError
        If an array's type is not float32, int32, uint32 or uint64, if a name
        is not an identifier, or if two names give the same constant.
    """
    seen = {}
    for name in arrays:
        if not _IDENTIFIER.match(name):
            raise ValueError(f"array name {name!r} is not an identifier, so it cannot "
                             f"name a WGSL constant.")
        if name.upper() in seen:
            raise ValueError(f"array names {seen[name.upper()]!r} and {name!r} give the "
                             f"same constant.")
        seen[name.upper()] = name
    layout, parts, offset = {}, [], 0
    for name, array in arrays.items():
        shape = np.shape(array)            # np.ascontiguousarray makes 0-d 1-d
        array = np.ascontiguousarray(array)
        if array.dtype not in _WORDS:
            raise ValueError(f"array {name!r} is {array.dtype}; a packed buffer holds "
                             f"float32, int32, uint32 and uint64.")
        words = array.view(np.uint32).ravel() if array.size else np.zeros(0, np.uint32)
        layout[name] = Slot(offset, array.dtype, shape)
        padded = -(-words.size // _ALIGN) * _ALIGN
        parts.append(np.concatenate([words, np.zeros(padded - words.size, np.uint32)]))
        offset += padded
    words = np.concatenate(parts) if parts else np.zeros(0, np.uint32)
    if words.size == 0:
        words = np.zeros(_ALIGN, np.uint32)        # a binding may not be empty
    return Packed(words, layout)

unpack

unpack(packed: Packed, name: str) -> np.ndarray

Return array name from a packed buffer, as :func:pack received it.

Source code in src/hifuku/wgsl/packing.py
def unpack(packed: Packed, name: str) -> np.ndarray:
    """Return array ``name`` from a packed buffer, as :func:`pack` received it."""
    slot = packed.layout[name]
    count = int(np.prod(slot.shape, dtype=np.int64)) * _WORDS[slot.dtype]
    words = packed.words[slot.offset:slot.offset + count]
    return words.view(slot.dtype).reshape(slot.shape).copy()

wgsl_offsets

wgsl_offsets(packed: Packed, prefix: str) -> str

Return the start of each array as a WGSL constant, in words.

Source code in src/hifuku/wgsl/packing.py
def wgsl_offsets(packed: Packed, prefix: str) -> str:
    """Return the start of each array as a WGSL constant, in words."""
    return "".join(f"const {prefix}_{name.upper()}: u32 = {slot.offset}u;\n"
                   for name, slot in packed.layout.items())

initial_states

initial_states(n: int, seed: int) -> np.ndarray

Return the states of n walkers, as Numba seeds them, uint64 (n, 2).

Column 0 is s0 and column 1 is s1, the layout in which the CUDA engine saves its states in a checkpoint. The seed wraps to 64 bits.

Numba's own CPU seeding does the work when its CUDA module imports, which needs no GPU. Otherwise :func:initial_states_reference does, in Python integers, several hundred times more slowly.

Source code in src/hifuku/wgsl/xoroshiro.py
def initial_states(n: int, seed: int) -> np.ndarray:
    """Return the states of ``n`` walkers, as Numba seeds them, uint64 ``(n, 2)``.

    Column 0 is ``s0`` and column 1 is ``s1``, the layout in which the CUDA
    engine saves its states in a checkpoint.  The seed wraps to 64 bits.

    Numba's own CPU seeding does the work when its CUDA module imports, which
    needs no GPU.  Otherwise :func:`initial_states_reference` does, in Python
    integers, several hundred times more slowly.
    """
    word = operator.index(seed) & _MASK
    try:
        from numba.cuda.random import init_xoroshiro128p_states_cpu, xoroshiro128p_dtype
    except Exception:
        return initial_states_reference(n, word)
    states = np.empty(n, dtype=xoroshiro128p_dtype)
    # Numba takes the seed as a signed 64-bit integer and converts it back.
    init_xoroshiro128p_states_cpu(states, word - (1 << 64) if word >> 63 else word, 0)
    return np.stack([states["s0"], states["s1"]], axis=1)

initial_states_reference

initial_states_reference(n: int, seed: int) -> np.ndarray

The states of :func:initial_states, computed in Python integers.

Source code in src/hifuku/wgsl/xoroshiro.py
def initial_states_reference(n: int, seed: int) -> np.ndarray:
    """The states of :func:`initial_states`, computed in Python integers."""
    out = np.empty((n, 2), dtype=np.uint64)
    # A NumPy integer seed becomes a Python int first, so that the wrap to 64
    # bits neither overflows a fixed-width type nor warns.
    z = _splitmix64(operator.index(seed) & _MASK)
    state = [z, z]
    for m in range(n):
        if m:
            jump(state)
        out[m] = state
    return out

next_word

next_word(state: list) -> int

Return the next 64-bit word and advance state, a list [s0, s1].

Source code in src/hifuku/wgsl/xoroshiro.py
def next_word(state: list) -> int:
    """Return the next 64-bit word and advance ``state``, a list ``[s0, s1]``."""
    s0, s1 = state
    result = (s0 + s1) & _MASK
    s1 ^= s0
    state[0] = _rotl(s0, 55) ^ s1 ^ ((s1 << 14) & _MASK)
    state[1] = _rotl(s1, 36)
    return result

jump

jump(state: list) -> None

Advance state by 2^64 steps.

Source code in src/hifuku/wgsl/xoroshiro.py
def jump(state: list) -> None:
    """Advance ``state`` by 2^64 steps."""
    s0 = s1 = 0
    for word in _JUMP:
        for bit in range(64):
            if word & (1 << bit):
                s0 ^= state[0]
                s1 ^= state[1]
            next_word(state)
    state[0], state[1] = s0, s1

uniform_float32

uniform_float32(word: int) -> np.float32

The uniform in [0, 1) that the CUDA engine draws from one word.

The top 24 bits times 2^-24. Both steps are exact in float32.

Source code in src/hifuku/wgsl/xoroshiro.py
def uniform_float32(word: int) -> np.float32:
    """The uniform in [0, 1) that the CUDA engine draws from one word.

    The top 24 bits times 2^-24.  Both steps are exact in float32.
    """
    return np.float32(word >> 40) * _UNIT

Transition matrices

The CUDA engine rebuilds a transition matrix in float64 by the exp form P = D^-½ U diag(e^{λt}) Uᵀ D^½ and rounds it to float32. WGSL has no float64. In float32 the exp form loses the small entries of a short branch, because each one is a sum of terms of both signs whose size does not shrink with t. transition_matrices_ff uses the expm1 form P = I + D^-½ U diag(expm1(λt)) Uᵀ D^½ instead. In this form the terms of an off-diagonal entry shrink with t, as the entry does. The rebuild computes this form in float-float, with the float-float ff_expm1 of ff_expm1.wgsl, and rounds each entry to float32. It is a baseline for correctness. A faster rebuild will be measured against it.

ff_expm1 reduces its argument by multiples of ln 2 and sums a Taylor polynomial of degree FF_EXPM1_TERMS in float-float. Below FF_EXPM1_FLOOR it returns −1. ff_expm1_error gives its error bound, and transition_matrix_error gives the bound of one matrix entry, for this rebuild and for the CUDA engine's float64 rebuild.

For float64 eigenvectors, the two forms differ by R_ij (UUᵀ)_ij − δ_ij at every t, with R_ij = √(π_j/π_i). The cause is that an eigensolver returns a U that is orthonormal only to its rounding. form_difference gives this difference. It is 2.5×10⁻¹⁶ for JC69 and 8.4×10⁻¹⁴ for WAG, so the two engines' matrices can differ by this much at t = 0. docs/theory/algebra/joldes2017tight-higham2002accuracy-expm1.py derives every bound in this section.

The transition_matrices workload of scripts/bench.py times the rebuild against the CUDA engine's.

transition_matrices_ff

transition_matrices_ff(model, edge_lengths: ndarray, arithmetic: Arithmetic | None = None) -> np.ndarray

Return the float32 transition matrix of each edge length, (B, S, S).

Each entry is the float-float value of the expm1 form rounded to float32 and clamped at zero. Its error before the rounding is within :func:hifuku.precision.transition_matrix_error of the value for the model's float64 eigensystem. arithmetic=None uses :func:hifuku.wgsl.likelihood.choose_arithmetic.

Raises:

Type Description
ValueError

If the model has more than 20 states, or if the matrices need more bytes than one storage binding of the device holds.

Source code in src/hifuku/wgsl/pmat.py
def transition_matrices_ff(model, edge_lengths: np.ndarray,
                           arithmetic: Arithmetic | None = None) -> np.ndarray:
    """Return the float32 transition matrix of each edge length, ``(B, S, S)``.

    Each entry is the float-float value of the expm1 form rounded to float32
    and clamped at zero.  Its error before the rounding is within
    :func:`hifuku.precision.transition_matrix_error` of the value for the
    model's float64 eigensystem.  ``arithmetic=None`` uses
    :func:`hifuku.wgsl.likelihood.choose_arithmetic`.

    Raises
    ------
    ValueError
        If the model has more than 20 states, or if the matrices need more
        bytes than one storage binding of the device holds.
    """
    if model.n_states > _MAX_STATES:
        raise ValueError(f"the kernel holds at most {_MAX_STATES} states; the model "
                         f"has {model.n_states}.")
    if arithmetic is None:
        from hifuku.wgsl.likelihood import choose_arithmetic
        arithmetic = choose_arithmetic()
    lengths = np.ascontiguousarray(edge_lengths, dtype=np.float32).ravel()
    S, B = model.n_states, lengths.size
    if B == 0:
        return np.zeros((0, S, S), dtype=np.float32)
    per_matrix = 4 * S * S
    if B * per_matrix > storage_limit():
        raise ValueError(f"{B} matrices of {S} states need {B * per_matrix} bytes, more "
                         f"than the storage limit of {storage_limit()} bytes of the device.")
    packed = _model_buffer(model)
    source = kernel_source(model, packed, arithmetic)
    pieces = []
    # One workgroup per matrix, and one dispatch holds at most
    # workgroup_limit() groups.
    most = workgroup_limit()
    for first in range(0, B, most):
        part = lengths[first:first + most]
        raw = run_kernel(source, [packed.words, part], per_matrix * part.size, part.size,
                         arithmetic, name="transition matrices")
        pieces.append(np.frombuffer(raw, dtype=np.float32))
    return np.concatenate(pieces).reshape(B, S, S)

expm1_source

expm1_source(arithmetic: Arithmetic) -> str

Return the WGSL source of the float-float expm1 of one library variant.

It holds the float-float library of arithmetic, the constants the expm1 reads, the unrolled Taylor chain and ff_expm1. A kernel calls ff_prelude() first, as for any float-float kernel.

Source code in src/hifuku/wgsl/library.py
def expm1_source(arithmetic: Arithmetic) -> str:
    """Return the WGSL source of the float-float expm1 of one library variant.

    It holds the float-float library of ``arithmetic``, the constants the
    expm1 reads, the unrolled Taylor chain and ``ff_expm1``.  A kernel calls
    ``ff_prelude()`` first, as for any float-float kernel.
    """
    constants = (f"const FF_EXPM1_FLOOR: f32 = {wgsl_f32(FF_EXPM1_FLOOR)};\n"
                 f"const LN2: vec2<f32> = {wgsl_ff(math.log(2.0))};\n"
                 f"const INV_LN2: f32 = {wgsl_f32(float(np.float32(1.0 / math.log(2.0))))};\n")
    return (wgsl_source(arithmetic) + "\n" + constants + _expm1_taylor()
            + (files("hifuku.wgsl") / "ff_expm1.wgsl").read_text(encoding="utf-8"))

ff_expm1_error

ff_expm1_error() -> tuple

Return (relative, absolute) bounds of the WGSL float-float expm1.

For a float-float x with FF_EXPM1_FLOOR < x <= 1/2, the computed value lies within relative * |expm1(x)| + absolute of expm1(x). The relative bound is set by the reduction r = x - k ln 2, whose error grows with |k|; the absolute term covers a device that flushes subnormal values.

Derived in docs/theory/algebra/joldes2017tight-higham2002accuracy-expm1.py. Joldes et al. (2017); muller2022formalization (Theorems 2.7 and 2.8).

Source code in src/hifuku/precision.py
def ff_expm1_error() -> tuple:
    """Return ``(relative, absolute)`` bounds of the WGSL float-float expm1.

    For a float-float ``x`` with ``FF_EXPM1_FLOOR < x <= 1/2``, the computed
    value lies within ``relative * |expm1(x)| + absolute`` of ``expm1(x)``.
    The relative bound is set by the reduction ``r = x - k ln 2``, whose error
    grows with ``|k|``; the absolute term covers a device that flushes
    subnormal values.

    Derived in
    docs/theory/algebra/joldes2017tight-higham2002accuracy-expm1.py.
    Joldes et al. (2017); muller2022formalization (Theorems 2.7 and 2.8).
    """
    em, ea, dc = FF_MUL_RELATIVE_ERROR, FF_ADD_RELATIVE_ERROR, _FF_SPLIT_ERROR
    ln2 = math.log(2.0)
    k_max = math.floor(abs(FF_EXPM1_FLOOR) / ln2 + 0.5)
    # k is rounded from a float32 product, so |r| can pass ln 2 / 2 a little.
    r_max = ln2 / 2.0 + abs(FF_EXPM1_FLOOR) * _gamma(3, UNIT_ROUNDOFF["float32"])

    def delta_r(k):
        return abs(k) * ln2 * (dc + em + dc * em) * (1.0 + ea) + ea * r_max

    # The derivation fixes the Taylor degree for |r| up to r_max + margin.
    if delta_r(k_max) > _REDUCTION_MARGIN:
        raise AssertionError("the reduction error exceeds the margin the Taylor "
                             "degree was derived for")
    r_bound = r_max + _REDUCTION_MARGIN
    rho_e = dc / 2.0 + 1.5 * ea + 2.0 * em + 2.0 ** -48
    # k <= -1: the scale 2^k shrinks the reduction error faster than |k| grows it.
    lower = 1.0 - math.exp(r_bound) / 2.0
    e_max = (math.exp(r_bound) - 1.0) / 2.0
    rho_neg = (e_max * rho_e + math.exp(r_bound) / 2.0 * delta_r(1)) / lower + ea
    # k = 1: r lies in [-r_bound, 1/2 - ln 2] and the result is 2 e^r - 1.
    lower_1 = 2.0 * math.exp(-r_bound) - 1.0
    rho_pos = (2.0 * (1.0 - math.exp(-r_bound)) * rho_e + 2.0 * delta_r(1)) / lower_1 + ea
    saturation = math.exp(FF_EXPM1_FLOOR) / (1.0 - math.exp(FF_EXPM1_FLOOR))
    absolute = 2.0 * (3 * FF_EXPM1_TERMS + 6) * 2.0 ** -126
    return max(rho_e, rho_neg, rho_pos, saturation), absolute

transition_matrix_error

transition_matrix_error(terms: float, kind: str, n_states: int, coefficients: float = 0.0) -> float

Return a bound on the error of one transition matrix entry before rounding.

kind is "float-float" for the WGSL engine's expm1 form, with terms = R_ij sum_l |U_il U_jl expm1(lambda_l t)| and coefficients = R_ij sum_l |U_il U_jl|, where R_ij = sqrt(pi_j / pi_i). It is "float64" for the CUDA engine's exp form, with terms = R_ij sum_l |U_il U_jl exp(lambda_l t)| and the same coefficients, which carry the rounding of lambda_l t. The exact value is the one for the float64 eigensystem.

Derived in docs/theory/algebra/joldes2017tight-higham2002accuracy-expm1.py, items 8 and 9. Higham (2002) : Lemma 3.1; eq. (3.5).

Raises:

Type Description
ValueError

If kind is neither "float-float" nor "float64".

Source code in src/hifuku/precision.py
def transition_matrix_error(terms: float, kind: str, n_states: int,
                            coefficients: float = 0.0) -> float:
    """Return a bound on the error of one transition matrix entry before rounding.

    ``kind`` is ``"float-float"`` for the WGSL engine's expm1 form, with
    ``terms = R_ij sum_l |U_il U_jl expm1(lambda_l t)|`` and
    ``coefficients = R_ij sum_l |U_il U_jl|``, where
    ``R_ij = sqrt(pi_j / pi_i)``.  It is ``"float64"`` for the CUDA engine's
    exp form, with ``terms = R_ij sum_l |U_il U_jl exp(lambda_l t)|`` and the
    same ``coefficients``, which carry the rounding of ``lambda_l t``.  The
    exact value is the one for the float64 eigensystem.

    Derived in
    docs/theory/algebra/joldes2017tight-higham2002accuracy-expm1.py, items 8
    and 9.  Higham (2002) : Lemma 3.1; eq. (3.5).

    Raises
    ------
    ValueError
        If ``kind`` is neither ``"float-float"`` nor ``"float64"``.
    """
    if kind == "float64":
        v = UNIT_ROUNDOFF["float64"]
        g = _gamma(n_states + 5, v)
        # The rounding of lambda t, at most |x| e^x v <= v / e for each term.
        return g * terms + coefficients * v * (1.0 + 2.0 * v) * (1.0 + g) / math.e
    if kind != "float-float":
        raise ValueError(f"{kind!r} is not a kind this bound covers; it covers "
                         f"'float-float' and 'float64', and not float32.")
    em, ea, dc = FF_MUL_RELATIVE_ERROR, FF_ADD_RELATIVE_ERROR, _FF_SPLIT_ERROR
    relative, absolute = ff_expm1_error()
    return (terms * (relative + 4.0 * dc + 4.0 * em + (n_states - 1) * ea)
            + coefficients * absolute + ea * (1.0 + terms)
            + (3 * n_states + 3) * 2.0 ** -126)

form_difference

form_difference(model) -> np.ndarray

Return a bound on the distance between the exp and expm1 forms, (S, S).

For one float64 eigensystem, the exp form R_ij sum_l U_il U_jl exp(lambda_l t) and the expm1 form delta_ij + R_ij sum_l U_il U_jl expm1(lambda_l t) differ by R_ij (U U^T)_ij - delta_ij at every t. This is zero for an orthonormal U, and the float64 U of an eigensolver is orthonormal only to its rounding. The bound is the float64 value of that difference and its rounding error.

Derived in docs/theory/algebra/joldes2017tight-higham2002accuracy-expm1.py, items 10 and 11. Higham (2002) : Lemma 3.1; eq. (3.5).

Source code in src/hifuku/precision.py
def form_difference(model) -> np.ndarray:
    """Return a bound on the distance between the exp and expm1 forms, ``(S, S)``.

    For one float64 eigensystem, the exp form
    ``R_ij sum_l U_il U_jl exp(lambda_l t)`` and the expm1 form
    ``delta_ij + R_ij sum_l U_il U_jl expm1(lambda_l t)`` differ by
    ``R_ij (U U^T)_ij - delta_ij`` at every ``t``.  This is zero for an
    orthonormal ``U``, and the float64 ``U`` of an eigensolver is orthonormal
    only to its rounding.  The bound is the float64 value of that difference
    and its rounding error.

    Derived in
    docs/theory/algebra/joldes2017tight-higham2002accuracy-expm1.py, items 10
    and 11.  Higham (2002) : Lemma 3.1; eq. (3.5).
    """
    R = model.inv_sqrt_pi[:, None] * model.sqrt_pi[None, :]
    eye = np.eye(model.n_states)
    omega = R * (model.U @ model.U.T) - eye
    C = R * (np.abs(model.U) @ np.abs(model.U).T)
    return np.abs(omega) + _gamma(model.n_states + 3, UNIT_ROUNDOFF["float64"]) * (C + eye)

Walker fitness

The CUDA walk kernel computes each walker's log-likelihood fitness after every move. walker_fitness computes it on a WebGPU device from the walker states that the archive stores, with three kernels, each timed by profiling:

  1. walker_orders gives the post-order of each tree by the depth-first search of the CUDA walk, bit for bit.
  2. transition_matrices_ff rebuilds the matrix of every edge.
  3. A peel kernel with one workgroup per walker peels every pattern, with float32 partials scaled by powers of two. It raises each site value to its weight and multiplies the powers in float-float, and it reduces them by a tree. One invocation then forms the fitness log(h) + E ln 2 from the product (h + l) 2^E.

The fitness uses WGSL's float32 log, whose absolute error the WGSL specification bounds by 2^-21 on [0.5, 2.0]. walker_fitness_error gives the allowed distance from the CUDA engine's fitness for the same tree. docs/theory/algebra/joldes2017tight-higham2002accuracy-walker-fitness.py derives it. The walker_fitness workload of scripts/bench.py times the three kernels, and walker_evaluation times them with the placement against the CUDA engine's seed-evaluation kernel.

walker_fitness

walker_fitness(states: ndarray, leaf_rows: ndarray, alignment, model, arithmetic: Arithmetic | None = None) -> WalkerResult

Return each walker's log-likelihood fitness, computed on the device.

states is float32 (M, 4 n_nodes) in the archive's layout, with every walker's leaves in one order, and leaf_rows[k] is the alignment row of leaf k. The device orders each tree, rebuilds its transition matrices in float-float (:func:hifuku.wgsl.pmat.transition_matrices_ff), peels every pattern, multiplies the weighted site values in float-float and forms the fitness from the product. The distance from the CUDA engine's fitness for the same tree is within :func:hifuku.precision.walker_fitness_error, except for a tree that gives a pattern the likelihood zero. Both engines then floor the scaled site likelihood, but they scale it differently, so the floored values differ by design.

Raises:

Type Description
ValueError

If the tree has fewer than three leaves, if leaf_rows does not hold one row per leaf, if one walker's partials or matrices need more than the storage limit of the device, or if an exponent of a walker's product passes the limit of the kernel.

Source code in src/hifuku/wgsl/walker.py
def walker_fitness(states: np.ndarray, leaf_rows: np.ndarray, alignment, model,
                   arithmetic: Arithmetic | None = None) -> WalkerResult:
    """Return each walker's log-likelihood fitness, computed on the device.

    ``states`` is float32 ``(M, 4 n_nodes)`` in the archive's layout, with
    every walker's leaves in one order, and ``leaf_rows[k]`` is the alignment
    row of leaf ``k``.  The device orders each tree, rebuilds its transition
    matrices in float-float (:func:`hifuku.wgsl.pmat.transition_matrices_ff`),
    peels every pattern, multiplies the weighted site values in float-float
    and forms the fitness from the product.  The distance from the CUDA
    engine's fitness for the same tree is within
    :func:`hifuku.precision.walker_fitness_error`, except for a tree that
    gives a pattern the likelihood zero.  Both engines then floor the scaled
    site likelihood, but they scale it differently, so the floored values
    differ by design.

    Raises
    ------
    ValueError
        If the tree has fewer than three leaves, if ``leaf_rows`` does not
        hold one row per leaf, if one walker's partials or matrices need more
        than the storage limit of the device, or if an exponent of a walker's
        product passes the limit of the kernel.
    """
    if arithmetic is None:
        from hifuku.wgsl.likelihood import choose_arithmetic
        arithmetic = choose_arithmetic()
    states = np.ascontiguousarray(states, dtype=np.float32)
    M, n_nodes = states.shape[0], states.shape[1] // 4
    n_leaves = (n_nodes + 1) // 2
    if n_leaves < 3:
        raise ValueError(f"a tree of {n_leaves} leaves has no internal node to peel.")
    leaf_rows = np.asarray(leaf_rows)
    if leaf_rows.shape != (n_leaves,):
        raise ValueError(f"leaf_rows holds {leaf_rows.size} rows; a tree of {n_leaves} "
                         f"leaves needs one row per leaf.")
    if M == 0:
        return WalkerResult(np.zeros(0, np.float32), np.zeros((0, 2), np.float32),
                            np.zeros(0, np.int32))
    S = model.n_states
    codes = alignment.patterns[leaf_rows]
    n_patterns = codes.shape[1]
    inputs = _inputs(codes, alignment.weights, model.freqs)
    orders = walker_orders(states, n_leaves)
    # The root's length is not an edge; its matrix is never read.
    lengths = states[:, 3 * n_nodes:].copy()
    lengths[:, n_nodes - 1] = 0.0
    per_partials = max(n_leaves - 2, 1) * S * n_patterns * 4
    per_matrices = n_nodes * S * S * 4
    limit = storage_limit()
    fit = min(limit // per_partials, limit // per_matrices)
    if fit < 1:
        raise ValueError(
            f"one walker of a {n_leaves}-taxon tree and {n_patterns} patterns needs "
            f"{max(per_partials, per_matrices)} bytes in one binding, more than the "
            f"storage limit of {limit} bytes of the device.")
    most = min(fit, workgroup_limit())
    source = peel_source(n_leaves, n_nodes, n_patterns, S, arithmetic)
    pieces = []
    for first in range(0, M, most):
        count = min(most, M - first)
        pmat = transition_matrices_ff(model, lengths[first:first + count].ravel(), arithmetic)
        raw = run_kernel(source, [inputs.words, orders[first:first + count].ravel(),
                                  pmat.ravel()],
                         _OUT.itemsize * count, count, arithmetic,
                         scratch=(per_partials * count,), name="walker peel")
        pieces.append(np.frombuffer(raw, dtype=_OUT))
    out = np.concatenate(pieces)
    flagged = np.flatnonzero(out["flag"])
    if flagged.size:
        raise ValueError(
            f"walker {int(flagged[0])}: an exponent of its likelihood product passed "
            f"{WGSL_PRODUCT_EXPONENT_LIMIT} in magnitude, beyond which the kernel's "
            f"integer sums can overflow.")
    return WalkerResult(out["fitness"].copy(),
                        np.stack([out["hi"], out["lo"]], axis=1),
                        out["exponent"].copy())

walker_orders

walker_orders(states: ndarray, n_leaves: int) -> np.ndarray

Return each walker's post-order, computed on the device.

states is float32 (M, 4 n_nodes). The result is int32 (M, n_leaves - 1, 3): rows (node, left, right), non-root internal nodes first and the root last, in the order of the CUDA walk's depth-first search.

Raises:

Type Description
ValueError

If one walker's state needs more than the storage limit of the device.

Source code in src/hifuku/wgsl/walker.py
def walker_orders(states: np.ndarray, n_leaves: int) -> np.ndarray:
    """Return each walker's post-order, computed on the device.

    ``states`` is float32 ``(M, 4 n_nodes)``.  The result is int32
    ``(M, n_leaves - 1, 3)``: rows ``(node, left, right)``, non-root internal
    nodes first and the root last, in the order of the CUDA walk's
    depth-first search.

    Raises
    ------
    ValueError
        If one walker's state needs more than the storage limit of the
        device.
    """
    states = np.ascontiguousarray(states, dtype=np.float32)
    M, n_nodes = states.shape[0], states.shape[1] // 4
    source = traversal_source(n_leaves, n_nodes)
    rows = (n_leaves - 1) * 3
    pieces = []
    # The state row is the largest binding per walker: 4 n_nodes float32
    # values, against 2 n_nodes int32 stack entries and the order rows.
    per_walker = 16 * n_nodes
    fit = storage_limit() // per_walker
    if fit < 1:
        raise ValueError(f"one walker of {n_nodes} nodes needs {per_walker} bytes in one "
                         f"binding, more than the storage limit of {storage_limit()} "
                         f"bytes of the device.")
    # One invocation per walker, and one dispatch holds at most
    # workgroup_limit() groups of WGSL_WORKGROUP_SIZE invocations.
    most = min(fit, workgroup_limit() * WGSL_WORKGROUP_SIZE)
    for first in range(0, M, most):
        part = states[first:first + most]
        raw = run_kernel(source, [part], 4 * rows * len(part),
                         -(-len(part) // WGSL_WORKGROUP_SIZE),
                         scratch=(8 * n_nodes * len(part),), name="walker orders")
        pieces.append(np.frombuffer(raw, dtype=np.int32))
    if not pieces:
        return np.zeros((0, n_leaves - 1, 3), dtype=np.int32)
    return np.concatenate(pieces).reshape(M, n_leaves - 1, 3)

WalkerResult dataclass

The device's fitness of each walker, and the product it came from.

fitness is float32 (M,). product is float32 (M, 2), the high part in [1/2, 1) and the low part, and exponent is int32 (M,), so that the likelihood is (hi + lo) 2^exponent.

Source code in src/hifuku/wgsl/walker.py
@dataclass(frozen=True)
class WalkerResult:
    """The device's fitness of each walker, and the product it came from.

    ``fitness`` is float32 ``(M,)``.  ``product`` is float32 ``(M, 2)``, the
    high part in [1/2, 1) and the low part, and ``exponent`` is int32
    ``(M,)``, so that the likelihood is ``(hi + lo) 2^exponent``.
    """

    fitness: np.ndarray
    product: np.ndarray
    exponent: np.ndarray

    @property
    def log_likelihood(self) -> np.ndarray:
        """The log of the product, formed on the host in float64."""
        mantissa = self.product[:, 0].astype(np.float64) + self.product[:, 1].astype(np.float64)
        return np.log(mantissa) + self.exponent.astype(np.float64) * math.log(2.0)

log_likelihood property

log_likelihood: ndarray

The log of the product, formed on the host in float64.

walker_fitness_error

walker_fitness_error(n_leaves: int, n_states: int, kind: str, weights, magnitudes, workgroup: int, matrix_shift: float, cuda_threads: int = _N_THREADS) -> float

Return the distance allowed between a walker's WGSL and CUDA fitness.

Both are float32 values for the same tree. kind is the precision of the partials that bounds both engines' pruning (the coarser of the two), magnitudes[p] bounds the magnitude of pattern p's log-likelihood, and matrix_shift bounds the log shift that the difference of the two engines' transition matrices causes in the total. The CUDA engine adds its weighted pattern terms in a chain per thread and then by a tree of cuda_threads sums.

Derived in docs/theory/algebra/joldes2017tight-higham2002accuracy-walker-fitness.py. Higham (2002) : Lemma 3.1; eq. (3.5); w3c2026wgsl (section 15.7.4.1).

Source code in src/hifuku/precision.py
def walker_fitness_error(n_leaves: int, n_states: int, kind: str, weights, magnitudes,
                         workgroup: int, matrix_shift: float,
                         cuda_threads: int = _N_THREADS) -> float:
    """Return the distance allowed between a walker's WGSL and CUDA fitness.

    Both are float32 values for the same tree.  ``kind`` is the precision of
    the partials that bounds both engines' pruning (the coarser of the two),
    ``magnitudes[p]`` bounds the magnitude of pattern ``p``'s log-likelihood,
    and ``matrix_shift`` bounds the log shift that the difference of the two
    engines' transition matrices causes in the total.  The CUDA engine adds
    its weighted pattern terms in a chain per thread and then by a tree of
    ``cuda_threads`` sums.

    Derived in
    docs/theory/algebra/joldes2017tight-higham2002accuracy-walker-fitness.py.
    Higham (2002) : Lemma 3.1; eq. (3.5); w3c2026wgsl
    (section 15.7.4.1).
    """
    weights = np.asarray(weights, dtype=np.float64)
    magnitudes = np.asarray(magnitudes, dtype=np.float64)
    total = float(np.dot(weights, magnitudes))
    pruning = 2.0 * sum(w * pruning_log_error(n_leaves, n_states, kind, m)
                        for w, m in zip(weights, magnitudes))
    count = 1 + math.ceil(len(weights) / cuda_threads) + math.ceil(math.log2(cuda_threads))
    cuda_sum = _gamma(count, UNIT_ROUNDOFF["float64"]) * total
    bound = (pruning + matrix_shift + walker_product_log_error(weights, workgroup)
             + fitness_log_error(total) + cuda_sum)
    # Half a float32 unit of each fitness.
    return bound + float(np.spacing(np.float32(total + bound)))

walker_product_log_error

walker_product_log_error(weights, workgroup: int) -> float

Return a bound, in log, on the error of one walker's device product.

One workgroup multiplies the weighted site values of all of a walker's patterns: each invocation keeps a running product over its patterns, and the workgroup reduces the workgroup running products by a tree. The product carries at most sum w_p + workgroup - 1 factors of the error of one float-float product.

Derived in docs/theory/algebra/joldes2017tight-higham2002accuracy-walker-fitness.py, item 1. Muller & Rideau (2022) : Theorems 2.7 and 2.8; knuth1997seminumerical (section 4.6.3, Algorithm A).

Source code in src/hifuku/precision.py
def walker_product_log_error(weights, workgroup: int) -> float:
    """Return a bound, in log, on the error of one walker's device product.

    One workgroup multiplies the weighted site values of all of a walker's
    patterns: each invocation keeps a running product over its patterns, and
    the workgroup reduces the ``workgroup`` running products by a tree.  The
    product carries at most ``sum w_p + workgroup - 1`` factors of the error
    of one float-float product.

    Derived in
    docs/theory/algebra/joldes2017tight-higham2002accuracy-walker-fitness.py,
    item 1.  Muller & Rideau (2022) : Theorems 2.7 and 2.8;
    knuth1997seminumerical (section 4.6.3, Algorithm A).
    """
    per_product = math.expm1(math.log1p(FF_MUL_RELATIVE_ERROR)
                             + math.log1p(2.0 * FF_LOW_PART_MIN))
    count = float(np.sum(weights)) + workgroup - 1
    return -math.log1p(-math.expm1(count * math.log1p(per_product)))

fitness_log_error

fitness_log_error(magnitude: float) -> float

Return a bound on the error of log(m) + E ln 2 before its rounding.

The device forms a walker's fitness from its product m 2^E, m in [1/2, 1), as WGSL's float32 log of the high part of m plus E ln 2 in float-float. magnitude is a bound on the magnitude of the log-likelihood, so that |E| ln 2 <= magnitude + ln 2.

Derived in docs/theory/algebra/joldes2017tight-higham2002accuracy-walker-fitness.py, items 2 and 3. w3c2026wgsl : section 15.7.4.1, log; joldes2017tight; muller2022formalization.

Source code in src/hifuku/precision.py
def fitness_log_error(magnitude: float) -> float:
    """Return a bound on the error of ``log(m) + E ln 2`` before its rounding.

    The device forms a walker's fitness from its product ``m 2^E``, ``m`` in
    [1/2, 1), as WGSL's float32 ``log`` of the high part of ``m`` plus
    ``E ln 2`` in float-float.  ``magnitude`` is a bound on the magnitude of
    the log-likelihood, so that ``|E| ln 2 <= magnitude + ln 2``.

    Derived in
    docs/theory/algebra/joldes2017tight-higham2002accuracy-walker-fitness.py,
    items 2 and 3.  w3c2026wgsl : section 15.7.4.1, log;
    joldes2017tight; muller2022formalization.
    """
    exponent_term = magnitude + math.log(2.0)
    # E ln 2 is formed from E_hi, a multiple of 2^12, and E_lo < 2^12.
    return (2.0 ** -21 + 2.0 ** -23
            + (FF_MUL_RELATIVE_ERROR + _FF_SPLIT_ERROR) * (exponent_term + 2.0 ** 13 * math.log(2.0))
            + FF_ADD_RELATIVE_ERROR * exponent_term
            + FF_ADD_RELATIVE_ERROR * (exponent_term + 1.0))

Walker placement

The CUDA walk reads each walker against its chart's three anchors after every move and places it on the chart. walker_placement does the same on a WebGPU device, from the archive's walker states. One kernel takes one workgroup per walker. For each anchor it runs the masked post-order sweep that keys each split of the walker restricted to the shared taxa and adds each run of merged edges in float32, as the CUDA sweep does. It then searches the anchor's sorted split keys, adds the branch-score parts A and B in float-float and counts the shared splits. From the parts it forms the squared distance in float-float, then the barycentric coordinates, the residual z and the niche, with the chart's float64 constants split into two float32 parts.

The cosine B / sqrt(A C) and z = sqrt(-c) use ff_rsqrt, a float-float reciprocal square root. It starts from WGSL's inverseSqrt, which the WGSL specification bounds by 2 ULP, and takes two Newton steps. Its bound, ff_rsqrt_error, holds for arguments in [2^-60, 2^100].

The precision kind of this reading is "float-float". z_squared_tolerance and lambda_tolerance bound how far two readings put z^2 and each barycentric coordinate. Both devices add the runs and read the anchors' lengths in float32, and that rounding sets the bound of each device against the exact value. Float-float arithmetic does not reduce that bound below the float32 kind's. docs/theory/algebra/higham2002accuracy-kuhner1994-residual-rounding.py derives the bounds. The walker_placement workload of scripts/bench.py times the placement.

walker_placement

walker_placement(states: ndarray, chart: ChartData, arithmetic: Arithmetic | None = None) -> Placement

Return each walker's place on the chart, computed on the device.

The squared distances, the barycentric coordinates and z are float-float values; z is zero where -c is below the lower end of FF_RSQRT_DOMAIN, 2^-60. The niche is floor((lambda - origin) / cell) with the quotient taken as a product by the split value of 1 / cell, which can differ from the CUDA engine's division only at a cell edge. A walker whose restricted squared split lengths sum below 2^-100 counts as having a cosine of zero. The distance of z^2 and of each coordinate from the host's reading is within :func:hifuku.precision.z_squared_tolerance and :func:hifuku.precision.lambda_tolerance of the kind "float-float".

Raises:

Type Description
ValueError

If chart has no placement constants (it was made without a triangle), or if one walker's state needs more than the storage limit of the device.

Source code in src/hifuku/wgsl/placement.py
def walker_placement(states: np.ndarray, chart: ChartData,
                     arithmetic: Arithmetic | None = None) -> Placement:
    """Return each walker's place on the chart, computed on the device.

    The squared distances, the barycentric coordinates and z are float-float
    values; ``z`` is zero where ``-c`` is below the lower end of
    ``FF_RSQRT_DOMAIN``, 2^-60.  The niche is ``floor((lambda - origin) / cell)``
    with the quotient taken as a product by the split value of ``1 / cell``,
    which can differ from the CUDA engine's division only at a cell edge.  A
    walker whose restricted squared split lengths sum below 2^-100 counts as
    having a cosine of zero.  The distance of ``z^2``
    and of each coordinate from the host's reading is within
    :func:`hifuku.precision.z_squared_tolerance` and
    :func:`hifuku.precision.lambda_tolerance` of the kind ``"float-float"``.

    Raises
    ------
    ValueError
        If ``chart`` has no placement constants (it was made without a
        triangle), or if one walker's state needs more than the storage limit
        of the device.
    """
    if chart.chart is None:
        raise ValueError("the chart data hold no triangle, so no placement follows; "
                         "make them with chart_data(..., triangle).")
    words = _run(states, chart, arithmetic)
    anchors = np.ascontiguousarray(words[:, :24]).reshape(len(words), 3, 8)
    s2 = _ff64(anchors[:, :, 6:8])
    flat = words[:, OUT_NICHE].view(np.int32).astype(np.int64)
    n_side, n_off = chart.chart["n_side"], chart.chart["n_off"]
    niche = np.stack([flat // n_side - n_off, flat % n_side - n_off], axis=1)
    niche[flat == chart.chart["sink"]] = np.iinfo(np.int64).min
    return Placement(_ff64(words[:, OUT_LAMBDA1:OUT_LAMBDA1 + 2]),
                     _ff64(words[:, OUT_LAMBDA2:OUT_LAMBDA2 + 2]),
                     _ff64(words[:, OUT_Z:OUT_Z + 2]),
                     s2, niche)

anchor_parts

anchor_parts(states: ndarray, chart: ChartData, arithmetic: Arithmetic | None = None) -> AnchorParts

Return each walker's branch-score parts against the chart's anchors.

states is float32 (M, 4 n_nodes) in the archive's layout, with every walker's leaves in the order of the tree chart was made for. The runs are float32 sums, as on the CUDA device, and A and B are float-float sums.

Raises:

Type Description
ValueError

If one walker's state needs more than the storage limit of the device.

Source code in src/hifuku/wgsl/placement.py
def anchor_parts(states: np.ndarray, chart: ChartData,
                 arithmetic: Arithmetic | None = None) -> AnchorParts:
    """Return each walker's branch-score parts against the chart's anchors.

    ``states`` is float32 ``(M, 4 n_nodes)`` in the archive's layout, with
    every walker's leaves in the order of the tree ``chart`` was made for.
    The runs are float32 sums, as on the CUDA device, and A and B are
    float-float sums.

    Raises
    ------
    ValueError
        If one walker's state needs more than the storage limit of the device.
    """
    words = _run(states, chart, arithmetic)
    rows = np.ascontiguousarray(words[:, :24]).reshape(len(words), 3, 8)
    as_float = rows.view(np.float32)
    return AnchorParts(as_float[:, :, 0:2].copy(), as_float[:, :, 2:4].copy(),
                       rows[:, :, 4].view(np.int32).copy(), rows[:, :, 5].view(np.int32).copy())

chart_data

chart_data(walk_tree, anchors, triangle=None, cell: float = ARCHIVE_CELL, origin: float = 0.0, extent: float = ARCHIVE_GPU_EXTENT) -> ChartData

Return the chart data of three anchors for walkers shaped like walk_tree.

walk_tree gives the leaf order of the walker states, with its global taxon indices set, as :func:hifuku.gpu_walk.evaluate_gpu prepares it. The tables come from the host functions the CUDA engine uses. With triangle, the chart of the three anchors, the data also hold the placement constants and the niche grid of cell, origin and extent, as evaluate_gpu takes them.

Source code in src/hifuku/wgsl/placement.py
def chart_data(walk_tree, anchors, triangle=None, cell: float = ARCHIVE_CELL,
               origin: float = 0.0, extent: float = ARCHIVE_GPU_EXTENT) -> ChartData:
    """Return the chart data of three anchors for walkers shaped like ``walk_tree``.

    ``walk_tree`` gives the leaf order of the walker states, with its global
    taxon indices set, as :func:`hifuku.gpu_walk.evaluate_gpu` prepares it.
    The tables come from the host functions the CUDA engine uses.  With
    ``triangle``, the chart of the three anchors, the data also hold the
    placement constants and the niche grid of ``cell``, ``origin`` and
    ``extent``, as ``evaluate_gpu`` takes them.
    """
    from hifuku.chain_tree import _anchor_reference
    tables = []
    for anchor in anchors:
        split_ref, leaf_value, n_shared = _anchor_reference(walk_tree, anchor)
        if not FF_RSQRT_DOMAIN[0] <= float(split_ref.C) <= FF_RSQRT_DOMAIN[1]:
            raise ValueError(
                f"an anchor's sum of squared split lengths is {float(split_ref.C)!r}, "
                f"outside [{FF_RSQRT_DOMAIN[0]!r}, {FF_RSQRT_DOMAIN[1]!r}], the domain "
                f"of the float-float reciprocal square root the placement uses.")
        tables.append(AnchorTable(np.asarray(split_ref.ref_hashes, dtype=np.uint64),
                                  np.asarray(split_ref.ref_lengths, dtype=np.float32),
                                  np.asarray(leaf_value, dtype=np.uint64),
                                  float(split_ref.C), int(n_shared)))
    if triangle is None:
        return ChartData(tuple(tables))
    from hifuku.anchor_triangle import trilateration_arrays
    from hifuku.walk_state import bin_frame, device_grid
    A_inv, M_bary, rhs_off, P3 = trilateration_arrays(triangle)
    n_off, n_side, _grid_lo, sink = device_grid(cell, origin, extent)
    bin_origin, bin_offset = bin_frame(origin, n_off)
    w = float(triangle.tree_metric.w)
    chart = {"w": w, "A_inv": A_inv, "M_bary": M_bary, "rhs_off": rhs_off, "P3": P3,
             "cell": float(cell), "bin_origin": bin_origin, "bin_offset": bin_offset,
             "n_off": n_off, "n_side": n_side, "sink": sink}
    return ChartData(tuple(tables), chart)

rsqrt_source

rsqrt_source(arithmetic: Arithmetic) -> str

Return the WGSL source of the float-float reciprocal square root.

It holds the float-float library of arithmetic, the step count and ff_rsqrt. A kernel calls ff_prelude() first.

Source code in src/hifuku/wgsl/library.py
def rsqrt_source(arithmetic: Arithmetic) -> str:
    """Return the WGSL source of the float-float reciprocal square root.

    It holds the float-float library of ``arithmetic``, the step count and
    ``ff_rsqrt``.  A kernel calls ``ff_prelude()`` first.
    """
    constants = f"const FF_RSQRT_NEWTON_STEPS: u32 = {FF_RSQRT_NEWTON_STEPS}u;\n"
    return (wgsl_source(arithmetic) + "\n" + constants
            + (files("hifuku.wgsl") / "ff_rsqrt.wgsl").read_text(encoding="utf-8"))

ff_rsqrt_error

ff_rsqrt_error() -> float

Return a relative bound on the WGSL float-float reciprocal square root.

For a float-float x in FF_RSQRT_DOMAIN, [2^-60, 2^100], the computed value lies within ff_rsqrt_error() / sqrt(x) of 1 / sqrt(x). The start is WGSL's inverseSqrt, with an error of at most 2 ULP, and each of FF_RSQRT_NEWTON_STEPS Newton steps squares the relative error and adds the rounding of its float-float operations. A device that flushes a subnormal low part of x or of the result adds a fixed term.

Derived in docs/theory/algebra/w3c2026wgsl-joldes2017tight-ff-rsqrt.py. w3c2026wgsl : section 15.7.4.1, inverseSqrt; joldes2017tight; muller2022formalization.

Source code in src/hifuku/precision.py
def ff_rsqrt_error() -> float:
    """Return a relative bound on the WGSL float-float reciprocal square root.

    For a float-float ``x`` in ``FF_RSQRT_DOMAIN``, [2^-60, 2^100], the computed value lies within
    ``ff_rsqrt_error() / sqrt(x)`` of ``1 / sqrt(x)``.  The start is WGSL's
    ``inverseSqrt``, with an error of at most 2 ULP, and each of
    ``FF_RSQRT_NEWTON_STEPS`` Newton steps squares the relative error and adds
    the rounding of its float-float operations.  A device that flushes a
    subnormal low part of ``x`` or of the result adds a fixed term.

    Derived in docs/theory/algebra/w3c2026wgsl-joldes2017tight-ff-rsqrt.py.
    w3c2026wgsl : section 15.7.4.1, inverseSqrt; joldes2017tight;
    muller2022formalization.
    """
    em, ea = FF_MUL_RELATIVE_ERROR, FF_ADD_RELATIVE_ERROR
    rho_q = (1.0 + em) ** 2 - 1.0
    e = (1.0 + 2.0 * 2.0 ** -23 * math.sqrt(2.0)) * (1.0 + 2.0 ** -24 * (1.0 + 2.0 ** -22)) - 1.0
    for _ in range(FF_RSQRT_NEWTON_STEPS):
        d = 2.0 * e + e * e + rho_q * (1.0 + e) ** 2 * (1.0 + ea)
        rounding = ((1.0 + e) / 2.0 * (rho_q * (1.0 + e) ** 2 + ea * d)
                    + em * (1.0 + e) * d + ea * (1.0 + e) * (1.0 + d))
        e = 1.5 * e * e + 0.5 * e ** 3 + rounding
    # A flushed low part of x, relative to the smallest x of the domain, and of
    # the result, relative to the smallest result.
    low, high = FF_RSQRT_DOMAIN
    t = 2.0 ** -126 / low
    flush = t * (1.0 + t) / 2.0 + 2.0 ** -126 * math.sqrt(2.0 * high)
    return e + flush

lambda_tolerance

lambda_tolerance(tree, triangle, taxon_table, first: str, second: str) -> tuple[np.ndarray, float]

Return a float64 reading of (lambda1, lambda2) for tree, and a bound on how far two readings made at the precisions first and second can put either coordinate.

The readings are those of :func:z_squared_tolerance, and the bound is the sum of the two readings' distances from the exact coordinates.

Raises:

Type Description
ValueError

For the reasons of :func:z_squared_tolerance.

Higham (2002), kuhner1994branch, robinson1981rf.
Source code in src/hifuku/precision.py
def lambda_tolerance(tree, triangle, taxon_table, first: str,
                     second: str) -> tuple[np.ndarray, float]:
    """Return a float64 reading of ``(lambda1, lambda2)`` for ``tree``, and a bound
    on how far two readings made at the precisions ``first`` and ``second`` can
    put either coordinate.

    The readings are those of :func:`z_squared_tolerance`, and the bound is the
    sum of the two readings' distances from the exact coordinates.

    Raises
    ------
    ValueError
        For the reasons of :func:`z_squared_tolerance`.

    Higham (2002), kuhner1994branch, robinson1981rf.
    """
    from hifuku.anchor_triangle import barycentric_from_squared
    from hifuku.archive import _set_global_leaf_indices

    coarser(first, second)
    _set_global_leaf_indices(tree, taxon_table)
    anchors = (triangle.r1, triangle.r2, triangle.r3)
    for anchor in anchors:
        _set_global_leaf_indices(anchor, taxon_table)
    w = float(triangle.tree_metric.w)
    readings = [_anchor_reading(tree, anchor, w) for anchor in anchors]
    errors = {kind: [_squared_distance_error(r, kind) for r in readings]
              for kind in FLOAT_TYPES}
    lambdas, _z = barycentric_from_squared(*(r["s2"] for r in readings), triangle)
    bound = sum(_lambda_error(readings, triangle, errors[kind], errors["float64"], kind)
                for kind in (first, second))
    return np.asarray(lambdas[:2], dtype=np.float64), bound

z_squared_tolerance

z_squared_tolerance(tree, triangle, taxon_table, first: str, second: str) -> tuple[float, float]

Return a float64 reading of z^2 for tree, and a bound on how far two readings made at the precisions first and second can differ.

A float32 reading is the device engine's. It adds each run of merged edges in float32 and reads the anchors' split lengths rounded to float32. A float64 reading is the host engine's. It works in float64 and forms its sums with Python's compensated sum. Both engines then place the tree with the closed form in :func:hifuku.anchor_triangle.barycentric_from_squared. A float-float reading is the WGSL engine's. It adds the runs and reads the anchors as the CUDA engine does, and forms the sums, the cosine and the closed form in float-float.

The bound is the sum of the two readings' distances from the exact value, so it also bounds the distance of either reading from the returned one. Each step follows the derivation in docs/theory/algebra/higham2002accuracy-kuhner1994-residual-rounding.py. Such a bound usually exceeds the actual difference by orders of magnitude, so a test on it detects a disagreement that rounding cannot explain.

Parameters:

Name Type Description Default
tree HifukuTree

The tree both readings are of.

required
triangle AnchorTriangle

The chart, with its anchors and its metric weight.

required
taxon_table TaxonTable

The namespace the tree and the anchors are read in.

required
first str

The recorded precisions of the two readings.

required
second str

The recorded precisions of the two readings.

required

Returns:

Type Description
(z2, bound) : (float, float)

Raises:

Type Description
ValueError

If a precision is unrecorded or unknown, if the tree cannot be measured against an anchor, or if a sum is too long for the compensated-sum bound.

Higham (2002), kuhner1994branch, robinson1981rf.
Source code in src/hifuku/precision.py
def z_squared_tolerance(tree, triangle, taxon_table, first: str,
                        second: str) -> tuple[float, float]:
    """Return a float64 reading of ``z^2`` for ``tree``, and a bound on how far
    two readings made at the precisions ``first`` and ``second`` can differ.

    A float32 reading is the device engine's.  It adds each run of merged edges
    in float32 and reads the anchors' split lengths rounded to float32.  A
    float64 reading is the host engine's.  It works in float64 and forms its
    sums with Python's compensated ``sum``.  Both engines then place the tree
    with the closed form in :func:`hifuku.anchor_triangle.barycentric_from_squared`.
    A float-float reading is the WGSL engine's.  It adds the runs and reads
    the anchors as the CUDA engine does, and forms the sums, the cosine and the
    closed form in float-float.

    The bound is the sum of the two readings' distances from the exact value, so
    it also bounds the distance of either reading from the returned one.  Each
    step follows the derivation in
    ``docs/theory/algebra/higham2002accuracy-kuhner1994-residual-rounding.py``.
    Such a bound usually exceeds the actual difference by orders of magnitude,
    so a test on it detects a disagreement that rounding cannot explain.

    Parameters
    ----------
    tree : HifukuTree
        The tree both readings are of.
    triangle : AnchorTriangle
        The chart, with its anchors and its metric weight.
    taxon_table : TaxonTable
        The namespace the tree and the anchors are read in.
    first, second : str
        The recorded precisions of the two readings.

    Returns
    -------
    (z2, bound) : (float, float)

    Raises
    ------
    ValueError
        If a precision is unrecorded or unknown, if the tree cannot be measured
        against an anchor, or if a sum is too long for the compensated-sum bound.

    Higham (2002), kuhner1994branch, robinson1981rf.
    """
    from hifuku.anchor_triangle import barycentric_from_squared
    from hifuku.archive import _set_global_leaf_indices

    coarser(first, second)
    _set_global_leaf_indices(tree, taxon_table)
    anchors = (triangle.r1, triangle.r2, triangle.r3)
    for anchor in anchors:
        _set_global_leaf_indices(anchor, taxon_table)
    w = float(triangle.tree_metric.w)
    readings = [_anchor_reading(tree, anchor, w) for anchor in anchors]

    errors = {kind: [_squared_distance_error(r, kind) for r in readings]
              for kind in FLOAT_TYPES}
    _lambdas, z = barycentric_from_squared(
        *(r["s2"] for r in readings), triangle)
    bound = sum(_residual_squared_error(readings, triangle, errors[kind],
                                        errors["float64"], kind)
                for kind in (first, second))
    return z * z, bound

Walker moves

walk_moves applies the CUDA walk's moves to walker states on a WebGPU device, one invocation per walker and K steps in sequence, as thread 0 of the CUDA walk does. Each step draws the move kind from the walker's xoroshiro128+ generator. It then applies a prune-regraft with uniform prune and graft selection, a nearest-neighbor interchange, a branch slide or a branch scale, and rebuilds the post-order and the leaf counts. From the same parents and generator states, the topology of every step and the generator stream are bit-identical to the CUDA walk's. The CUDA walk's float64 sum of two merged lengths and its comparison with the minimum split length are reproduced exactly.

The slide's normal draw and the scale factor are the floating-point outcomes. normal_f32 draws by Box-Muller in float32 and reduces the angle to [-pi, pi], where the WGSL specification states the accuracy of cos. scale_factor computes the exponential in float-float. normal_draw_error bounds the distance between the two walks' normal draws, and scale_factor_band the band in which their scale factors can round apart. A fixed-seed WGSL walk therefore follows the CUDA walk exactly up to its first slide or scale.

hifuku.gpu_walk.walk_gpu runs the CUDA walk kernel from given trees and generator states, and is the reference for these comparisons. The walker_moves workload of scripts/bench.py times the moves.

walk_moves

walk_moves(states: ndarray, rng_states: ndarray, K: int, params, arithmetic: Arithmetic | None = None) -> MoveResult

Apply K moves to each walker on the device, as the CUDA walk does.

states is float32 (M, 4 n_nodes) in the archive's layout, with the root at node n_nodes - 1. rng_states is each walker's xoroshiro128+ state, uint64 (M, 2), s0 then s1. params gives the move mix, the slide's step and the scale width, as an :class:hifuku.params.ArchiveParams does. From the same states and generator words the topology of every step is bit-identical to the CUDA walk's; the lengths a slide or a scale writes agree within the bounds of :func:hifuku.precision.normal_draw_error and :func:hifuku.precision.scale_factor_band.

Raises:

Type Description
ValueError

If one walker's output or scratch needs more than the storage limit of the device, or if the scale width exceeds 1.

Source code in src/hifuku/wgsl/moves.py
def walk_moves(states: np.ndarray, rng_states: np.ndarray, K: int, params,
               arithmetic: Arithmetic | None = None) -> MoveResult:
    """Apply ``K`` moves to each walker on the device, as the CUDA walk does.

    ``states`` is float32 ``(M, 4 n_nodes)`` in the archive's layout, with the
    root at node ``n_nodes - 1``.  ``rng_states`` is each walker's
    xoroshiro128+ state, uint64 ``(M, 2)``, ``s0`` then ``s1``.  ``params``
    gives the move mix, the slide's step and the scale width, as an
    :class:`hifuku.params.ArchiveParams` does.  From the same states and
    generator words the topology of every step is bit-identical to the CUDA
    walk's; the lengths a slide or a scale writes agree within the bounds of
    :func:`hifuku.precision.normal_draw_error` and
    :func:`hifuku.precision.scale_factor_band`.

    Raises
    ------
    ValueError
        If one walker's output or scratch needs more than the storage limit
        of the device, or if the scale width exceeds 1.
    """
    if arithmetic is None:
        from hifuku.wgsl.likelihood import choose_arithmetic
        arithmetic = choose_arithmetic()
    states = np.ascontiguousarray(states, dtype=np.float32)
    M, n_nodes = states.shape[0], states.shape[1] // 4
    n_leaves = (n_nodes + 1) // 2
    _check_states(states, n_leaves)
    words = np.asarray(rng_states, dtype=np.uint64)
    if words.shape != (M, 2):
        raise ValueError(f"rng_states has shape {words.shape}; {M} walkers need ({M}, 2).")
    rng = np.ascontiguousarray(np.stack([words[:, 0] & 0xFFFFFFFF, words[:, 0] >> 32,
                                         words[:, 1] & 0xFFFFFFFF, words[:, 1] >> 32],
                                        axis=1).astype(np.uint32))
    out_words = _out_words(n_leaves, K)
    per_walker = 4 * max(out_words, _scratch_words(n_leaves), 4 * n_nodes)
    fit = storage_limit() // per_walker
    if fit < 1:
        raise ValueError(f"one walker of {n_nodes} nodes and {K} steps needs {per_walker} "
                         f"bytes in one binding, more than the storage limit of "
                         f"{storage_limit()} bytes.")
    most = min(fit, workgroup_limit() * WGSL_WORKGROUP_SIZE)
    source = moves_source(n_leaves, K, params, arithmetic)
    pieces = []
    for first in range(0, M, most):
        part = states[first:first + most]
        count = len(part)
        raw = run_kernel(source, [part, rng[first:first + count]], 4 * out_words * count,
                         -(-count // WGSL_WORKGROUP_SIZE), arithmetic,
                         scratch=(4 * _scratch_words(n_leaves) * count,), name="walker moves")
        pieces.append(np.frombuffer(raw, dtype=np.uint32).reshape(count, out_words))
    out = np.concatenate(pieces) if pieces else np.zeros((0, out_words), np.uint32)
    steps = out[:, :K * (4 * n_nodes + 8)].reshape(M, K, 4 * n_nodes + 8)
    record = steps[:, :, 4 * n_nodes:].view(np.int32)
    tail = out[:, K * (4 * n_nodes + 8):].astype(np.uint64)
    return MoveResult(state=steps[:, :, :4 * n_nodes].view(np.float32).copy(),
                      move=record[:, :, 0].copy(), n_changed=record[:, :, 1].copy(),
                      changed=record[:, :, 2:5].copy(), flags=record[:, :, 5].copy(),
                      rng_states=np.stack([tail[:, 0] | (tail[:, 1] << np.uint64(32)),
                                           tail[:, 2] | (tail[:, 3] << np.uint64(32))], axis=1))

draws_source

draws_source(arithmetic: Arithmetic, scale_width: float) -> str

Return the WGSL source of the walk's normal draw and scale factor.

It holds the float-float library of arithmetic with ff_expm1, the constants of the draws and draws.wgsl.

A scale width above 1 is halved J times, with 2^J >= w, so that the argument of ff_expm1 stays in its domain, and the factor is squared J times.

Raises:

Type Description
ValueError

If scale_width is negative.

Source code in src/hifuku/wgsl/moves.py
def draws_source(arithmetic: Arithmetic, scale_width: float) -> str:
    """Return the WGSL source of the walk's normal draw and scale factor.

    It holds the float-float library of ``arithmetic`` with ``ff_expm1``, the
    constants of the draws and ``draws.wgsl``.

    A scale width above 1 is halved ``J`` times, with ``2^J >= w``, so that
    the argument of ``ff_expm1`` stays in its domain, and the factor is squared
    ``J`` times.

    Raises
    ------
    ValueError
        If ``scale_width`` is negative.
    """
    if not scale_width >= 0.0:
        raise ValueError(f"the scale width {scale_width!r} is negative.")
    squarings = scale_squarings(scale_width)
    pi_below = float(np.nextafter(np.float32(math.pi), np.float32(0.0)))
    constants = (f"const BOX_MULLER_FLOOR: f32 = {wgsl_f32(float(np.float32(_BOX_MULLER_U_FLOOR)))};\n"
                 f"const TWO_PI: f32 = {wgsl_f32(float(np.float32(2.0 * math.pi)))};\n"
                 f"const PI_BELOW: f32 = {wgsl_f32(pi_below)};\n"
                 f"const SCALE_WIDTH: vec2<f32> = "
                 f"{wgsl_ff(math.ldexp(float(scale_width), -squarings))};\n"
                 f"const SCALE_SQUARINGS: u32 = {squarings}u;\n")
    return (expm1_source(arithmetic) + constants
            + (files("hifuku.wgsl") / "draws.wgsl").read_text(encoding="utf-8"))

walk_gpu

walk_gpu(trees, rng_states, K, r1, r2, r3, alignment, model, triangle, taxon_table, params, cell: float = ARCHIVE_CELL, origin: float = 0.0, extent: float = ARCHIVE_GPU_EXTENT) -> WalkResult

Run the walk kernel for K steps from given parents and generator states.

Walker m starts from trees[m] and the xoroshiro128+ state rng_states[m] (uint64 (M, 2), s0 then s1), and applies K moves with the move mix and step sizes of params, as a survey pass does. The kernel and its arguments are the survey's own; this function prepares them as :func:evaluate_gpu prepares the seed-evaluation kernel's, so that another engine can be checked against a walk step by step. No fitness floor applies.

Source code in src/hifuku/gpu_walk.py
def walk_gpu(trees, rng_states, K, r1, r2, r3, alignment, model, triangle, taxon_table,
             params, cell: float = ARCHIVE_CELL, origin: float = 0.0,
             extent: float = ARCHIVE_GPU_EXTENT) -> WalkResult:
    """Run the walk kernel for ``K`` steps from given parents and generator states.

    Walker ``m`` starts from ``trees[m]`` and the xoroshiro128+ state
    ``rng_states[m]`` (uint64 ``(M, 2)``, ``s0`` then ``s1``), and applies
    ``K`` moves with the move mix and step sizes of ``params``, as a survey
    pass does.  The kernel and its arguments are the survey's own; this
    function prepares them as :func:`evaluate_gpu` prepares the seed-evaluation
    kernel's, so that another engine can be checked against a walk step by
    step.  No fitness floor applies.
    """
    from numba.cuda.random import xoroshiro128p_dtype

    from hifuku.walk_state import EMPTY_FITNESS

    trees = list(trees)
    for t in (r1, r2, r3, *trees):
        _set_global_leaf_indices(t, taxon_table)
    M = len(trees)
    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,
    )
    if np.shape(rng_states) != (M, 2):
        raise ValueError(f"rng_states has shape {np.shape(rng_states)}; {M} walkers need "
                         f"({M}, 2), one state per walker.")
    rng = np.zeros(M, dtype=xoroshiro128p_dtype)
    rng["s0"] = np.asarray(rng_states, dtype=np.uint64)[:, 0]
    rng["s1"] = np.asarray(rng_states, dtype=np.uint64)[:, 1]
    d_rng = cuda.to_device(rng)

    n_nodes, n_leaves = ct.n_nodes, ct.n_leaves
    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)
    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()
    parents = np.stack([canonical_flat(flatten_host(hp[m], hlc[m], hrc[m], hedge[m], n_nodes),
                                       n_nodes, n_leaves) for m in range(M)])
    A_inv, Mbary_inv, rhs_off, P3_arr = trilateration_arrays(triangle)
    n_cand = M * K
    out = {"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),
           "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)}
    walk_kernel = _walk_kernel_for(model.n_states)
    walk_kernel[M, _CUDA_BLOCK_SIZE](
        cuda.to_device(np.arange(M, dtype=np.int32)), cuda.to_device(parents),
        cuda.to_device(np.zeros(M, dtype=np.float32)),
        ct.parent, ct.left_child, ct.right_child, ct.edge_len,
        ct.node_order, ct.node_order_pos, ct.subtree_leaf_cnt,
        d_rng,
        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,
        cuda.to_device(model.U.astype(np.float64)),
        cuda.to_device(model.eigvals.astype(np.float64)),
        cuda.to_device(model.inv_sqrt_pi.astype(np.float64)),
        cuda.to_device(model.sqrt_pi.astype(np.float64)),
        cuda.to_device(model.freqs.astype(np.float64)),
        cuda.to_device(alignment.weights.astype(np.float64)),
        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),
        np.float64(triangle.tree_metric.w),
        out["niche"], out["fit"], out["z"], out["state"],
        out["move"], out["flag"], out["parent_fit"],
        np.int32(K), np.int32(n_leaves), np.int32(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(cell),
        np.int32(n_side), np.int32(sink), np.float32(EMPTY_FITNESS),
        np.float64(-np.inf),
    )
    cuda.synchronize()
    after = d_rng.copy_to_host()
    return WalkResult(
        parents=parents,
        state=out["state"].copy_to_host().reshape(M, K, sdim),
        move=out["move"].copy_to_host().reshape(M, K),
        fitness=out["fit"].copy_to_host().reshape(M, K),
        niche=out["niche"].copy_to_host().reshape(M, K),
        rng_states=np.stack([after["s0"], after["s1"]], axis=1).astype(np.uint64),
    )

normal_draw_error

normal_draw_error(u1, z_wgsl, z_cuda) -> np.ndarray

Return a bound on the distance between the two walks' normal draws.

For float32 uniforms u1 (and any u2), the WGSL walk's float32 Box-Muller draw z_wgsl and the CUDA walk's z_cuda differ by at most the returned value. The bound reads the two draws only for the rounding of their final products. Arrays broadcast.

Derived in docs/theory/algebra/w3c2026wgsl-higham2002accuracy-walk-draws.py. w3c2026wgsl : section 15.7.4.1; higham2002accuracy (Theorem 2.2).

Source code in src/hifuku/precision.py
def normal_draw_error(u1, z_wgsl, z_cuda) -> np.ndarray:
    """Return a bound on the distance between the two walks' normal draws.

    For float32 uniforms ``u1`` (and any ``u2``), the WGSL walk's float32
    Box-Muller draw ``z_wgsl`` and the CUDA walk's ``z_cuda`` differ by at
    most the returned value.  The bound reads the two draws only for the
    rounding of their final products.  Arrays broadcast.

    Derived in docs/theory/algebra/w3c2026wgsl-higham2002accuracy-walk-draws.py.
    w3c2026wgsl : section 15.7.4.1; higham2002accuracy (Theorem 2.2).
    """
    from hifuku.constants import _BOX_MULLER_U_FLOOR
    u = UNIT_ROUNDOFF["float32"]
    v = UNIT_ROUNDOFF["float64"]
    floor = np.float64(np.float32(_BOX_MULLER_U_FLOOR))
    u1 = np.maximum(np.asarray(u1, dtype=np.float64), floor)
    log_u1 = np.log(u1)
    q = -2.0 * log_u1
    r_c = np.sqrt(q)
    d_log = np.where(u1 >= 0.5, 2.0 ** -21, 3.0 * 2.0 ** -23 * np.abs(log_u1))
    d_q = 2.0 * d_log + 2.0 * v * q
    # sqrt as 1 / inverseSqrt: inverseSqrt within 2 ULP, the division within 2.5.
    sqrt_rel = (1 + 2.5 * 2.0 ** -23) / (1 - 2 * 2.0 ** -23) - 1
    r_w = np.sqrt(q + d_q)
    with np.errstate(divide="ignore", invalid="ignore"):
        lipschitz = np.where(r_c > 0, d_q / r_c, np.inf)
    d_r = np.minimum(lipschitz, np.sqrt(d_q)) + sqrt_rel * r_w + (u + v) * r_c
    d_c = 2.0 ** -11 + math.pi * (2 * u + u * u) + 2.0 ** -22 + u + (4 * math.pi + 3) * v
    return ((1.0 + d_c) * d_r + r_c * d_c
            + u * (np.abs(np.asarray(z_wgsl, np.float64)) + np.abs(np.asarray(z_cuda, np.float64))))

scale_factor_band

scale_factor_band(u: float, w: float) -> float

Return how close to a float32 rounding boundary the two walks' scale factors must lie to round apart.

For a float32 uniform u and a nonnegative scale width w, the CUDA walk's float64 exp((u - 1/2) w) and the WGSL walk's float-float value both lie within the returned distance of the exact factor, so their float32 roundings agree unless a rounding boundary lies that close to it.

Derived in docs/theory/algebra/w3c2026wgsl-higham2002accuracy-walk-draws.py. Higham (2002) : Theorem 2.2; joldes2017tight.

Source code in src/hifuku/precision.py
def scale_factor_band(u: float, w: float) -> float:
    """Return how close to a float32 rounding boundary the two walks' scale
    factors must lie to round apart.

    For a float32 uniform ``u`` and a nonnegative scale width ``w``, the
    CUDA walk's float64 ``exp((u - 1/2) w)`` and the WGSL walk's float-float
    value both lie within the returned distance of the exact factor, so their
    float32 roundings agree unless a rounding boundary lies that close to it.

    Derived in docs/theory/algebra/w3c2026wgsl-higham2002accuracy-walk-draws.py.
    Higham (2002) : Theorem 2.2; joldes2017tight.
    """
    v = UNIT_ROUNDOFF["float64"]
    U = (float(u) - 0.5) * float(w)
    c = math.exp(U)
    relative, absolute = ff_expm1_error()
    cuda = 3.0 * v * c + abs(U) * v * c
    # The base exp(U 2^-J), then J squarings (2^J - 1 product roundings).
    J = scale_squarings(float(w))
    x = math.ldexp(U, -J)
    b = math.exp(x)
    r_b = ((relative * abs(b - 1.0) + absolute
            + (_FF_SPLIT_ERROR + FF_MUL_RELATIVE_ERROR) * abs(x) * b) / b
           + FF_ADD_RELATIVE_ERROR)
    power = 2 ** J
    wgsl = math.expm1(power * math.log1p(r_b)
                      + (power - 1) * math.log1p(FF_MUL_RELATIVE_ERROR)) * c
    return cuda + wgsl

The likelihood functions

pattern_log_likelihoods

pattern_log_likelihoods(tree, alignment, model, *, p_matrices=None) -> np.ndarray

Return the log-likelihood of each site pattern, computed on the device.

The host takes log(max(L, _SITE_L_FLOOR)) + E log 2 in float64. As in the CPU engine, the floor applies to the scaled value L, so it raises only a scaled likelihood of zero, and a site likelihood far below the floor keeps its value. For a pattern of likelihood zero the two engines give different finite values, because their scales differ.

Returns float64 (n_patterns,).

Raises:

Type Description
ValueError

For the reasons of :func:site_values.

Source code in src/hifuku/wgsl/likelihood.py
def pattern_log_likelihoods(tree, alignment, model, *, p_matrices=None) -> np.ndarray:
    """Return the log-likelihood of each site pattern, computed on the device.

    The host takes ``log(max(L, _SITE_L_FLOOR)) + E log 2`` in float64.  As in
    the CPU engine, the floor applies to the scaled value ``L``, so it raises
    only a scaled likelihood of zero, and a site likelihood far below the
    floor keeps its value.  For a pattern of likelihood zero the two engines
    give different finite values, because their scales differ.

    Returns float64 ``(n_patterns,)``.

    Raises
    ------
    ValueError
        For the reasons of :func:`site_values`.
    """
    values = site_values(tree, alignment, model, p_matrices=p_matrices)
    scaled = np.maximum(values[:, 0].astype(np.float64), _SITE_L_FLOOR)
    return np.log(scaled) + values[:, 1].astype(np.float64) * math.log(2.0)

log_likelihood

log_likelihood(tree, alignment, model, *, arithmetic: Arithmetic | None = None, p_matrices=None) -> float

Return the total log-likelihood, computed on the device.

The pruning kernel gives the site value of each pattern, and the product kernel multiplies the values, raised to the pattern weights, in float-float. The host takes one float64 log per workgroup. When arithmetic is None, :func:choose_arithmetic chooses the variant.

Raises:

Type Description
ValueError

For the reasons of :func:site_values, or if a pattern weight times its exponent could pass the exponent range of the product kernel (:func:run_product).

RuntimeError

If arithmetic is None and no variant passes its self-test on the device (:func:choose_arithmetic).

Source code in src/hifuku/wgsl/likelihood.py
def log_likelihood(tree, alignment, model, *, arithmetic: Arithmetic | None = None,
                   p_matrices=None) -> float:
    """Return the total log-likelihood, computed on the device.

    The pruning kernel gives the site value of each pattern, and the product
    kernel multiplies the values, raised to the pattern weights, in
    float-float.  The host takes one float64 log per workgroup.  When
    ``arithmetic`` is None, :func:`choose_arithmetic` chooses the variant.

    Raises
    ------
    ValueError
        For the reasons of :func:`site_values`, or if a pattern weight times
        its exponent could pass the exponent range of the product kernel
        (:func:`run_product`).
    RuntimeError
        If ``arithmetic`` is None and no variant passes its self-test on the
        device (:func:`choose_arithmetic`).
    """
    arithmetic = arithmetic or choose_arithmetic()
    sites = site_values(tree, alignment, model, p_matrices=p_matrices)
    return weighted_log_product(sites, alignment.weights.astype(np.uint32), arithmetic)

site_values

site_values(tree, alignment, model, *, p_matrices=None, chunk_patterns=None) -> np.ndarray

Return each pattern's scaled site likelihood and its exponent.

Returns float32 (n_patterns, 2). Column 0 holds L and column 1 holds the integer E, so that the site likelihood is L * 2**E. The patterns run in chunks that fit the storage limit of the device, of at most chunk_patterns patterns when it is given. p_matrices replaces the transition matrices of :func:transition_matrices.

Raises:

Type Description
ValueError

If the model does not fit the alignment, a tree leaf is not in the alignment, the transition matrices or the partials of one pattern do not fit the storage limit of the device, or the tree is large enough that an exponent could exceed what an f32 holds exactly.

Source code in src/hifuku/wgsl/likelihood.py
def site_values(tree, alignment, model, *, p_matrices=None, chunk_patterns=None) -> np.ndarray:
    """Return each pattern's scaled site likelihood and its exponent.

    Returns float32 ``(n_patterns, 2)``.  Column 0 holds ``L`` and column 1
    holds the integer ``E``, so that the site likelihood is ``L * 2**E``.  The
    patterns run in chunks that fit the storage limit of the device, of at
    most ``chunk_patterns`` patterns when it is given.  ``p_matrices``
    replaces the transition matrices of :func:`transition_matrices`.

    Raises
    ------
    ValueError
        If the model does not fit the alignment, a tree leaf is not in the
        alignment, the transition matrices or the partials of one pattern
        do not fit the storage limit of the device, or the tree is large
        enough that an exponent could exceed what an f32 holds exactly.
    """
    rows = _leaf_rows(tree, alignment, model)
    P = transition_matrices(tree, model) if p_matrices is None else p_matrices
    codes = alignment.patterns[rows].astype(np.uint32)
    n_patterns = codes.shape[1]
    inner = tree.n_nodes - 1 - tree.n_leaves
    # Each node adds at most _NODE_EXPONENT in magnitude, and the floor of the
    # product input at most _FLOOR_EXPONENT.
    reach = _NODE_EXPONENT * (inner + 1) + _FLOOR_EXPONENT
    if reach >= WGSL_EXPONENT_TRANSFER_LIMIT:
        raise ValueError(
            f"an exponent of a {tree.n_leaves}-taxon tree could reach {reach}, "
            f"past {WGSL_EXPONENT_TRANSFER_LIMIT}, below which an f32 holds every "
            f"integer exactly.")
    per_pattern = max(inner, 1) * model.n_states * 4
    limit = storage_limit()
    pmat = np.ascontiguousarray(P, dtype=np.float32).ravel()
    if pmat.nbytes > limit:
        raise ValueError(
            f"the transition matrices of a {tree.n_leaves}-taxon tree need "
            f"{pmat.nbytes} bytes, more than the storage limit of {limit} bytes "
            f"of the device.")
    fit = limit // per_pattern
    if fit < 1:
        raise ValueError(
            f"the partials of one pattern of a {tree.n_leaves}-taxon tree need "
            f"{per_pattern} bytes, more than the storage limit of {limit} bytes "
            f"of the device.")
    chunk = min(fit, workgroup_limit() * WGSL_WORKGROUP_SIZE,
                chunk_patterns if chunk_patterns else n_patterns)
    code = _source(tree, model)
    order = _order(tree)
    freqs = model.freqs.astype(np.float32)
    out = np.empty((n_patterns, 2), dtype=np.float32)
    for start in range(0, n_patterns, chunk):
        part = np.ascontiguousarray(codes[:, start:start + chunk])
        n = part.shape[1]
        raw = run_kernel(code, [part.ravel(), order, pmat, freqs,
                                np.array([n, inner], dtype=np.uint32)],
                         8 * n, math.ceil(n / WGSL_WORKGROUP_SIZE),
                         scratch=[per_pattern * n])
        out[start:start + n] = np.frombuffer(raw, dtype=np.float32).reshape(n, 2)
    return out

choose_arithmetic

choose_arithmetic(candidates=ARITHMETICS, check=None, rounding=None) -> Arithmetic

Return the first variant whose self-test passes on this device.

check(arithmetic) returns None for a variant that passes, and defaults to :func:self_test. rounding() says whether the device rounds to nearest, and defaults to :func:hifuku.wgsl.device.rounds_to_nearest. A variant whose check raises, for example because the shader does not compile, is skipped. With the defaults, the choice is made once per process.

Raises:

Type Description
RuntimeError

If the device does not round to nearest, which every variant assumes, or if no variant passes. The message names each variant and the reason it failed.

Source code in src/hifuku/wgsl/likelihood.py
def choose_arithmetic(candidates=ARITHMETICS, check=None, rounding=None) -> Arithmetic:
    """Return the first variant whose self-test passes on this device.

    ``check(arithmetic)`` returns None for a variant that passes, and
    defaults to :func:`self_test`.  ``rounding()`` says whether the device
    rounds to nearest, and defaults to
    :func:`hifuku.wgsl.device.rounds_to_nearest`.  A variant whose check
    raises, for example because the shader does not compile, is skipped.
    With the defaults, the choice is made once per process.

    Raises
    ------
    RuntimeError
        If the device does not round to nearest, which every variant
        assumes, or if no variant passes.  The message names each variant
        and the reason it failed.
    """
    default = check is None and rounding is None and candidates is ARITHMETICS
    if default and "choice" in _CHOSEN:
        return _CHOSEN["choice"]
    if not (rounding or rounds_to_nearest)():
        raise RuntimeError("the device does not round float32 addition to nearest, "
                           "and every float-float variant assumes that it does.")
    reasons = []
    for arithmetic in candidates:
        try:
            reason = (check or self_test)(arithmetic)
        except Exception as exc:
            reason = f"{type(exc).__name__}: {exc}"
        if reason is None:
            if default:
                _CHOSEN["choice"] = arithmetic
            return arithmetic
        reasons.append(f"{arithmetic}: {reason}")
    raise RuntimeError("no float-float variant is exact on this device.  "
                       + "  ".join(reasons))

self_test

self_test(arithmetic: Arithmetic, run=None) -> str | None

Run the product kernel in arithmetic on a fixed input, and say why it fails.

The kernel's total is compared with the host's float64 sum of the same site values, within :func:hifuku.precision.weighted_product_log_error. Both sides start from the same values, so the comparison measures the float-float arithmetic alone. run(sites, weights) replaces the production kernel of arithmetic.

Returns None when the total is within the bound, and the reason when it is not.

Source code in src/hifuku/wgsl/likelihood.py
def self_test(arithmetic: Arithmetic, run=None) -> str | None:
    """Run the product kernel in ``arithmetic`` on a fixed input, and say why it fails.

    The kernel's total is compared with the host's float64 sum of the same
    site values, within :func:`hifuku.precision.weighted_product_log_error`.
    Both sides start from the same values, so the comparison measures the
    float-float arithmetic alone.  ``run(sites, weights)`` replaces the
    production kernel of ``arithmetic``.

    Returns None when the total is within the bound, and the reason when it
    is not.
    """
    sites, weights = _self_test_input()
    norm = normalized_sites(sites)
    if run is None:
        source = product_kernel_source(wgsl_source(arithmetic))

        def run(s, w):
            return run_product(source, s, w, arithmetic)

    got = run(norm, weights)
    want = host_log_product(sites, weights)
    magnitudes = np.abs(np.log(norm[:, 0].astype(np.float64))
                        + norm[:, 1].astype(np.float64) * math.log(2.0))
    bound = weighted_product_log_error(weights, magnitudes, WGSL_WORKGROUP_SIZE)
    if abs(got - want) <= bound:
        return None
    return (f"the total differs from the host sum by {abs(got - want):.3e}, "
            f"past the bound of {bound:.3e}")

pruning_log_error

pruning_log_error(n_leaves: int, n_states: int, kind: str, magnitude: float) -> float

Return a bound on the error of one engine's site log-likelihood.

The bound is on the distance between the computed value and the exact value for the same float32 transition matrices and tip partials and the model's float64 state frequencies. The partial likelihoods are at precision kind. Every term of the pruning recursion is nonnegative, so the relative error of the site likelihood is at most gamma_K, with K = N (2S + 3) + S + 1 for N = n_leaves - 1 internal nodes and S = n_states states. The count covers the rescaling of each of Hifuku's engines: a power of two (WGSL), a division (CPU) or a reciprocal and a product (CUDA), and frequencies held in float32. The logs and the log-scale sums are float64. magnitude is a bound on the absolute value of the computed site log-likelihood.

The bound assumes rounding to nearest, no subnormal partial element, and a host log within one unit in the last place.

Derived in docs/theory/algebra/higham2002accuracy-felsenstein1981-pruning-rounding.py. Higham (2002) : Lemmas 3.1 and 3.3.

Raises:

Type Description
ValueError

If K u reaches 1, where the bound has no meaning.

Source code in src/hifuku/precision.py
def pruning_log_error(n_leaves: int, n_states: int, kind: str, magnitude: float) -> float:
    """Return a bound on the error of one engine's site log-likelihood.

    The bound is on the distance between the computed value and the exact
    value for the same float32 transition matrices and tip partials and the
    model's float64 state frequencies.  The partial likelihoods are at
    precision ``kind``.  Every term of the pruning recursion is nonnegative,
    so the relative error of the site likelihood is at most ``gamma_K``, with
    ``K = N (2S + 3) + S + 1`` for ``N = n_leaves - 1`` internal nodes and
    ``S = n_states`` states.  The count covers the rescaling of each of
    Hifuku's engines: a power of two (WGSL), a division (CPU) or a reciprocal
    and a product (CUDA), and frequencies held in float32.  The logs and the
    log-scale sums are float64.  ``magnitude`` is a bound on the absolute
    value of the computed site log-likelihood.

    The bound assumes rounding to nearest, no subnormal partial element, and
    a host log within one unit in the last place.

    Derived in
    docs/theory/algebra/higham2002accuracy-felsenstein1981-pruning-rounding.py.
    Higham (2002) : Lemmas 3.1 and 3.3.

    Raises
    ------
    ValueError
        If ``K u`` reaches 1, where the bound has no meaning.
    """
    internal = n_leaves - 1
    count = internal * (2 * n_states + 3) + n_states + 1
    g = _gamma(count, UNIT_ROUNDOFF[kind])
    if g >= 1.0:
        raise ValueError(
            f"a pruning of {n_leaves} taxa and {n_states} states has no rounding "
            f"bound at {kind}, because k u reaches 1.")
    # The float64 terms of an engine have absolute values that sum to at most
    # 3 |l| + 2 N log 2 + 1: the WGSL exponent term can be positive.
    spread = 3.0 * magnitude + 2.0 * internal * math.log(2.0) + 1.0
    return -math.log1p(-g) + _gamma(internal + 2, UNIT_ROUNDOFF["float64"]) * spread

weighted_product_log_error

weighted_product_log_error(weights, magnitudes, workgroup: int) -> float

Return a bound on the error of the WGSL product total.

The bound is on the distance between the device total and the host's float64 sum of w_p l_p for the same site values, where magnitudes[p] = |l_p|. The WGSL product kernel raises each normalized site value to its weight and multiplies the powers of one workgroup in float-float. The product of a group carries at most sum w_p + workgroup - 1 factors of the error of one product. The host part counts every rounding of the two recursive float64 sums that :func:hifuku.wgsl.likelihood.host_log_product and :func:hifuku.wgsl.likelihood.run_product perform.

Derived in docs/theory/algebra/joldes2017tight-higham2002accuracy-weighted-product.py. Muller & Rideau (2022) : Theorems 2.7 and 2.8; higham2002accuracy (Lemma 3.1; eq. (3.5)).

Source code in src/hifuku/precision.py
def weighted_product_log_error(weights, magnitudes, workgroup: int) -> float:
    """Return a bound on the error of the WGSL product total.

    The bound is on the distance between the device total and the host's
    float64 sum of ``w_p l_p`` for the same site values, where
    ``magnitudes[p] = |l_p|``.  The WGSL product kernel raises each
    normalized site value to its weight and multiplies the powers of one
    workgroup in float-float.  The product of a group carries at most
    ``sum w_p + workgroup - 1`` factors of the error of one product.  The
    host part counts every rounding of the two recursive float64 sums that
    :func:`hifuku.wgsl.likelihood.host_log_product` and
    :func:`hifuku.wgsl.likelihood.run_product` perform.

    Derived in
    docs/theory/algebra/joldes2017tight-higham2002accuracy-weighted-product.py.
    Muller & Rideau (2022) : Theorems 2.7 and 2.8;
    higham2002accuracy (Lemma 3.1; eq. (3.5)).
    """
    weights = np.asarray(weights, dtype=np.float64)
    magnitudes = np.asarray(magnitudes, dtype=np.float64)
    per_product = math.expm1(math.log1p(FF_MUL_RELATIVE_ERROR)
                             + math.log1p(2.0 * FF_LOW_PART_MIN))
    groups = max(1, -(-len(weights) // workgroup))
    device = 0.0
    for g in range(groups):
        count = float(weights[g * workgroup:(g + 1) * workgroup].sum()) + workgroup - 1
        delta = math.expm1(count * math.log1p(per_product))
        device += -math.log1p(-delta)
    # Both host sums are recursive, with every rounding counted: the
    # reference terms, and the group logs with the exponent term.
    v = UNIT_ROUNDOFF["float64"]
    weighted = float(np.dot(weights, magnitudes))
    host = (_gamma(len(weights) + 3, v) * (weighted + 2.0 * math.log(2.0) * weights.sum())
            + _gamma(groups + 3, v) * (weighted + 2.0 * groups))
    return device + host

Resident buffers

A survey keeps its walkers, its elite pool and its counters on the device for the whole run. Resident holds storage buffers by name, fills them on the device, and reads back only the range a caller asks for. Resident.run encodes a sequence of dispatches in one submission. WebGPU makes the writes of each dispatch visible to the dispatches after it, so a sequence needs no barrier of its own.

Resident

Named storage buffers on the process's WebGPU device.

An element type must be a whole number of 32-bit words: a 64-bit element is two words, low word first, which is how a WGSL kernel reads it.

Source code in src/hifuku/wgsl/resident.py
class Resident:
    """Named storage buffers on the process's WebGPU device.

    An element type must be a whole number of 32-bit words: a 64-bit element
    is two words, low word first, which is how a WGSL kernel reads it.
    """

    def __init__(self):
        self.device = default_device()
        self._buffers: dict[str, _Buffer] = {}

    def _get(self, name: str) -> _Buffer:
        try:
            return self._buffers[name]
        except KeyError:
            raise KeyError(f"no resident buffer is named {name!r}") from None

    def alloc(self, name: str, dtype, shape, fill=None) -> None:
        """Create the buffer ``name`` of ``shape`` elements of ``dtype``.

        The buffer holds zeros, or ``fill`` in every element when it is given.
        A fill of a 32-bit type runs on the device.  A fill of a 64-bit type
        is uploaded, since a survey keeps only small 64-bit buffers.
        """
        wgpu = _wgpu()
        dtype = np.dtype(dtype)
        if dtype.itemsize % 4:
            raise ValueError(f"{dtype} is not a whole number of 32-bit words")
        size = int(np.prod(shape, dtype=np.int64))
        usage = (wgpu.BufferUsage.STORAGE | wgpu.BufferUsage.COPY_SRC
                 | wgpu.BufferUsage.COPY_DST)
        buffer = self.device.create_buffer(size=_words(size * dtype.itemsize),
                                           usage=usage)
        self._buffers[name] = _Buffer(buffer, dtype, size)
        _log(("alloc", name, size * dtype.itemsize // 4))
        if fill is None or size == 0:
            return
        value = np.array([fill], dtype=dtype)
        if dtype.itemsize == 4:
            groups = -(-size // WGSL_WORKGROUP_SIZE)
            self.run([Step(_FILL, self.grid(groups),
                           (name, value.view(np.uint32)), name="fill")])
        else:
            self.write(name, np.full(size, fill, dtype=dtype))

    def release(self) -> None:
        """Destroy every buffer, so that the device can give its memory back
        at once rather than when Python collects the objects."""
        for b in self._buffers.values():
            b.buffer.destroy()
        self._buffers.clear()

    def grid(self, groups: int, limit: int | None = None):
        """A workgroup count as ``(x, y)`` within the per-dimension limit.

        A kernel that takes ``(x, y)`` numbers its invocations
        ``id.x + id.y * x * WGSL_WORKGROUP_SIZE``.  ``limit`` defaults to the
        device's limit.
        """
        if limit is None:
            limit = workgroup_limit()
        if groups <= limit:
            return groups
        return (limit, -(-groups // limit))

    def write(self, name: str, array, offset: int = 0) -> None:
        """Copy ``array`` into ``name`` from element ``offset``."""
        b = self._get(name)
        data = np.ascontiguousarray(array, dtype=b.dtype).reshape(-1)
        if offset < 0 or offset + data.size > b.size:
            raise ValueError(f"a write of {data.size} elements at {offset} runs "
                             f"past the end of {name!r}, which holds {b.size}")
        if data.size:
            _log(("write", name, offset * b.dtype.itemsize // 4,
                  data.view(np.uint32).copy()))
            self.device.queue.write_buffer(b.buffer, offset * b.dtype.itemsize,
                                           data)

    def read(self, name: str, lo: int, hi: int) -> np.ndarray:
        """Copy elements ``[lo, hi)`` of ``name`` to the host.

        Only that range moves.  The call waits for every submission before it.
        """
        b = self._get(name)
        if not 0 <= lo <= hi <= b.size:
            raise ValueError(f"a read of [{lo}, {hi}) runs past the end of "
                             f"{name!r}, which holds {b.size}")
        if hi == lo:
            return np.empty(0, dtype=b.dtype)
        item = b.dtype.itemsize
        data = self.device.queue.read_buffer(b.buffer, lo * item, (hi - lo) * item)
        return np.frombuffer(bytes(data), dtype=b.dtype).copy()

    def run(self, steps: Sequence[Step]) -> None:
        """Encode ``steps`` in order in one submission, and wait for it."""
        wgpu = _wgpu()
        start = time.perf_counter()
        compiled = False
        prepared = []
        for step in steps:
            pipeline, fresh = compute_pipeline(self.device, step.code)
            compiled = compiled or fresh
            prepared.append((step, pipeline))
        compiled_at = time.perf_counter()
        if _LOGS:
            _log(("run", [
                (step.code, step.workgroups,
                 tuple(entry if isinstance(entry, str)
                       else np.ascontiguousarray(entry).view(np.uint32).copy()
                       for entry in step.bindings),
                 bool(step.arithmetic is not None and step.arithmetic.needs_runtime),
                 step.name)
                for step in steps]))

        encoder = self.device.create_command_encoder()
        compute_pass = encoder.begin_compute_pass()
        for step, pipeline in prepared:
            members = []
            for entry in step.bindings:
                if isinstance(entry, str):
                    members.append(self._get(entry).buffer)
                else:
                    members.append(self.device.create_buffer_with_data(
                        data=np.ascontiguousarray(entry),
                        usage=wgpu.BufferUsage.STORAGE))
            group = self.device.create_bind_group(
                layout=pipeline.get_bind_group_layout(0),
                entries=[{"binding": i,
                          "resource": {"buffer": m, "offset": 0, "size": m.size}}
                         for i, m in enumerate(members)])
            compute_pass.set_pipeline(pipeline)
            compute_pass.set_bind_group(0, group)
            if step.arithmetic is not None and step.arithmetic.needs_runtime:
                compute_pass.set_bind_group(
                    WGSL_RUNTIME_GROUP, runtime_group(self.device, pipeline))
            grid = step.workgroups
            if isinstance(grid, tuple):
                compute_pass.dispatch_workgroups(*grid)
            else:
                compute_pass.dispatch_workgroups(grid)
        compute_pass.end()
        uploaded_at = time.perf_counter()
        self.device.queue.submit([encoder.finish()])
        self.device.queue.on_submitted_work_done_sync()
        record(KernelRecord("+".join(s.name for s in steps), compiled,
                            compiled_at - start, uploaded_at - compiled_at,
                            time.perf_counter() - uploaded_at))

alloc

alloc(name: str, dtype, shape, fill=None) -> None

Create the buffer name of shape elements of dtype.

The buffer holds zeros, or fill in every element when it is given. A fill of a 32-bit type runs on the device. A fill of a 64-bit type is uploaded, since a survey keeps only small 64-bit buffers.

Source code in src/hifuku/wgsl/resident.py
def alloc(self, name: str, dtype, shape, fill=None) -> None:
    """Create the buffer ``name`` of ``shape`` elements of ``dtype``.

    The buffer holds zeros, or ``fill`` in every element when it is given.
    A fill of a 32-bit type runs on the device.  A fill of a 64-bit type
    is uploaded, since a survey keeps only small 64-bit buffers.
    """
    wgpu = _wgpu()
    dtype = np.dtype(dtype)
    if dtype.itemsize % 4:
        raise ValueError(f"{dtype} is not a whole number of 32-bit words")
    size = int(np.prod(shape, dtype=np.int64))
    usage = (wgpu.BufferUsage.STORAGE | wgpu.BufferUsage.COPY_SRC
             | wgpu.BufferUsage.COPY_DST)
    buffer = self.device.create_buffer(size=_words(size * dtype.itemsize),
                                       usage=usage)
    self._buffers[name] = _Buffer(buffer, dtype, size)
    _log(("alloc", name, size * dtype.itemsize // 4))
    if fill is None or size == 0:
        return
    value = np.array([fill], dtype=dtype)
    if dtype.itemsize == 4:
        groups = -(-size // WGSL_WORKGROUP_SIZE)
        self.run([Step(_FILL, self.grid(groups),
                       (name, value.view(np.uint32)), name="fill")])
    else:
        self.write(name, np.full(size, fill, dtype=dtype))

release

release() -> None

Destroy every buffer, so that the device can give its memory back at once rather than when Python collects the objects.

Source code in src/hifuku/wgsl/resident.py
def release(self) -> None:
    """Destroy every buffer, so that the device can give its memory back
    at once rather than when Python collects the objects."""
    for b in self._buffers.values():
        b.buffer.destroy()
    self._buffers.clear()

grid

grid(groups: int, limit: int | None = None)

A workgroup count as (x, y) within the per-dimension limit.

A kernel that takes (x, y) numbers its invocations id.x + id.y * x * WGSL_WORKGROUP_SIZE. limit defaults to the device's limit.

Source code in src/hifuku/wgsl/resident.py
def grid(self, groups: int, limit: int | None = None):
    """A workgroup count as ``(x, y)`` within the per-dimension limit.

    A kernel that takes ``(x, y)`` numbers its invocations
    ``id.x + id.y * x * WGSL_WORKGROUP_SIZE``.  ``limit`` defaults to the
    device's limit.
    """
    if limit is None:
        limit = workgroup_limit()
    if groups <= limit:
        return groups
    return (limit, -(-groups // limit))

write

write(name: str, array, offset: int = 0) -> None

Copy array into name from element offset.

Source code in src/hifuku/wgsl/resident.py
def write(self, name: str, array, offset: int = 0) -> None:
    """Copy ``array`` into ``name`` from element ``offset``."""
    b = self._get(name)
    data = np.ascontiguousarray(array, dtype=b.dtype).reshape(-1)
    if offset < 0 or offset + data.size > b.size:
        raise ValueError(f"a write of {data.size} elements at {offset} runs "
                         f"past the end of {name!r}, which holds {b.size}")
    if data.size:
        _log(("write", name, offset * b.dtype.itemsize // 4,
              data.view(np.uint32).copy()))
        self.device.queue.write_buffer(b.buffer, offset * b.dtype.itemsize,
                                       data)

read

read(name: str, lo: int, hi: int) -> np.ndarray

Copy elements [lo, hi) of name to the host.

Only that range moves. The call waits for every submission before it.

Source code in src/hifuku/wgsl/resident.py
def read(self, name: str, lo: int, hi: int) -> np.ndarray:
    """Copy elements ``[lo, hi)`` of ``name`` to the host.

    Only that range moves.  The call waits for every submission before it.
    """
    b = self._get(name)
    if not 0 <= lo <= hi <= b.size:
        raise ValueError(f"a read of [{lo}, {hi}) runs past the end of "
                         f"{name!r}, which holds {b.size}")
    if hi == lo:
        return np.empty(0, dtype=b.dtype)
    item = b.dtype.itemsize
    data = self.device.queue.read_buffer(b.buffer, lo * item, (hi - lo) * item)
    return np.frombuffer(bytes(data), dtype=b.dtype).copy()

run

run(steps: Sequence[Step]) -> None

Encode steps in order in one submission, and wait for it.

Source code in src/hifuku/wgsl/resident.py
def run(self, steps: Sequence[Step]) -> None:
    """Encode ``steps`` in order in one submission, and wait for it."""
    wgpu = _wgpu()
    start = time.perf_counter()
    compiled = False
    prepared = []
    for step in steps:
        pipeline, fresh = compute_pipeline(self.device, step.code)
        compiled = compiled or fresh
        prepared.append((step, pipeline))
    compiled_at = time.perf_counter()
    if _LOGS:
        _log(("run", [
            (step.code, step.workgroups,
             tuple(entry if isinstance(entry, str)
                   else np.ascontiguousarray(entry).view(np.uint32).copy()
                   for entry in step.bindings),
             bool(step.arithmetic is not None and step.arithmetic.needs_runtime),
             step.name)
            for step in steps]))

    encoder = self.device.create_command_encoder()
    compute_pass = encoder.begin_compute_pass()
    for step, pipeline in prepared:
        members = []
        for entry in step.bindings:
            if isinstance(entry, str):
                members.append(self._get(entry).buffer)
            else:
                members.append(self.device.create_buffer_with_data(
                    data=np.ascontiguousarray(entry),
                    usage=wgpu.BufferUsage.STORAGE))
        group = self.device.create_bind_group(
            layout=pipeline.get_bind_group_layout(0),
            entries=[{"binding": i,
                      "resource": {"buffer": m, "offset": 0, "size": m.size}}
                     for i, m in enumerate(members)])
        compute_pass.set_pipeline(pipeline)
        compute_pass.set_bind_group(0, group)
        if step.arithmetic is not None and step.arithmetic.needs_runtime:
            compute_pass.set_bind_group(
                WGSL_RUNTIME_GROUP, runtime_group(self.device, pipeline))
        grid = step.workgroups
        if isinstance(grid, tuple):
            compute_pass.dispatch_workgroups(*grid)
        else:
            compute_pass.dispatch_workgroups(grid)
    compute_pass.end()
    uploaded_at = time.perf_counter()
    self.device.queue.submit([encoder.finish()])
    self.device.queue.on_submitted_work_done_sync()
    record(KernelRecord("+".join(s.name for s in steps), compiled,
                        compiled_at - start, uploaded_at - compiled_at,
                        time.perf_counter() - uploaded_at))

Step dataclass

One dispatch of a sequence.

bindings gives group 0 in binding order. An entry is the name of a resident buffer, or a host array that goes to the device for this submission only. workgroups is a count, or an (x, y) pair for a count above the per-dimension limit.

Source code in src/hifuku/wgsl/resident.py
@dataclass(frozen=True)
class Step:
    """One dispatch of a sequence.

    ``bindings`` gives group 0 in binding order.  An entry is the name of a
    resident buffer, or a host array that goes to the device for this
    submission only.  ``workgroups`` is a count, or an ``(x, y)`` pair for a
    count above the per-dimension limit.
    """

    code: str
    workgroups: int | tuple
    bindings: Sequence
    name: str = "kernel"
    arithmetic: Arithmetic | None = None

The elite pool

WgslArchive keeps the elite pool and its counters on the device, and gives the operations of hifuku.gpu_archive. A new cell claims a pool slot while slots remain. The incumbent elite wins every tie, and among equal candidates the highest index wins. From the same candidates, the pool, the outcomes, the move tally, the best and the smallest fitness are those of the CUDA pool.

WGSL has 32-bit atomics only. A 64-bit counter is a pair of words, and atomic_i64_source writes the add for one buffer of them. The winner of a slot comes from two atomic maxima, one of the ordered fitness and one of the index, where the CUDA pool uses one 64-bit maximum. The gain counter is the exact sum of the fixed-point gains. It equals the CUDA float64 counter under three conditions: both counters start at zero, gain_is_exact holds for every improvement, and the sum of the absolute gains stays below 2^33. Elsewhere it is within gain_error of it. The derivation is in docs/theory/algebra/higham2002accuracy-fixed-point-gain.py.

The kernels compare fitnesses through their ordered words, not as floats, because WGSL lets an implementation assume that a float comparison sees no NaN and no infinity, and a fitness can be -inf.

WgslArchive

An elite pool and its candidate buffers on the WebGPU device.

n_niche cells index capacity pool slots, each of which holds a flat tree state of state_dim float32 values. A batch holds at most n_cand candidates.

Source code in src/hifuku/wgsl/archive.py
class WgslArchive:
    """An elite pool and its candidate buffers on the WebGPU device.

    ``n_niche`` cells index ``capacity`` pool slots, each of which holds a
    flat tree state of ``state_dim`` float32 values.  A batch holds at most
    ``n_cand`` candidates.
    """

    def __init__(self, n_niche: int, capacity: int, state_dim: int, n_cand: int,
                 arithmetic: Arithmetic | None = None):
        if arithmetic is None:
            from hifuku.wgsl.likelihood import choose_arithmetic
            arithmetic = choose_arithmetic()
        self.arithmetic = arithmetic
        self.n_niche, self.capacity = int(n_niche), int(capacity)
        self.state_dim, self.n_cand = int(state_dim), int(n_cand)
        self._cand, cand_words = _layout(_CAND_FIELDS, self.n_cand)
        self._pool, pool_words = _layout(_POOL_FIELDS, self.capacity)
        self._count = 0
        self._check_sizes(cand_words, pool_words)
        self.resident = r = Resident()
        try:
            r.alloc("cand", np.uint32, (cand_words,))
            r.alloc("cand_state", np.float32, (self.n_cand * self.state_dim,))
            r.alloc("pool", np.uint32, (pool_words,))
            r.write("pool", np.full(self.capacity, EMPTY_FITNESS,
                                    np.float32).view(np.uint32), self._pool["P_FIT"])
            r.write("pool", np.full(self.capacity, -1, np.int32).view(np.uint32),
                    self._pool["P_NICHE"])
            r.alloc("pool_state", np.float32, (self.capacity * self.state_dim,))
            r.alloc("slot_map", np.int32, (self.n_niche,), fill=_EMPTY_CELL)
            r.alloc("winners", np.uint32, (2 * self.capacity,))
            n_stats = 2 * (_MOVES_PAIR + N_MOVE_TYPES * len(MOVE_COUNTERS))
            r.alloc("stats", np.uint32, (n_stats,))
        except BaseException:
            # A device that ran out of memory partway gets back what it gave.
            r.release()
            raise
        self._sources = {name: self._source(name) for name in _KERNELS}

    def _check_sizes(self, cand_words: int, pool_words: int) -> None:
        """Refuse a pool whose buffers one binding cannot hold.

        A device would refuse such a binding only at the first placement.  The
        CUDA pool sizes its capacity from free memory, so a capacity carried
        over from it can pass this limit, which a browser sets at 128 MiB.
        """
        from hifuku.wgsl.device import buffer_limit, storage_limit

        limit = min(storage_limit(), buffer_limit())
        sizes = {
            f"the tree states of a capacity of {self.capacity} slots":
                4 * self.capacity * self.state_dim,
            f"the tree states of a batch of {self.n_cand} candidates":
                4 * self.n_cand * self.state_dim,
            f"the {self.n_niche} cells of the niche index": 4 * self.n_niche,
            "the candidate fields": 4 * cand_words,
            "the slot fields": 4 * pool_words,
        }
        for what, nbytes in sizes.items():
            if nbytes > limit:
                raise ValueError(
                    f"{what} need {nbytes} bytes, and one storage binding on "
                    f"this device holds {limit}.  Lower the capacity or the "
                    f"batch, or coarsen the cell.")

    def _source(self, name: str) -> str:
        consts = {**self._cand, **self._pool,
                  "W_FIT": 0, "W_INDEX": self.capacity, "CAP": self.capacity,
                  "SDIM": self.state_dim, "WORKGROUP": WGSL_WORKGROUP_SIZE,
                  "S_SLOTS": _S_SLOTS, "S_DROPPED": _S_DROPPED, "S_BEST": _S_BEST,
                  "S_MIN": _S_MIN, "GAIN_PAIR": _GAIN_PAIR,
                  "MOVES_PAIR": _MOVES_PAIR, "N_COUNTERS": len(MOVE_COUNTERS)}
        header = "".join(f"const {k}: u32 = {v}u;\n" for k, v in consts.items())
        header += (f"const GATE: f32 = {wgsl_f32(_GATE)};\n"
                   f"const GAIN_SCALE: f32 = {wgsl_f32(2.0 ** GAIN_FIXED_BITS)};\n"
                   f"const EMPTY_CELL: i32 = {_EMPTY_CELL};\n"
                   f"const NO_ROOM: i32 = -2;\n")
        buffers = _KERNELS[name]
        decls = "".join(_declaration(i, b, a) for i, (b, a) in enumerate(buffers))
        uses_ff = name == "write_winners"
        prelude = "ff_prelude();\n    " if uses_ff else ""
        parts = [wgsl_source(self.arithmetic)] if uses_ff else []
        parts += [library("u64", "counters"), header, decls]
        if any(b == "stats" for b, _ in buffers):
            parts.append(atomic_i64_source("stats"))
        if any(b == "cand" for b, _ in buffers):
            parts.append(_sections()["common"])
        else:
            parts.append(_sections()["common"].split("fn cand_fit")[0])
        parts.append(_sections()["gate"])
        parts.append(_sections()[name])
        parts.append(f"""
@compute @workgroup_size({WGSL_WORKGROUP_SIZE})
fn main(@builtin(global_invocation_id) id: vec3<u32>,
        @builtin(num_workgroups) groups: vec3<u32>) {{
    {prelude}{name}(invocation(id, groups));
}}
""")
        return "\n".join(parts)

    def _step(self, name: str, invocations: int, params, extra=()):
        groups = self.resident.grid(max(1, -(-invocations // WGSL_WORKGROUP_SIZE)))
        names = [b for b, _ in _KERNELS[name]]
        bindings = []
        for b in names:
            if b == "params":
                bindings.append(np.asarray(params, dtype=np.uint32))
            elif b == "parent_niche":
                bindings.append(np.asarray(extra, dtype=np.int32))
            else:
                bindings.append(b)
        arithmetic = self.arithmetic if name == "write_winners" else None
        return Step(self._sources[name], groups, tuple(bindings), name=name,
                    arithmetic=arithmetic)

    # -- placement ----------------------------------------------------------

    def write_candidates(self, niches, fits, states, zs) -> None:
        """Copy a batch of candidates into the candidate buffers.

        ``zs`` are float64 residuals, stored as float-float pairs.
        """
        niches = np.asarray(niches, dtype=np.int32)
        n = niches.size
        if n > self.n_cand:
            raise ValueError(f"a batch of {n} candidates exceeds the buffer of "
                             f"{self.n_cand}")
        fits = np.asarray(fits, np.float32)
        states = np.asarray(states, np.float32)
        zs = np.asarray(zs, dtype=np.float64)
        _same_length(n, fitness=fits, residual=zs)
        if states.shape != (n, self.state_dim):
            raise ValueError(f"the states have shape {states.shape}, and a batch "
                             f"of {n} needs ({n}, {self.state_dim})")
        hi = zs.astype(np.float32)
        lo = (zs - hi.astype(np.float64)).astype(np.float32)
        r, c = self.resident, self._cand
        r.write("cand", niches.view(np.uint32), c["C_NICHE"])
        r.write("cand", fits.view(np.uint32), c["C_FIT"])
        r.write("cand", np.stack([hi, lo], axis=1).reshape(-1).view(np.uint32), c["C_Z"])
        r.write("cand_state", states.reshape(-1))
        self._count = n

    def place(self, sink: int) -> None:
        """Merge the candidates in the buffers into the pool, in one submission."""
        self.resident.run(self.placement_steps(sink))

    def placement_steps(self, sink: int, count: int | None = None) -> list:
        """The dispatches that merge the candidates in the buffers into the pool,
        for a submission of the caller's.

        ``count`` is the number of candidates in the buffers, when a walk on
        the device wrote them; it then becomes the batch that
        :meth:`outcomes` and :meth:`tally_step` read.
        """
        if count is not None:
            if count > self.n_cand:
                raise ValueError(f"a batch of {count} candidates exceeds the buffer "
                                 f"of {self.n_cand}")
            self._count = int(count)
        params = (self._count, np.int32(sink).view(np.uint32))
        return [self._step(name, self._count * (WGSL_WORKGROUP_SIZE
                                                if name == "copy_states" else 1), params)
                for name in _PLACEMENT]

    def place_candidates(self, niches, fits, states, zs, sink: int) -> None:
        """Copy a batch into the candidate buffers and place it."""
        self.write_candidates(niches, fits, states, zs)
        self.place(sink)

    def outcomes(self) -> tuple:
        """``(outcome, gain)`` of each candidate of the last batch: int32 codes
        (0 nothing, 1 new niche, 2 improved) and int64 fixed-point gains."""
        r, c, n = self.resident, self._cand, self._count
        outcome = r.read("cand", c["C_OUTCOME"], c["C_OUTCOME"] + n).view(np.int32)
        gain = _i64(r.read("cand", c["C_GAIN"], c["C_GAIN"] + 2 * n))
        return outcome, gain

    def tally_moves(self, moves, flags, parent_fits, parent_niche, walk_steps: int,
                    n_side: int, best: float, top_band: float) -> None:
        """Add the last batch's outcomes to the move tally.

        ``moves``, ``flags`` and ``parent_fits`` belong to the candidates of
        the last batch; candidate ``i`` belongs to walker ``i // walk_steps``,
        whose parent niche is ``parent_niche[walker]``.
        """
        if self._count == 0:
            _same_length(0, move=moves, flag=flags, parent_fitness=parent_fits)
            return
        self.write_tally_fields(moves, flags, parent_fits)
        self.resident.run([self.tally_step(parent_niche, walk_steps, n_side, best,
                                           top_band)])

    def write_tally_fields(self, moves, flags, parent_fits) -> None:
        """Copy the move, flag and parent fitness of the last batch's candidates
        into the candidate buffer.  A walk on the device writes them itself."""
        r, c, n = self.resident, self._cand, self._count
        _same_length(n, move=moves, flag=flags, parent_fitness=parent_fits)
        r.write("cand", np.asarray(moves, np.int32).view(np.uint32), c["C_MOVE"])
        r.write("cand", np.asarray(flags, np.int32).view(np.uint32), c["C_FLAG"])
        r.write("cand", np.asarray(parent_fits, np.float32).view(np.uint32),
                c["C_PARENT_FIT"])

    def tally_step(self, parent_niche, walk_steps: int, n_side: int, best: float,
                   top_band: float) -> Step:
        """The dispatch that adds the last batch's outcomes to the move tally,
        for a submission of the caller's."""
        n = self._count
        if -(-n // walk_steps) > len(parent_niche):
            raise ValueError(f"{n} candidates of {walk_steps} steps need "
                             f"{-(-n // walk_steps)} parent niches, and "
                             f"{len(parent_niche)} were given")
        t = parent_threshold(best, top_band)
        every = 1 if np.isneginf(t) else 0
        bits = 0 if every else int(np.array(t, np.float32).view(np.uint32))
        params = (n, walk_steps, n_side, every, bits)
        return self._step("tally_moves", n, params, extra=parent_niche)

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

    def occupied_slots(self) -> int:
        """How many slots hold a claimed cell.  The count is clamped to the
        capacity, because a claim draws its slot before it learns there is
        no room."""
        return min(int(self.resident.read("stats", _S_SLOTS, _S_SLOTS + 1)[0]),
                   self.capacity)

    def saturated(self) -> int:
        """Cells the pool had no room for."""
        return int(self.resident.read("stats", _S_DROPPED, _S_DROPPED + 1)[0])

    def read(self, name: str, lo: int, hi: int) -> np.ndarray:
        """Slots ``[lo, hi)`` of ``"niche"`` (int32), ``"fitness"`` (float32)
        or ``"z"`` (float64, from its float-float pair)."""
        r, p = self.resident, self._pool
        if name == "niche":
            return r.read("pool", p["P_NICHE"] + lo, p["P_NICHE"] + hi).view(np.int32)
        if name == "fitness":
            return r.read("pool", p["P_FIT"] + lo, p["P_FIT"] + hi).view(np.float32)
        if name == "z":
            pair = r.read("pool", p["P_Z"] + 2 * lo, p["P_Z"] + 2 * hi).view(np.float32)
            return pair[0::2].astype(np.float64) + pair[1::2].astype(np.float64)
        raise KeyError(f"the pool has no field {name!r}")

    def read_state(self, slot: int) -> np.ndarray:
        return self.read_states(slot, slot + 1)[0]

    def read_states(self, lo: int, hi: int) -> np.ndarray:
        """The flat tree states of slots ``[lo, hi)``, one row each."""
        d = self.state_dim
        return self.resident.read("pool_state", lo * d, hi * d).reshape(-1, d)

    def min_occupied_fitness(self) -> float:
        """The smallest elite fitness, or ``1e30`` when no slot holds one."""
        n = self.occupied_slots()
        self.resident.write("stats", np.array([0xFFFFFFFF], np.uint32), _S_MIN)
        if n:
            self.resident.run([self._step("smallest_elite", n, (n,))])
        word = int(self.resident.read("stats", _S_MIN, _S_MIN + 1)[0])
        return 1.0e30 if word == 0xFFFFFFFF else _unordered(word)

    def counters(self) -> tuple:
        """``(gain, best, moves)``: the gain counter in log-likelihood, the best
        fitness placed (``-1e30`` before any), and the int64 move tally."""
        words = self.resident.read("stats", 0, 2 * (_MOVES_PAIR + N_MOVE_TYPES
                                                     * len(MOVE_COUNTERS)))
        pairs = _i64(words)
        gain = float(pairs[_GAIN_PAIR]) * 2.0 ** -GAIN_FIXED_BITS
        best_word = int(words[_S_BEST])
        best = -1.0e30 if best_word == 0 else _unordered(best_word)
        moves = pairs[_MOVES_PAIR:].reshape(N_MOVE_TYPES, len(MOVE_COUNTERS)).copy()
        return gain, best, moves

    def set_counters(self, gain: float, moves=None) -> None:
        """Set the gain counter, and the move tally unless ``moves`` is None.

        The counter holds whole units of ``2^-GAIN_FIXED_BITS``, so ``gain``
        is rounded to the nearest unit.  A gain saved by this pool is already
        whole, and restores exactly.  A float64 gain saved by the CUDA pool
        may not be, and then the two counters no longer start from the same
        value, which the equality of :func:`hifuku.precision.gain_is_exact`
        assumes.
        """
        fixed = np.array([round(gain * 2.0 ** GAIN_FIXED_BITS)], np.int64)
        self.resident.write("stats", fixed.view(np.uint32), 2 * _GAIN_PAIR)
        if moves is not None:
            tally = np.asarray(moves, np.int64).reshape(-1)
            if tally.size != N_MOVE_TYPES * len(MOVE_COUNTERS):
                raise ValueError(f"a move tally holds {N_MOVE_TYPES} x "
                                 f"{len(MOVE_COUNTERS)} counters, and {tally.size} "
                                 f"were given")
            self.resident.write("stats", tally.view(np.uint32), 2 * _MOVES_PAIR)

write_candidates

write_candidates(niches, fits, states, zs) -> None

Copy a batch of candidates into the candidate buffers.

zs are float64 residuals, stored as float-float pairs.

Source code in src/hifuku/wgsl/archive.py
def write_candidates(self, niches, fits, states, zs) -> None:
    """Copy a batch of candidates into the candidate buffers.

    ``zs`` are float64 residuals, stored as float-float pairs.
    """
    niches = np.asarray(niches, dtype=np.int32)
    n = niches.size
    if n > self.n_cand:
        raise ValueError(f"a batch of {n} candidates exceeds the buffer of "
                         f"{self.n_cand}")
    fits = np.asarray(fits, np.float32)
    states = np.asarray(states, np.float32)
    zs = np.asarray(zs, dtype=np.float64)
    _same_length(n, fitness=fits, residual=zs)
    if states.shape != (n, self.state_dim):
        raise ValueError(f"the states have shape {states.shape}, and a batch "
                         f"of {n} needs ({n}, {self.state_dim})")
    hi = zs.astype(np.float32)
    lo = (zs - hi.astype(np.float64)).astype(np.float32)
    r, c = self.resident, self._cand
    r.write("cand", niches.view(np.uint32), c["C_NICHE"])
    r.write("cand", fits.view(np.uint32), c["C_FIT"])
    r.write("cand", np.stack([hi, lo], axis=1).reshape(-1).view(np.uint32), c["C_Z"])
    r.write("cand_state", states.reshape(-1))
    self._count = n

place

place(sink: int) -> None

Merge the candidates in the buffers into the pool, in one submission.

Source code in src/hifuku/wgsl/archive.py
def place(self, sink: int) -> None:
    """Merge the candidates in the buffers into the pool, in one submission."""
    self.resident.run(self.placement_steps(sink))

placement_steps

placement_steps(sink: int, count: int | None = None) -> list

The dispatches that merge the candidates in the buffers into the pool, for a submission of the caller's.

count is the number of candidates in the buffers, when a walk on the device wrote them; it then becomes the batch that :meth:outcomes and :meth:tally_step read.

Source code in src/hifuku/wgsl/archive.py
def placement_steps(self, sink: int, count: int | None = None) -> list:
    """The dispatches that merge the candidates in the buffers into the pool,
    for a submission of the caller's.

    ``count`` is the number of candidates in the buffers, when a walk on
    the device wrote them; it then becomes the batch that
    :meth:`outcomes` and :meth:`tally_step` read.
    """
    if count is not None:
        if count > self.n_cand:
            raise ValueError(f"a batch of {count} candidates exceeds the buffer "
                             f"of {self.n_cand}")
        self._count = int(count)
    params = (self._count, np.int32(sink).view(np.uint32))
    return [self._step(name, self._count * (WGSL_WORKGROUP_SIZE
                                            if name == "copy_states" else 1), params)
            for name in _PLACEMENT]

place_candidates

place_candidates(niches, fits, states, zs, sink: int) -> None

Copy a batch into the candidate buffers and place it.

Source code in src/hifuku/wgsl/archive.py
def place_candidates(self, niches, fits, states, zs, sink: int) -> None:
    """Copy a batch into the candidate buffers and place it."""
    self.write_candidates(niches, fits, states, zs)
    self.place(sink)

outcomes

outcomes() -> tuple

(outcome, gain) of each candidate of the last batch: int32 codes (0 nothing, 1 new niche, 2 improved) and int64 fixed-point gains.

Source code in src/hifuku/wgsl/archive.py
def outcomes(self) -> tuple:
    """``(outcome, gain)`` of each candidate of the last batch: int32 codes
    (0 nothing, 1 new niche, 2 improved) and int64 fixed-point gains."""
    r, c, n = self.resident, self._cand, self._count
    outcome = r.read("cand", c["C_OUTCOME"], c["C_OUTCOME"] + n).view(np.int32)
    gain = _i64(r.read("cand", c["C_GAIN"], c["C_GAIN"] + 2 * n))
    return outcome, gain

tally_moves

tally_moves(moves, flags, parent_fits, parent_niche, walk_steps: int, n_side: int, best: float, top_band: float) -> None

Add the last batch's outcomes to the move tally.

moves, flags and parent_fits belong to the candidates of the last batch; candidate i belongs to walker i // walk_steps, whose parent niche is parent_niche[walker].

Source code in src/hifuku/wgsl/archive.py
def tally_moves(self, moves, flags, parent_fits, parent_niche, walk_steps: int,
                n_side: int, best: float, top_band: float) -> None:
    """Add the last batch's outcomes to the move tally.

    ``moves``, ``flags`` and ``parent_fits`` belong to the candidates of
    the last batch; candidate ``i`` belongs to walker ``i // walk_steps``,
    whose parent niche is ``parent_niche[walker]``.
    """
    if self._count == 0:
        _same_length(0, move=moves, flag=flags, parent_fitness=parent_fits)
        return
    self.write_tally_fields(moves, flags, parent_fits)
    self.resident.run([self.tally_step(parent_niche, walk_steps, n_side, best,
                                       top_band)])

write_tally_fields

write_tally_fields(moves, flags, parent_fits) -> None

Copy the move, flag and parent fitness of the last batch's candidates into the candidate buffer. A walk on the device writes them itself.

Source code in src/hifuku/wgsl/archive.py
def write_tally_fields(self, moves, flags, parent_fits) -> None:
    """Copy the move, flag and parent fitness of the last batch's candidates
    into the candidate buffer.  A walk on the device writes them itself."""
    r, c, n = self.resident, self._cand, self._count
    _same_length(n, move=moves, flag=flags, parent_fitness=parent_fits)
    r.write("cand", np.asarray(moves, np.int32).view(np.uint32), c["C_MOVE"])
    r.write("cand", np.asarray(flags, np.int32).view(np.uint32), c["C_FLAG"])
    r.write("cand", np.asarray(parent_fits, np.float32).view(np.uint32),
            c["C_PARENT_FIT"])

tally_step

tally_step(parent_niche, walk_steps: int, n_side: int, best: float, top_band: float) -> Step

The dispatch that adds the last batch's outcomes to the move tally, for a submission of the caller's.

Source code in src/hifuku/wgsl/archive.py
def tally_step(self, parent_niche, walk_steps: int, n_side: int, best: float,
               top_band: float) -> Step:
    """The dispatch that adds the last batch's outcomes to the move tally,
    for a submission of the caller's."""
    n = self._count
    if -(-n // walk_steps) > len(parent_niche):
        raise ValueError(f"{n} candidates of {walk_steps} steps need "
                         f"{-(-n // walk_steps)} parent niches, and "
                         f"{len(parent_niche)} were given")
    t = parent_threshold(best, top_band)
    every = 1 if np.isneginf(t) else 0
    bits = 0 if every else int(np.array(t, np.float32).view(np.uint32))
    params = (n, walk_steps, n_side, every, bits)
    return self._step("tally_moves", n, params, extra=parent_niche)

occupied_slots

occupied_slots() -> int

How many slots hold a claimed cell. The count is clamped to the capacity, because a claim draws its slot before it learns there is no room.

Source code in src/hifuku/wgsl/archive.py
def occupied_slots(self) -> int:
    """How many slots hold a claimed cell.  The count is clamped to the
    capacity, because a claim draws its slot before it learns there is
    no room."""
    return min(int(self.resident.read("stats", _S_SLOTS, _S_SLOTS + 1)[0]),
               self.capacity)

saturated

saturated() -> int

Cells the pool had no room for.

Source code in src/hifuku/wgsl/archive.py
def saturated(self) -> int:
    """Cells the pool had no room for."""
    return int(self.resident.read("stats", _S_DROPPED, _S_DROPPED + 1)[0])

read

read(name: str, lo: int, hi: int) -> np.ndarray

Slots [lo, hi) of "niche" (int32), "fitness" (float32) or "z" (float64, from its float-float pair).

Source code in src/hifuku/wgsl/archive.py
def read(self, name: str, lo: int, hi: int) -> np.ndarray:
    """Slots ``[lo, hi)`` of ``"niche"`` (int32), ``"fitness"`` (float32)
    or ``"z"`` (float64, from its float-float pair)."""
    r, p = self.resident, self._pool
    if name == "niche":
        return r.read("pool", p["P_NICHE"] + lo, p["P_NICHE"] + hi).view(np.int32)
    if name == "fitness":
        return r.read("pool", p["P_FIT"] + lo, p["P_FIT"] + hi).view(np.float32)
    if name == "z":
        pair = r.read("pool", p["P_Z"] + 2 * lo, p["P_Z"] + 2 * hi).view(np.float32)
        return pair[0::2].astype(np.float64) + pair[1::2].astype(np.float64)
    raise KeyError(f"the pool has no field {name!r}")

read_states

read_states(lo: int, hi: int) -> np.ndarray

The flat tree states of slots [lo, hi), one row each.

Source code in src/hifuku/wgsl/archive.py
def read_states(self, lo: int, hi: int) -> np.ndarray:
    """The flat tree states of slots ``[lo, hi)``, one row each."""
    d = self.state_dim
    return self.resident.read("pool_state", lo * d, hi * d).reshape(-1, d)

min_occupied_fitness

min_occupied_fitness() -> float

The smallest elite fitness, or 1e30 when no slot holds one.

Source code in src/hifuku/wgsl/archive.py
def min_occupied_fitness(self) -> float:
    """The smallest elite fitness, or ``1e30`` when no slot holds one."""
    n = self.occupied_slots()
    self.resident.write("stats", np.array([0xFFFFFFFF], np.uint32), _S_MIN)
    if n:
        self.resident.run([self._step("smallest_elite", n, (n,))])
    word = int(self.resident.read("stats", _S_MIN, _S_MIN + 1)[0])
    return 1.0e30 if word == 0xFFFFFFFF else _unordered(word)

counters

counters() -> tuple

(gain, best, moves): the gain counter in log-likelihood, the best fitness placed (-1e30 before any), and the int64 move tally.

Source code in src/hifuku/wgsl/archive.py
def counters(self) -> tuple:
    """``(gain, best, moves)``: the gain counter in log-likelihood, the best
    fitness placed (``-1e30`` before any), and the int64 move tally."""
    words = self.resident.read("stats", 0, 2 * (_MOVES_PAIR + N_MOVE_TYPES
                                                 * len(MOVE_COUNTERS)))
    pairs = _i64(words)
    gain = float(pairs[_GAIN_PAIR]) * 2.0 ** -GAIN_FIXED_BITS
    best_word = int(words[_S_BEST])
    best = -1.0e30 if best_word == 0 else _unordered(best_word)
    moves = pairs[_MOVES_PAIR:].reshape(N_MOVE_TYPES, len(MOVE_COUNTERS)).copy()
    return gain, best, moves

set_counters

set_counters(gain: float, moves=None) -> None

Set the gain counter, and the move tally unless moves is None.

The counter holds whole units of 2^-GAIN_FIXED_BITS, so gain is rounded to the nearest unit. A gain saved by this pool is already whole, and restores exactly. A float64 gain saved by the CUDA pool may not be, and then the two counters no longer start from the same value, which the equality of :func:hifuku.precision.gain_is_exact assumes.

Source code in src/hifuku/wgsl/archive.py
def set_counters(self, gain: float, moves=None) -> None:
    """Set the gain counter, and the move tally unless ``moves`` is None.

    The counter holds whole units of ``2^-GAIN_FIXED_BITS``, so ``gain``
    is rounded to the nearest unit.  A gain saved by this pool is already
    whole, and restores exactly.  A float64 gain saved by the CUDA pool
    may not be, and then the two counters no longer start from the same
    value, which the equality of :func:`hifuku.precision.gain_is_exact`
    assumes.
    """
    fixed = np.array([round(gain * 2.0 ** GAIN_FIXED_BITS)], np.int64)
    self.resident.write("stats", fixed.view(np.uint32), 2 * _GAIN_PAIR)
    if moves is not None:
        tally = np.asarray(moves, np.int64).reshape(-1)
        if tally.size != N_MOVE_TYPES * len(MOVE_COUNTERS):
            raise ValueError(f"a move tally holds {N_MOVE_TYPES} x "
                             f"{len(MOVE_COUNTERS)} counters, and {tally.size} "
                             f"were given")
        self.resident.write("stats", tally.view(np.uint32), 2 * _MOVES_PAIR)

parent_threshold

parent_threshold(best: float, top_band: float) -> np.float32

The float32 form of the test parent >= best - top_band.

The CUDA tally makes the test in float64. For a float32 parent fitness it holds exactly when the parent is at or above the smallest float32 at or above best - top_band, which this returns. With no finite band, every parent passes, and this returns -inf. A threshold of zero is returned as -0, so that the device, which compares ordered words in which -0 lies below +0, passes a parent of either zero, as the float comparison does.

Source code in src/hifuku/wgsl/archive.py
def parent_threshold(best: float, top_band: float) -> np.float32:
    """The float32 form of the test ``parent >= best - top_band``.

    The CUDA tally makes the test in float64.  For a float32 parent fitness
    it holds exactly when the parent is at or above the smallest float32 at
    or above ``best - top_band``, which this returns.  With no finite band,
    every parent passes, and this returns ``-inf``.  A threshold of zero is
    returned as ``-0``, so that the device, which compares ordered words in
    which ``-0`` lies below ``+0``, passes a parent of either zero, as the
    float comparison does.
    """
    if not math.isfinite(top_band):
        return np.float32(-np.inf)
    exact = float(best) - float(top_band)
    t = np.float32(exact)
    if float(t) < exact:
        t = np.nextafter(t, np.float32(np.inf))
    if t == 0:
        t = np.float32(-0.0)
    return t

atomic_i64_source

atomic_i64_source(buffer: str) -> str

Return the WGSL function <buffer>_add_i64(index, value).

buffer is a storage array<atomic<u32>> that holds 64-bit counters as word pairs, low word first, and value is a vec2<u32> in two's complement. The function adds the low word, takes the carry from the value the low word held before the add, and adds it with the high word. Each word is added atomically, so once every add has finished the counter holds the exact sum modulo 2^64, in any order of the adds. A read during the adds can see the low word without its carry.

The function names its buffer because a WGSL function cannot take a pointer to storage memory.

Source code in src/hifuku/wgsl/library.py
def atomic_i64_source(buffer: str) -> str:
    """Return the WGSL function ``<buffer>_add_i64(index, value)``.

    ``buffer`` is a storage ``array<atomic<u32>>`` that holds 64-bit counters
    as word pairs, low word first, and ``value`` is a ``vec2<u32>`` in two's
    complement.  The function adds the low word, takes the carry from the
    value the low word held before the add, and adds it with the high word.
    Each word is added atomically, so once every add has finished the counter
    holds the exact sum modulo 2^64, in any order of the adds.  A read during
    the adds can see the low word without its carry.

    The function names its buffer because a WGSL function cannot take a
    pointer to storage memory.
    """
    if not buffer.isidentifier():
        raise ValueError(f"{buffer!r} is not a WGSL identifier")
    return f"""
fn {buffer}_add_i64(index: u32, value: vec2<u32>) {{
    let old = atomicAdd(&{buffer}[2u * index], value.x);
    let carry = select(0u, 1u, old > 0xFFFFFFFFu - value.x);
    atomicAdd(&{buffer}[2u * index + 1u], value.y + carry);
}}
"""

gain_is_exact

gain_is_exact(new_fitness, old_fitness)

True where the fixed-point gain of an improvement equals the float64 gain.

The two fitnesses are float32. Where both have magnitude at least 8 and they differ by less than 2^32, the difference is a whole number of units of 2^-GAIN_FIXED_BITS, and the CUDA pool's float64 gain and the WGSL pool's fixed-point gain are the same number. A float64 sum of such gains is exact in any order while the sum of their magnitudes stays below 2^33, so the two pools' gain counters agree to the bit.

Derived in docs/theory/algebra/higham2002accuracy-fixed-point-gain.py. Higham (2002) : equation 2.1.

Source code in src/hifuku/precision.py
def gain_is_exact(new_fitness, old_fitness):
    """True where the fixed-point gain of an improvement equals the float64 gain.

    The two fitnesses are float32.  Where both have magnitude at least 8 and
    they differ by less than ``2^32``, the difference is a whole number of
    units of ``2^-GAIN_FIXED_BITS``, and the CUDA pool's float64 gain and the
    WGSL pool's fixed-point gain are the same number.  A float64 sum of such
    gains is exact in any order while the sum of their magnitudes stays below
    ``2^33``, so the two pools' gain counters agree to the bit.

    Derived in docs/theory/algebra/higham2002accuracy-fixed-point-gain.py.
    Higham (2002) : equation 2.1.
    """
    # A float32 of magnitude 2^(24 - 1 - B) or more is a whole number of
    # units 2^-B, and float64 rounds x + 1/2 exactly below 2^52 units.
    floor = 2.0 ** (24 - 1 - GAIN_FIXED_BITS)
    limit = 2.0 ** (52 - GAIN_FIXED_BITS)
    a = np.asarray(new_fitness, dtype=np.float32).astype(np.float64)
    b = np.asarray(old_fitness, dtype=np.float32).astype(np.float64)
    return ((np.abs(a) >= floor) & (np.abs(b) >= floor)
            & (np.abs(a - b) < limit))

gain_error

gain_error(n_improvements: int, magnitude: float) -> float

Bound the difference between the float64 gain counter and the fixed-point one.

n_improvements is the number of improvements summed, and magnitude is the sum of their absolute gains. Each fixed-point gain below 2^43 log-likelihood is within one unit, 2^-GAIN_FIXED_BITS, of its exact value, and the float64 counter is a sum of n rounded terms in some order. Both counters start at zero. Where :func:gain_is_exact holds for every improvement and magnitude is below 2^33, the two counters are equal and this bound is not needed.

Derived in docs/theory/algebra/higham2002accuracy-fixed-point-gain.py. Higham (2002) : Lemma 3.1, section 4.2.

Source code in src/hifuku/precision.py
def gain_error(n_improvements: int, magnitude: float) -> float:
    """Bound the difference between the float64 gain counter and the
    fixed-point one.

    ``n_improvements`` is the number of improvements summed, and
    ``magnitude`` is the sum of their absolute gains.  Each fixed-point gain
    below ``2^43`` log-likelihood is within one unit, ``2^-GAIN_FIXED_BITS``,
    of its exact value, and the float64 counter is a sum of ``n`` rounded
    terms in some order.  Both counters start at zero.  Where
    :func:`gain_is_exact` holds for every improvement and ``magnitude`` is
    below ``2^33``, the two counters are equal and this bound is not needed.

    Derived in docs/theory/algebra/higham2002accuracy-fixed-point-gain.py.
    Higham (2002) : Lemma 3.1, section 4.2.
    """
    return (n_improvements * 2.0 ** -GAIN_FIXED_BITS
            + _gamma(n_improvements, UNIT_ROUNDOFF["float64"]) * magnitude)

The walk on the device

WgslWalk runs one survey pass in one submission. Each walker loads its parent from a pool slot and walks K steps. Every step's candidate goes into the pool's candidate buffers, and the pool's placement and move tally follow. The host reads nothing during the pass.

A step is a sequence of dispatches of the move, post-order, matrix, peel and placement kernels, which are the kernels the separate functions above run and test. Small kernels join them, and write each candidate in the canonical form and with the flags of the CUDA walk kernel. Each dispatch is short. This matters because a browser or Windows stops a GPU task that runs for about two seconds.

From the same parents and generator words, the pass draws the same moves and the same generator stream as the CUDA walk. Topology moves give the same trees, bit for bit. The fitness is within walker_fitness_error, and a niche differs only at a cell edge, within lambda_tolerance. Every step rebuilds every transition matrix and peels the whole tree.

WgslWalk

Walkers on the WebGPU device, beside the elite pool archive.

walk_tree gives the shared leaf order of every walker, with its global taxon indices set, as :class:~hifuku.device_backend.DeviceBackend prepares the seeds. anchors are the chart's three anchor trees and triangle its chart; cell, origin and extent lay out the niche grid, as the pool's. params gives the move mix and step sizes. The pool's candidate buffer must hold n_walkers * walk_steps candidates.

Raises:

Type Description
ValueError

If the pool is too small for a pass or holds states of another tree size, if the walkers exceed one dispatch dimension, or if a walker buffer passes the storage limit of one binding.

Source code in src/hifuku/wgsl/walk.py
class WgslWalk:
    """Walkers on the WebGPU device, beside the elite pool ``archive``.

    ``walk_tree`` gives the shared leaf order of every walker, with its global
    taxon indices set, as :class:`~hifuku.device_backend.DeviceBackend`
    prepares the seeds.  ``anchors`` are the chart's three anchor trees and
    ``triangle`` its chart; ``cell``, ``origin`` and ``extent`` lay out the
    niche grid, as the pool's.  ``params`` gives the move mix and step sizes.
    The pool's candidate buffer must hold ``n_walkers * walk_steps``
    candidates.

    Raises
    ------
    ValueError
        If the pool is too small for a pass or holds states of another tree
        size, if the walkers exceed one dispatch dimension, or if a walker
        buffer passes the storage limit of one binding.
    """

    def __init__(self, archive: WgslArchive, walk_tree, anchors, triangle, alignment,
                 model, params, n_walkers: int, walk_steps: int, cell: float,
                 origin: float, extent: float, arithmetic: Arithmetic | None = None):
        from hifuku.pruning import _leaf_rows
        from hifuku.wgsl import moves, placement, pmat, walker
        from hifuku.wgsl.device import storage_limit, workgroup_limit

        self.M, self.K = int(n_walkers), int(walk_steps)
        if self.M < 1 or self.K < 1:
            raise ValueError(f"a walk needs at least one walker and one step; it was "
                             f"given {self.M} walkers and {self.K} steps")
        # The walker buffers live beside the pool's under fixed names, so a
        # second walk would replace the first one's.
        if getattr(archive, "walk", None) is not None:
            raise ValueError("this pool already has a walk; a pool holds the "
                             "buffers of one walk")
        self.archive = archive
        self.resident = r = archive.resident
        self.arithmetic = arithmetic = arithmetic or archive.arithmetic
        L = self.n_leaves = walk_tree.n_leaves
        N = self.n_nodes = walk_tree.n_nodes
        S = model.n_states
        if archive.state_dim != 4 * N:
            raise ValueError(f"the pool holds states of {archive.state_dim} words, and "
                             f"a tree of {N} nodes needs {4 * N}")
        if archive.n_cand < self.M * self.K:
            raise ValueError(f"the pool's candidate buffer holds {archive.n_cand}, and a "
                             f"pass of {self.M} walkers and {self.K} steps writes "
                             f"{self.M * self.K}")
        if self.M > workgroup_limit():
            raise ValueError(f"{self.M} walkers need more workgroups than one dispatch "
                             f"dimension holds ({workgroup_limit()})")

        chart = placement.chart_data(walk_tree, anchors, triangle, cell, origin, extent)
        self.sink = int(chart.chart["sink"])
        self.n_side = int(chart.chart["n_side"])
        tables = placement._tables(chart)
        codes = alignment.patterns[_leaf_rows(walk_tree, alignment, model)]
        n_patterns = codes.shape[1]
        peel_inputs = walker._inputs(codes, alignment.weights, model.freqs)
        model_words = pmat._model_buffer(model)
        self._move_stride = moves._out_words(L, 1)
        place_stride = placement._OUT_STRIDE

        sizes = {
            "walk_states": (np.float32, self.M * 4 * N),
            "walk_rng": (np.uint32, self.M * 4),
            "walk_parent_fit": (np.float32, self.M),
            "walk_moves_out": (np.uint32, self.M * self._move_stride),
            "walk_moves_scratch": (np.int32, self.M * moves._scratch_words(L)),
            "walk_orders": (np.int32, self.M * (L - 1) * 3),
            "walk_stacks": (np.int32, self.M * 2 * N),
            "walk_edge_lengths": (np.float32, self.M * N),
            "walk_pmat": (np.float32, self.M * N * S * S),
            "walk_partials": (np.float32, self.M * max(L - 2, 1) * S * n_patterns),
            "walk_peel_out": (np.uint32, self.M * _PEEL_STRIDE),
            "walk_place_out": (np.uint32, self.M * place_stride),
            "walk_place_scratch": (np.uint32, self.M * 3 * N),
            "walk_canon_of": (np.int32, self.M * N),
        }
        limit = storage_limit()
        for name, (dtype, count) in sizes.items():
            if count * np.dtype(dtype).itemsize > limit:
                raise ValueError(f"{name[5:].replace('_', ' ')} of {self.M} walkers "
                                 f"need {count * np.dtype(dtype).itemsize} bytes, and "
                                 f"one storage binding holds {limit}.  Lower n_walkers.")
        for name, (dtype, count) in sizes.items():
            r.alloc(name, dtype, (count,))
        for name, words in (("walk_peel_inputs", peel_inputs.words),
                            ("walk_place_data", tables.words),
                            ("walk_model", model_words.words)):
            r.alloc(name, np.uint32, (words.size,))
            r.write(name, words)

        self._stage = {
            "moves": moves.moves_source(L, 1, params, arithmetic),
            "orders": walker.traversal_source(L, N),
            "matrices": pmat.kernel_source(model, model_words, arithmetic),
            "peel": walker.peel_source(L, N, n_patterns, S, arithmetic),
            "placement": placement.placement_source(chart, tables, L, arithmetic),
        }
        consts = {"N_LEAVES": L, "N_NODES": N, "N4": 4 * N,
                  "WORKGROUP": WGSL_WORKGROUP_SIZE,
                  "P_FIT": archive._pool["P_FIT"],
                  "MOVE_STRIDE": self._move_stride, "MOVE_TAIL": 4 * N + 8,
                  "PLACE_STRIDE": place_stride, "PLACE_Z": _PLACE_Z,
                  "PLACE_NICHE": _PLACE_NICHE, "PEEL_STRIDE": _PEEL_STRIDE,
                  "PEEL_FLAG": _PEEL_FLAG, "PEEL_FITNESS": _PEEL_FITNESS,
                  "EMPTY_BITS": int(np.array(EMPTY_FITNESS).view(np.uint32)),
                  **{k: v for k, v in archive._cand.items()}}
        header = "".join(f"const {k}: u32 = {v}u;\n" for k, v in consts.items())
        header += f"const SINK: i32 = {self.sink}i;\n"
        self._glue = {name: self._glue_source(name, header) for name in _KERNELS}
        archive.walk = self

    @staticmethod
    def _glue_source(name: str, header: str) -> str:
        decls = "".join(
            f"@group(0) @binding({i}) var<storage, "
            f"{'read' if access in ('host', 'read') else 'read_write'}> "
            f"{buffer}: array<{kind}>;\n"
            for i, (buffer, kind, access) in enumerate(_KERNELS[name]))
        return "\n".join([
            library("counters"), header, decls, _sections()["common"], _sections()[name],
            f"""
@compute @workgroup_size({WGSL_WORKGROUP_SIZE})
fn main(@builtin(global_invocation_id) id: vec3<u32>,
        @builtin(num_workgroups) groups: vec3<u32>) {{
    {name}(invocation(id, groups));
}}
"""])

    def _glue_step(self, name: str, invocations: int, params, host=()) -> Step:
        groups = self.resident.grid(max(1, -(-invocations // WGSL_WORKGROUP_SIZE)))
        bindings = []
        for buffer, _kind, access in _KERNELS[name]:
            if buffer == "params":
                bindings.append(np.asarray(params, dtype=np.uint32))
            elif access == "host":
                bindings.append(np.asarray(host, dtype=np.int32))
            else:
                bindings.append(_resident_name(buffer))
        return Step(self._glue[name], groups, tuple(bindings), name=name)

    # -- generator ----------------------------------------------------------

    def set_rng(self, words) -> None:
        """Set each walker's xoroshiro128+ state, uint64 ``(M, 2)``, s0 then s1."""
        words = np.asarray(words, dtype=np.uint64)
        if words.shape != (self.M, 2):
            raise ValueError(f"the generator states have shape {words.shape}, and "
                             f"{self.M} walkers need ({self.M}, 2)")
        self.resident.write("walk_rng", np.ascontiguousarray(words).view(np.uint32))

    def rng(self) -> np.ndarray:
        """Each walker's generator state, uint64 ``(M, 2)``, s0 then s1."""
        return self.resident.read("walk_rng", 0, 4 * self.M).view(np.uint64).reshape(-1, 2)

    # -- the pass -----------------------------------------------------------

    def _walk_steps(self, k: int, floor_on: int, floor_bits: int) -> list:
        M, N, L = self.M, self.n_nodes, self.n_leaves
        a = self.arithmetic
        per_walker = -(-M // WGSL_WORKGROUP_SIZE)
        params = (M,)
        return [
            Step(self._stage["moves"], per_walker,
                 ("walk_states", "walk_rng", "walk_moves_out", "walk_moves_scratch"),
                 name="moves", arithmetic=a),
            self._glue_step("commit", M * 4 * N, params),
            Step(self._stage["orders"], per_walker,
                 ("walk_states", "walk_orders", "walk_stacks"), name="orders"),
            self._glue_step("lengths", M * N, params),
            Step(self._stage["matrices"], self.resident.grid(M * N),
                 ("walk_model", "walk_edge_lengths", "walk_pmat"), name="matrices",
                 arithmetic=a),
            Step(self._stage["peel"], M,
                 ("walk_peel_inputs", "walk_orders", "walk_pmat", "walk_peel_out",
                  "walk_partials"), name="peel", arithmetic=a),
            Step(self._stage["placement"], M,
                 ("walk_place_data", "walk_states", "walk_orders", "walk_place_out",
                  "walk_place_scratch"), name="placement", arithmetic=a),
            self._glue_step("canon", M * N, params),
            self._glue_step("write_state", M * N, (M, self.K, k)),
            self._glue_step("write_scalars", M, (M, self.K, k, floor_on, floor_bits)),
        ]

    def pass_steps(self, slots, parent_niches, logl_floor: float, best: float,
                   top_band: float, claimed: int | None = None) -> list:
        """The dispatches of one pass, for one submission.

        Walker ``m`` starts from pool slot ``slots[m]``, whose niche is
        ``parent_niches[m]``.  A candidate below ``logl_floor`` is flagged and
        carries ``EMPTY_FITNESS``; ``-inf`` applies no floor.  ``best`` and
        ``top_band`` set the near-summit count of the move tally, as in
        :meth:`WgslArchive.tally_step`.  ``claimed`` is the pool's count of
        claimed slots, which a caller that runs many passes reads once; when
        it is None, it is read from the device.
        """
        slots = np.asarray(slots, dtype=np.int32)
        if slots.shape != (self.M,) or len(parent_niches) != self.M:
            raise ValueError(f"a pass of {self.M} walkers needs {self.M} slots and "
                             f"{self.M} parent niches")
        # A slot past the claimed ones holds a tree of zeros, which the walk
        # would read as a parent and place with an impossible fitness.  The
        # count is one word of the device.
        if claimed is None:
            claimed = self.archive.occupied_slots()
        outside = (slots < 0) | (slots >= claimed)
        if outside.any():
            m = int(np.flatnonzero(outside)[0])
            raise ValueError(f"walker {m} names pool slot {int(slots[m])}, and the "
                             f"pool has claimed slots 0 to {claimed - 1}")
        floor_on = 0 if np.isneginf(logl_floor) else 1
        floor_bits = (0 if not floor_on
                      else int(np.array(parent_threshold(logl_floor, 0.0)).view(np.uint32)))
        steps = [self._glue_step("load_parents", self.M * 4 * self.n_nodes, (self.M,),
                                 host=slots)]
        for k in range(self.K):
            steps += self._walk_steps(k, floor_on, floor_bits)
        steps += self.archive.placement_steps(self.sink, self.M * self.K)
        steps.append(self.archive.tally_step(parent_niches, self.K, self.n_side, best,
                                             top_band))
        return steps

    def run_pass(self, slots, parent_niches, logl_floor: float = float("-inf"),
                 best: float = float("-inf"), top_band: float = float("inf")) -> None:
        """Run one pass in one submission; see :meth:`pass_steps`."""
        self.resident.run(self.pass_steps(slots, parent_niches, logl_floor, best,
                                          top_band))

    def candidates(self) -> dict:
        """The last pass's candidates, as the walk wrote them, for a test or a reader.

        ``state`` is float32 ``(M, K, 4 n_nodes)`` in canonical form;
        ``niche``, ``fitness``, ``move``, ``flag`` and ``parent_fitness`` are
        ``(M, K)``; ``z`` is float64 ``(M, K)``, from its float-float pair.
        The fitness of a flagged candidate is ``EMPTY_FITNESS``, as the walk
        writes it for the pool.
        """
        r, c, n = self.resident, self.archive._cand, self.M * self.K
        shape = (self.M, self.K)

        def field(name, dtype, words=1):
            return r.read("cand", c[name], c[name] + words * n).view(dtype)

        pair = field("C_Z", np.float32, 2)
        return {
            "state": r.read("cand_state", 0, n * 4 * self.n_nodes).reshape(
                self.M, self.K, 4 * self.n_nodes),
            "niche": field("C_NICHE", np.int32).reshape(shape),
            "fitness": field("C_FIT", np.float32).reshape(shape),
            "z": (pair[0::2].astype(np.float64) + pair[1::2]).reshape(shape),
            "move": field("C_MOVE", np.int32).reshape(shape),
            "flag": field("C_FLAG", np.int32).reshape(shape),
            "parent_fitness": field("C_PARENT_FIT", np.float32).reshape(shape),
        }

set_rng

set_rng(words) -> None

Set each walker's xoroshiro128+ state, uint64 (M, 2), s0 then s1.

Source code in src/hifuku/wgsl/walk.py
def set_rng(self, words) -> None:
    """Set each walker's xoroshiro128+ state, uint64 ``(M, 2)``, s0 then s1."""
    words = np.asarray(words, dtype=np.uint64)
    if words.shape != (self.M, 2):
        raise ValueError(f"the generator states have shape {words.shape}, and "
                         f"{self.M} walkers need ({self.M}, 2)")
    self.resident.write("walk_rng", np.ascontiguousarray(words).view(np.uint32))

rng

rng() -> np.ndarray

Each walker's generator state, uint64 (M, 2), s0 then s1.

Source code in src/hifuku/wgsl/walk.py
def rng(self) -> np.ndarray:
    """Each walker's generator state, uint64 ``(M, 2)``, s0 then s1."""
    return self.resident.read("walk_rng", 0, 4 * self.M).view(np.uint64).reshape(-1, 2)

pass_steps

pass_steps(slots, parent_niches, logl_floor: float, best: float, top_band: float, claimed: int | None = None) -> list

The dispatches of one pass, for one submission.

Walker m starts from pool slot slots[m], whose niche is parent_niches[m]. A candidate below logl_floor is flagged and carries EMPTY_FITNESS; -inf applies no floor. best and top_band set the near-summit count of the move tally, as in :meth:WgslArchive.tally_step. claimed is the pool's count of claimed slots, which a caller that runs many passes reads once; when it is None, it is read from the device.

Source code in src/hifuku/wgsl/walk.py
def pass_steps(self, slots, parent_niches, logl_floor: float, best: float,
               top_band: float, claimed: int | None = None) -> list:
    """The dispatches of one pass, for one submission.

    Walker ``m`` starts from pool slot ``slots[m]``, whose niche is
    ``parent_niches[m]``.  A candidate below ``logl_floor`` is flagged and
    carries ``EMPTY_FITNESS``; ``-inf`` applies no floor.  ``best`` and
    ``top_band`` set the near-summit count of the move tally, as in
    :meth:`WgslArchive.tally_step`.  ``claimed`` is the pool's count of
    claimed slots, which a caller that runs many passes reads once; when
    it is None, it is read from the device.
    """
    slots = np.asarray(slots, dtype=np.int32)
    if slots.shape != (self.M,) or len(parent_niches) != self.M:
        raise ValueError(f"a pass of {self.M} walkers needs {self.M} slots and "
                         f"{self.M} parent niches")
    # A slot past the claimed ones holds a tree of zeros, which the walk
    # would read as a parent and place with an impossible fitness.  The
    # count is one word of the device.
    if claimed is None:
        claimed = self.archive.occupied_slots()
    outside = (slots < 0) | (slots >= claimed)
    if outside.any():
        m = int(np.flatnonzero(outside)[0])
        raise ValueError(f"walker {m} names pool slot {int(slots[m])}, and the "
                         f"pool has claimed slots 0 to {claimed - 1}")
    floor_on = 0 if np.isneginf(logl_floor) else 1
    floor_bits = (0 if not floor_on
                  else int(np.array(parent_threshold(logl_floor, 0.0)).view(np.uint32)))
    steps = [self._glue_step("load_parents", self.M * 4 * self.n_nodes, (self.M,),
                             host=slots)]
    for k in range(self.K):
        steps += self._walk_steps(k, floor_on, floor_bits)
    steps += self.archive.placement_steps(self.sink, self.M * self.K)
    steps.append(self.archive.tally_step(parent_niches, self.K, self.n_side, best,
                                         top_band))
    return steps

run_pass

run_pass(slots, parent_niches, logl_floor: float = float('-inf'), best: float = float('-inf'), top_band: float = float('inf')) -> None

Run one pass in one submission; see :meth:pass_steps.

Source code in src/hifuku/wgsl/walk.py
def run_pass(self, slots, parent_niches, logl_floor: float = float("-inf"),
             best: float = float("-inf"), top_band: float = float("inf")) -> None:
    """Run one pass in one submission; see :meth:`pass_steps`."""
    self.resident.run(self.pass_steps(slots, parent_niches, logl_floor, best,
                                      top_band))

candidates

candidates() -> dict

The last pass's candidates, as the walk wrote them, for a test or a reader.

state is float32 (M, K, 4 n_nodes) in canonical form; niche, fitness, move, flag and parent_fitness are (M, K); z is float64 (M, K), from its float-float pair. The fitness of a flagged candidate is EMPTY_FITNESS, as the walk writes it for the pool.

Source code in src/hifuku/wgsl/walk.py
def candidates(self) -> dict:
    """The last pass's candidates, as the walk wrote them, for a test or a reader.

    ``state`` is float32 ``(M, K, 4 n_nodes)`` in canonical form;
    ``niche``, ``fitness``, ``move``, ``flag`` and ``parent_fitness`` are
    ``(M, K)``; ``z`` is float64 ``(M, K)``, from its float-float pair.
    The fitness of a flagged candidate is ``EMPTY_FITNESS``, as the walk
    writes it for the pool.
    """
    r, c, n = self.resident, self.archive._cand, self.M * self.K
    shape = (self.M, self.K)

    def field(name, dtype, words=1):
        return r.read("cand", c[name], c[name] + words * n).view(dtype)

    pair = field("C_Z", np.float32, 2)
    return {
        "state": r.read("cand_state", 0, n * 4 * self.n_nodes).reshape(
            self.M, self.K, 4 * self.n_nodes),
        "niche": field("C_NICHE", np.int32).reshape(shape),
        "fitness": field("C_FIT", np.float32).reshape(shape),
        "z": (pair[0::2].astype(np.float64) + pair[1::2]).reshape(shape),
        "move": field("C_MOVE", np.int32).reshape(shape),
        "flag": field("C_FLAG", np.int32).reshape(shape),
        "parent_fitness": field("C_PARENT_FIT", np.float32).reshape(shape),
    }

The survey backend

WgslBackend runs a whole survey through the shared driver, selected as device="wgsl". It seeds its walker generators as the CUDA engine does. A survey of one seed therefore draws one generator stream on both engines, and a snapshot of either engine continues on the other. With prune-regraft and interchange moves only, a WGSL survey reaches the same niches with the same trees as a CUDA survey, and each fitness is within the walker bound. The survey workload of scripts/bench.py compares the CPU, CUDA and WGSL engines on one budget.

A resume across the two engines restores the elites, the parent draw and the walker generators exactly, with two differences in the counters it carries. The WGSL pool holds its gain in units of 2^-20, so a CUDA gain counter resumed on WGSL is rounded to that unit, which is exact where gain_is_exact holds. The WGSL pool holds each residual as a float-float pair, so the residual of a restored elite is the pair nearest the CUDA float64 value. Neither changes what the walk does next.

The WGSL engine does not measure device time. A WGSL record's device_seconds is zero, as on the host, and its device work is in wall_seconds. Each pass is one submission, which the host waits for, so that a browser or a driver does not stop a long one.

WebGPU reports neither the total nor the free memory of a device, for reasons of portability and privacy. The engine therefore checks each buffer against the storage limit of one binding before it allocates, and finds the total by allocation. WgslBackend.fit allocates the walkers' largest buffers and halves a walker count left to the engine until they allocate. prepare halves the pool's capacity the same way, but never below the trees it must place. A walker count the caller states is not lowered: a device that cannot hold it refuses the run. This method relies on the driver to report an out-of-memory error. Some drivers stop the device instead. On a device that shares the host's memory, the host can begin to swap before the driver reports anything.