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
|
|
two_prod |
str
|
|
Source code in src/hifuku/wgsl/arithmetic.py
needs_runtime
property
¶
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
¶
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 |
Source code in src/hifuku/wgsl/arithmetic.py
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: |
Source code in src/hifuku/wgsl/device.py
choose_adapter
¶
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
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
rounds_to_nearest
¶
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
fused_fma
¶
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
adapter_summary
¶
Return the adapter's device name, backend and type, for a log or a test.
storage_limit
¶
Return the largest storage buffer, in bytes, that one binding can hold.
workgroup_limit
¶
Return the largest workgroup count that one dispatch dimension can hold.
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
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
clear_pipeline_cache
¶
cached_pipeline_count
¶
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
¶
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
wgsl_f32
¶
Return value as a WGSL hexadecimal f32 literal, without rounding.
Raises:
| Type | Description |
|---|---|
ValueError
|
If float32 cannot hold |
Source code in src/hifuku/wgsl/library.py
pack
¶
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
unpack
¶
Return array name from a packed buffer, as :func:pack received it.
Source code in src/hifuku/wgsl/packing.py
wgsl_offsets
¶
Return the start of each array as a WGSL constant, in words.
initial_states
¶
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
initial_states_reference
¶
The states of :func:initial_states, computed in Python integers.
Source code in src/hifuku/wgsl/xoroshiro.py
next_word
¶
Return the next 64-bit word and advance state, a list [s0, s1].
Source code in src/hifuku/wgsl/xoroshiro.py
jump
¶
Advance state by 2^64 steps.
uniform_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.
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
expm1_source
¶
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
ff_expm1_error
¶
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
|
transition_matrix_error
¶
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 |
Source code in src/hifuku/precision.py
|
form_difference
¶
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
|
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:
walker_ordersgives the post-order of each tree by the depth-first search of the CUDA walk, bit for bit.transition_matrices_ffrebuilds the matrix of every edge.- 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 2from 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 |
Source code in src/hifuku/wgsl/walker.py
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | |
walker_orders
¶
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
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
log_likelihood
property
¶
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
|
walker_product_log_error
¶
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
|
fitness_log_error
¶
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
|
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 |
Source code in src/hifuku/wgsl/placement.py
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
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
rsqrt_source
¶
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
ff_rsqrt_error
¶
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
|
lambda_tolerance
¶
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: |
Higham (2002), kuhner1994branch, robinson1981rf.
|
|
Source code in src/hifuku/precision.py
|
z_squared_tolerance
¶
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
|
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
draws_source
¶
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 |
Source code in src/hifuku/wgsl/moves.py
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
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 | |
normal_draw_error
¶
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
|
scale_factor_band
¶
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
|
The likelihood functions¶
pattern_log_likelihoods
¶
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: |
Source code in src/hifuku/wgsl/likelihood.py
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: |
RuntimeError
|
If |
Source code in src/hifuku/wgsl/likelihood.py
site_values
¶
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
choose_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
self_test
¶
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
pruning_log_error
¶
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 |
Source code in src/hifuku/precision.py
|
weighted_product_log_error
¶
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
|
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
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | |
alloc
¶
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
release
¶
Destroy every buffer, so that the device can give its memory back at once rather than when Python collects the objects.
grid
¶
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
write
¶
Copy array into name from element offset.
Source code in src/hifuku/wgsl/resident.py
read
¶
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
run
¶
Encode steps in order in one submission, and wait for it.
Source code in src/hifuku/wgsl/resident.py
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
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
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | |
write_candidates
¶
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
place
¶
placement_steps
¶
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
place_candidates
¶
Copy a batch into the candidate buffers and place it.
outcomes
¶
(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
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
write_tally_fields
¶
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
tally_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
occupied_slots
¶
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
saturated
¶
read
¶
Slots [lo, hi) of "niche" (int32), "fitness" (float32)
or "z" (float64, from its float-float pair).
Source code in src/hifuku/wgsl/archive.py
read_states
¶
The flat tree states of slots [lo, hi), one row each.
min_occupied_fitness
¶
The smallest elite fitness, or 1e30 when no slot holds one.
Source code in src/hifuku/wgsl/archive.py
counters
¶
(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
set_counters
¶
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
parent_threshold
¶
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
atomic_i64_source
¶
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
gain_is_exact
¶
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
|
gain_error
¶
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
|
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
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | |
set_rng
¶
Set each walker's xoroshiro128+ state, uint64 (M, 2), s0 then s1.
Source code in src/hifuku/wgsl/walk.py
rng
¶
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
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
candidates
¶
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
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.