Skip to content

Port tsdate internals to C - #534

Open
nspope wants to merge 56 commits into
tskit-dev:mainfrom
nspope:numba-to-c-ext-2
Open

nspope wants to merge 56 commits into
tskit-dev:mainfrom
nspope:numba-to-c-ext-2

Conversation

@nspope

@nspope nspope commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Closes #523

There are a number of pre-existing, edge-case likely-to-be-bugs that are flagged in comments here (mostly "NOTE" comments in the tests). I'll deal with these in a followup. gammaincinv from scipy is included in the port under the BSD license, with some minor modifications.

tests/oracle/ holds the numba-jitted code of hypergeo, approx, variational,
rescaling, phasing, util, prior and discrete with the decorators stripped.
These are the reference that every implementation (numba now, the C extension
later) is compared against, and they stay once numba is removed. They were
checked against compiled numba to be bit-identical on large seeded sweeps.

Deviations from the source make plain Python follow compiled numba, and are
marked with '# oracle:' comments:
- log, exp, sqrt, pow, sin, tan follow C semantics (inf/NaN instead of raising);
  lgamma comes from the C runtime (libm, or ucrtbase on Windows) via ctypes,
  because CPython's own lgamma differs by up to thousands of ulp.
- integer powers x**n use repeated squaring, as numba's llvm.powi does.
- sums and means are sequential, as in numba (numpy sums pairwise).
- scalars are Python floats, so a float division by zero raises
  ZeroDivisionError as in numba (error_model="python").
- gammaincinv calls scipy.special.gammaincinv, which the numba cfunc wraps.
- EPFactors is a plain class.

tests/oracle/implementations.py registers the implementations under test, and
the `impl` fixture parametrises tests over them. tests/oracle/helpers.py
compares an implementation with an oracle (values to within a number of ulp,
NaN patterns, in-place updates, raised exceptions); expected_error and
errors_match are where the C extension's LibraryError will be accepted in
place of numba's exceptions. conftest.py adds a seeded rng fixture and small
simulated tree sequences (contemporary, unphased singletons, historical
samples).
evaluation/microbench.py times each array-level numba entry point (EP passes,
rescaling, phasing, util, prior, discrete.logsumexp) on inputs built from
simulated tree sequences at three sizes, with warm-up, median of N repeats,
and compile time reported separately (per dispatcher, and as the difference
in `import tsdate` time with and without NUMBA_DISABLE_JIT). Implementations
are selected with --impl; IMPLS is the seam for adding the C versions. No
changes under tsdate/.

Numba baseline (median seconds per call, 7 repeats; compile_s from numba
dispatcher timers; total compile at import ~43 s). INDICATIVE ONLY: other
jobs were running on this machine, so absolute numbers are noisy.
Sizes: small 20 individuals/1e5 bp, medium 100/1e6, large 1000/5e7
(564k edges, 164k mutations).

function                             small    medium     large  compile_s
propagate_likelihood[edges]       7.93e-04  1.48e-02  1.15e+00    4.20
propagate_likelihood[blocks]      1.12e-04  9.87e-04  5.69e-02    4.20
propagate_prior                   7.52e-06  5.14e-05  2.68e-03    1.63
propagate_mutations[edges]        8.61e-05  1.48e-03  1.68e-01    1.62
propagate_mutations[blocks]       3.58e-05  3.01e-04  2.43e-02    1.62
reallocate_unphased               3.16e-06  4.61e-05  4.71e-03    0.93
_block_singletons                 3.16e-05  3.52e-04  4.76e-02    3.21
_mutation_frequency               5.92e-05  1.26e-03  1.69e-01    1.01
mutational_area                   3.21e-05  4.95e-04  6.18e-02    2.17
mutational_timescale              5.59e-05  5.30e-04  5.47e-02    3.49
piecewise_scale_point_estimate    6.15e-06  6.71e-05  4.40e-03    0.98
piecewise_scale_posterior         2.13e-03  2.62e-02  1.82e+00    3.07
_fixed_changepoints               1.26e-05  1.91e-05  2.19e-04    1.71
_poisson_changepoints             3.56e-04  3.29e-02  1.81e-02    2.22
_count_mutations                  1.77e-05  3.74e-04  1.02e-01    0.82
_split_disjoint_nodes             1.69e-05  7.46e-04  1.35e-01    4.33
_relabel_mutations_node           6.85e-06  9.13e-05  3.10e-02    0.39
_constrain_ages                   6.83e-05  1.06e-03  1.28e-01    0.59
_contains_unary_nodes             2.69e-05  4.38e-04  5.69e-02    0.86
_marginalize_over_ancestors       6.63e-05  1.57e-03  1.86e-01    0.40
conditional_coalescent_variance   6.72e-05  1.58e-03  1.85e-01    0.73
logsumexp                         3.06e-06  1.27e-05  1.38e-04    0.08

Notes: _poisson_changepoints is unused in production and is capped at 2000
intervals, so it is not monotone in size.
…y report

Each function in tsdate.hypergeo and tsdate.approx is compared with its oracle
to within 4 ulp, including which inputs give NaN and which raise:
- edge-case tables: domain boundaries, poles, both sides of each branch switch,
  degenerate parameters, the regimes expectation propagation reaches (fixed and
  free nodes, no mutations, huge shapes, tiny and huge rates), with the outcome
  category (exception, NaN, finite) of each case;
- grids over the special functions (incl. 330 points of gammaincinv, which the
  C port must reproduce bit for bit, as numba wraps cephes igami);
- the 2F1 unity branch against its formula, and the projection invariants (NaN
  exactly when the moments are unusable, inputs returned unchanged);
- one seeded random test per function, over typical and extreme ranges.

test_oracle_numba_libm.py checks the oracle's integer power against numba's
x**n; it goes when numba does.

Accuracy of the approximations themselves is not a property of a port, so it
is reported by evaluation/numerical_accuracy.py rather than tested: error of the
production functions against mpmath, SciPy and closed forms per regime, and
violations of symmetry, monotonicity and continuity at switch points.
…ity report

Each implementation of the variational module is compared with its oracle:
EPFactors, _damp, _rescale (every branch, and the boundaries one ulp either
side), _rescale_factors and _assemble_factors (incl. the rescaling of tiny
scales mid-pass), _check_valid_constraints, and the passes propagate_likelihood,
propagate_prior and propagate_mutations. Inputs are snapshots of real EP state
on the simulated tree sequences (tests/oracle/ep_state.py), with constraints
edited to force every branch, one-edge states for each branch, and tables of
boundary and failure cases (skipped updates, failed projections, EM stopping,
invalid parameters).

Single calls agree to within 4 ulp. Over whole sweeps a difference in the last
bit of an intermediate grows (about 1e-6 relative after the first sweep, 1e-8
after several), so the multi-sweep test allows rtol 1e-4 after the first sweep
and 1e-6 later, with identical patterns of skipped updates.
evaluation/ep_sensitivity.py measures that growth with the production code.

Where compiled numba raises ZeroDivisionError and the plain-Python oracle does
not, the test checks that the implementation raises.
Each jitted function in these modules is compared with its oracle to within
4 ulp, including the arrays it updates in place and the exceptions it raises:
on simulated tree sequences and real EP output, on small hand-built tree
sequences that isolate one case each (no edges, no mutations, gaps, breakpoints,
unsorted input, excluded or fixed nodes, NaN phases), on boundary values of the
arguments, and on one seeded random input per function. Argument validation is
covered by truncating each array argument in turn.

Behaviour that looks wrong is kept and marked "current behaviour, possibly a
bug", so that a port reproduces it and a later fix shows up as a deliberate
test change.
Add lib/hypergeo.c: _digamma, _trigamma, _betaln, _gammainc_der,
_hyperu_laplace, _hyp1f1_laplace and _hyp2f1_laplace (with the unity limit),
following the numba operation order, ipow multiplications and libm calls.
lib/mathutil.h has the shared helpers (ipow, Python min/max, np.isclose).

gammaincinv is not reimplemented: as numba did, SciPy's is called through the C
API of scipy.special.cython_special. The module reads the capsule
__pyx_capi__["gammaincinv"] at import (using the capsule's own name for the
pointer lookup; the import fails with ImportError if SciPy or the symbol is
missing) and keeps the pointer in a module-level static. The library has no
global state and no SciPy dependency: tsd_gammaincinv_fn, a function pointer
type documented in tsdate.h, is passed as an argument to the library functions
that need it (none yet in this commit). gammainc_inv is exposed as a scalar
function.

Errors: new codes TSD_ERR_INVALID_HYPERGEO (every violated domain assertion of
the hypergeometric functions and of _gammainc_der, and a root on the boundary)
and TSD_ERR_ZERO_DIVISION (numba's ZeroDivisionError). Divisions are checked
only where the tests reach them: the poles of digamma/trigamma, the Laplace
root of hyperu/hyp1f1/hyp2f1, 1/v in hyperu, and c - a in hyp2f1. NaN and
infinite results stay in-band.

_tsdatemodule.c exposes scalar C functions through one table (name, number of
inputs, number of outputs, adapter), with one generic wrapper that returns a
float or a tuple and maps library errors to _tsdate.LibraryError.

Tests: the oracle implementation registry gets a "c" entry whose unported names
skip; expected_error/errors_match accept LibraryError (and ValueError for an
oracle AssertionError); tests of the wrapper, of gammainc_inv against SciPy and
of the import failure without SciPy's Cython API; CUnit smoke and error-path
tests. The microbenchmark harness gets an (empty) C implementation and skips
functions it lacks.
Add lib/approx.c, following the numba operation order and libm calls, with every
function registered in the module's scalar table and in the "c" test
implementation, agreeing with the oracles to within 4 ulp:
- the helpers: approximate_log_moments, approximate_gamma_kl,
  approximate_gamma_mom, approximate_gamma_iqr (the gammaincinv it needs is
  passed in as a tsd_gammaincinv_fn), average_gammas (an array-level function)
  and the _valid_* predicates;
- the node moments (moments, rootward, leafward, unphased, twin, sideways) and
  their projections;
- the mutation moments (incl. edge and block) and their projections.

lib/tsdate.h documents the signature convention: natural parameters in, outputs
through pointers written on success, int return. Moments return NaN in every
output when the parameters are outside the valid region of the hypergeometric
functions (in-band, as in numba). Projections then return a NaN normalising
constant and their input parameters unchanged (node projections), or NaN
probability and parameters (mutation projections).

Errors: every KLMinimizationFailedError message becomes an error code whose
tsd_strerror text is the numba message verbatim (nonpositive or nonfinite moments,
Jensen's inequality, maximum iterations in KL minimization, invalid shape,
nonpositive central moments, unsorted quantiles, maximum iterations in quantile
matching, negative shape). The asserts of approximate_log_moments become
TSD_ERR_NONPOSITIVE_MOMENTS, and those on the age of a fixed node
TSD_ERR_INVALID_FIXED_AGE. Divisions by zero that numba raises on and the tests
reach (mean ** 2 underflowing, a zero shape bound, an empty or zero-rate average,
zero quantiles, a vanishing quantile gradient, r or r ** 2 zero in the twin
moments) return TSD_ERR_ZERO_DIVISION; divisions that only vanish in regimes no
test reaches follow IEEE semantics. Errors of the hypergeometric functions
propagate.

Tests: the C parametrisations of the approx oracle tests; error messages, argument
checking of average_gammas, and failures of the quantile fit that the oracle tests
do not reach; CUnit smoke and error-path tests.
Adds lib/phasing.c (block_singletons, reallocate_unphased, mutation_frequency),
lib/util.c (split_disjoint_nodes, relabel_mutations_node, constrain_ages,
contains_unary_nodes, and a stable argsort) and lib/prior.c
(marginalize_over_ancestors, conditional_coalescent_variance), with the module
wrappers, C smoke tests, the "c" entries of the oracle test fixture and of the
microbenchmarks, and low-level tests of the error paths.

Error codes: the asserts reached by the tests become TSD_ERR_UNPHASED_INDIVIDUAL_EDGES
(an individual with more than two edges, or a block never completed),
TSD_ERR_BLOCK_OUT_OF_RANGE, TSD_ERR_PHASE_OUT_OF_RANGE,
TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED, TSD_ERR_MUTATION_NODE_NOT_IN_TREE and
TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT. Size asserts are ValueErrors in the module.

Deliberate deviations from numba, which is undefined where the C code is defined:
block_singletons sizes its per-individual state by individuals, not by edges;
conditional_coalescent_variance(1) returns two zeros instead of reading past the
end; relabel_mutations_node with no edges leaves every mutation NULL instead of
indexing an empty array; out-of-range block ids in reallocate_unphased are an error.
Adds lib/rescaling.c with _fixed_changepoints, _poisson_changepoints,
_count_mutations, mutational_area, mutational_timescale,
piecewise_scale_point_estimate and piecewise_scale_posterior, exposed from
_tsdatemodule.c as array-level functions, and registers them in the "c"
implementation of the oracle tests and of the microbenchmarks.

Error codes: the changepoint and interval-count asserts share
TSD_ERR_NONPOSITIVE_INTERVALS and TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER;
"Zero edge span in interval", the non-increasing breakpoint ValueError, the
quantile width, posterior domain and below-first-breakpoint asserts each have a
code, with the numba messages where numba had one. A zero lower quantile or
mean in piecewise_scale_posterior gives TSD_ERR_ZERO_DIVISION. Size and shape
asserts are checked in the module and raise ValueError; the others, that cannot
be reached, are tsd_bug_assert.

Deviations from numba: no out-of-bounds access (negative slice and index
wrap-around are done explicitly); the sorts are not those of numba but ties do not
affect the results.
Adds lib/variational.c: _damp, _rescale, _rescale_factors, _assemble_factors,
_check_valid_constraints, propagate_likelihood (the closure dispatch over edge
types is a set of per-branch functions), propagate_prior and propagate_mutations.
The EP state stays in numpy arrays owned by Python: the factors are passed to the
module as a tuple of the eight arrays of an EPFactors and updated in place, and the
GIL is released around each pass. _damp and _rescale are in the scalar table.
Results are bit-identical to numba on four sweeps of the test tree sequences.

Errors (new codes -30 to -36):
- max_shape < 1 (or NaN) and 0 < min_step < 1 failing are parameter errors with
  messages (TSD_ERR_INVALID_MAX_SHAPE, TSD_ERR_INVALID_MIN_STEP);
- the posterior asserts of _damp and _rescale (TSD_ERR_INVALID_NODE_POSTERIOR), the
  damping assert 0 < d <= 1 (TSD_ERR_INVALID_DAMPING), propagate_prior's
  penalty > 0 (TSD_ERR_NONPOSITIVE_PENALTY), and the twin_projection assert that an
  edge with equal parent and child is only used in an unphased pass
  (TSD_ERR_TWIN_EDGE_IN_PHASED_PASS);
- _check_valid_constraints raises TSD_ERR_INCONSISTENT_CONSTRAINTS, with numba's
  message verbatim;
- divisions where numba raises ZeroDivisionError and a test pins it (_damp by y,
  _rescale by x[0]) return TSD_ERR_ZERO_DIVISION; errors of the approx projections
  are forwarded;
- array size and shape asserts are ValueError in the module. Arrays that are updated
  in place must not need converting (a copy would lose the update), so they raise
  ValueError instead of being copied.

Deviations from numba: array sizes are checked in the module, but node and edge ids
are not; lognorm must have one entry per edge.

The oracle tests of tests.oracle.variational now run against C, with adapters in
implementations.py; microbench registers the three passes for C.
Production code now calls _tsdate instead of numba.

- hypergeo, approx: removed. Nothing in tsdate calls them any more (the C passes
  call the special functions and gamma approximations directly), and they were
  not documented. Their tests (test_hypergeo.py, test_approximations.py) and
  evaluation/numerical_accuracy.py call the _tsdate functions instead, with
  imports and names updated (e.g. hypergeo._digamma -> _tsdate.digamma) and a
  failed KL minimisation expected as _tsdate.LibraryError with the same message.
  The oracles define their own KLMinimizationFailedError.
- phasing, util, prior, rescaling: the jitted functions are the _tsdate
  functions; the piecewise rescaling functions check for increasing
  breakpoints in Python first, so the user-facing ValueError is kept.
- variational: EPFactors is a plain class of numpy arrays; the EP passes
  call _tsdate with factors.arrays(). The ValueError for inconsistent
  node age constraints is kept.
- discrete: the jitted logsumexp is scipy.special.logsumexp, and the row
  sums use np.logaddexp.reduceat (calling scipy per row made
  inside_outside ~44x slower).
- reallocate_unphased now refuses arrays that would have to be copied (as
  the variational wrappers do), with a test; the other in-place wrappers
  already used the same helper.
- The "numba" implementation is removed from the oracle test registry and
  from evaluation/microbench.py (default --impl c, no compile-time
  reporting); the discrete oracle and its test are removed.

logsumexp, numba vs scipy.special.logsumexp: 1.3M calls from test_functions,
test_inference and test_cli (inside_outside): max abs 5.7e-14, no -inf or NaN
mismatches; 20000 random rows incl. -inf entries and all -inf rows: max abs
5.7e-14, max rel 1.0e-13 (|value| > 1e-6).

End to end tsdate.date, numba tree (3f3afdd) vs this tree, median of 3 runs
excluding import/compile (numba: import 39 s, first-call warm-up 1.1 s;
C: import 0.75 s, warm-up 3.3 s):
  small 25 dip x 1 Mb gamma:   node times identical; 0.368 s -> 0.239 s
  medium 500 dip x 10 Mb:      node times identical; 7.05 s -> 4.35 s
  singletons_phased=False:     node times identical; 2.66 s -> 1.68 s
  inside_outside:              max abs 3.6e-11, max rel 2.6e-15;
                               1.94 s -> 2.06 s
- The multi-sweep test of the EP passes now requires the C implementation to
  match the oracle exactly: it does, on every sweep. The relative tolerances
  that allowed for last-bit differences between numba and the oracle are gone,
  and with them evaluation/ep_sensitivity.py, which measured how such
  differences grow over sweeps.
- test_oracle_helpers.py keeps only the tests that show the comparison helpers
  detect disagreements (values, NaN and infinity patterns, exceptions, in-place
  updates, library error mapping).
- test_python_c_approx.py: drop the test of the test adapter for projections.
- test_python_c_scalar.py: gammainc_inv is SciPy's function called through its
  C API, so a few values (including outside the domain) replace the grid and
  random draws.
- Remove tests/distribution_functions.py: nothing imports it, and it calls
  functions that no longer exist.
- Remove tsdate/accelerate.py and the numba dependency, with the numba cache
  setting (TSDATE_ENABLE_NUMBA_CACHE) and its documentation.
- cibuildwheel: build musllinux wheels and test the macOS x86_64 ones; both
  were skipped only because numba publishes no wheels there. win32 stays
  skipped (no scipy wheels).
- Tests: the oracle tests run against the C implementation only, so the
  registry of implementations and its skipping of unported functions are gone,
  as is the test of the oracle's integer powers against numba and the helper
  for calling numba cfuncs.
- evaluation: microbench.py times the C functions without an implementation
  switch; performance.py no longer warms up or caches numba compilation.
Comments and docstrings of the C library, the module, the oracles and their tests
now say what the code does rather than how it relates to the numba code it
replaced. The scalar adapters of _tsdatemodule.c are renamed scalar_* (from
adapt_*), matching the rest of the scalar-function machinery. The single-tip
prior test no longer stubs out conditional_coalescent_variance(1), which the C
library handles.
The oracles' headers explain where plain Python differs from C; the inline
'# oracle: ipow' (float, seq_sum, seq_mean) tags repeated that on each line.
Other explanatory comments lose the 'oracle:' prefix.
block_singletons and mutation_frequency had TODO docstrings; they now describe
their arguments, results and requirements. Each oracle that had no docstring (or
a TODO) gets a one-line summary of what it returns, and the comment of
tsd_mutation_frequency says that the counts are per mutation.
tsd_check_valid_constraints returned an error code that the Python wrapper
translated back into a ValueError. It is now tsd_constraints_are_consistent,
which reports the result through an output flag; ExpectationPropagation raises
the ValueError (same message as before) itself. TSD_ERR_INCONSISTENT_CONSTRAINTS
is removed and the two codes after it are renumbered.
C agrees with the oracles bit for bit on every test, so the 4-ulp tolerance
(assert_ulp_close and the maxulp parameters) is replaced by exact equality
(assert_same_values). Also removes the unused helper both(), assert_inplace_close
(the same comparison as assert_same_values on a list), and the fallback for an
unbuilt extension around the LibraryError import.
The C tests check return codes; numerical correctness is tested from Python
against SciPy's gammaincinv. The series-and-bisection inverse in tests.c is
replaced by a placeholder that ignores the shape, with inputs chosen to reach
the same branches of the interquantile fit (and its iteration limit and
derivative errors). The two rare branches of the incomplete gamma derivative
that the stand-in reached incidentally are now tested directly.
The oracle tests call the _tsdate functions directly and compare them with
the oracles. Where the C signature differs from the oracle's, a small adapter
in the test module that needs it bridges the two: projection flattening and
the bool result of the _valid_* checks in test_oracle_approx.py, and the
EPFactors unpacking and size-two parameter pairs in test_oracle_variational.py.
The ep_state runners take the propagate functions they call, and
Snapshot.factors always builds the oracle EPFactors.
The size checks of the damp/rescale adapters and the EPFactors constructor test
compared test code with itself; the C functions take scalars and the factors are
always the oracle's. Comments name what the C library does rather than compiled
code.
test_oracle_approx and test_oracle_hypergeo look up the C function for each
oracle in a table instead of deriving its name and adapter from the oracle's.
Add lib/gammaincinv.c, a C translation of xsf's cephes igami (the
implementation of scipy.special.gammaincinv) and the functions it
reaches, and call it directly from the approx and rescaling functions.
This removes the gammaincinv function-pointer parameter and the loading
of SciPy's Cython gammaincinv at module import, so _tsdate no longer
imports SciPy.

The port agrees bit for bit with scipy.special.gammaincinv (SciPy
1.18.1) on 3 million random points across regimes, including the
complemented inversion, tiny quantiles and arguments outside the domain.
tsd_gammaincinv returns NaN directly for a < 0, p outside [0, 1], and a = 0 or
a = inf with 0 < p < 1 (p = 0 and p = 1 still give 0 and inf), instead of letting
the computation run into NaN. Inside the domain the results are unchanged and
identical to scipy.special.gammaincinv (0 mismatches in about 4 million points).
The helpers keep only the branches their arguments can reach: Gamma is only
called for 0 < x < 1 and lgam for positive finite x, so the poles, the
reflection formulas, Stirling's formula, sinpi and the sign of lgam go, as do
the checks on the shape in igam and igamc. The oracle applies the same domain.
Four inputs found by fuzzing reach the remaining lines that any valid argument
reaches: cephes log1p, a NaN Halley iterate in igam and igamc, lgam1p's Taylor
series at zero and erfc of a negative argument.
The branches kept from xsf that no valid argument reached in 20 million random
draws carry GCOVR_EXCL markers, and the file header says so; gcovr (and so the
coverage reports) leaves them out.
NumPy's SIMD log and exp differ from libm in the last bit on some CPUs (the
Ubuntu CI runners), so the exact comparisons with the C library failed there.
The prior oracle now uses the libm wrappers of _libm, as the other oracles do.
SciPy's arm64 macOS wheels fuse multiply-adds in gammaincinv, so the port differs
from them by about 1e-15 relative, and the interquantile fits amplify that. The
oracles now take gammaincinv from the C library, as they take libm, so the
oracle comparisons of approx and rescaling stay exact everywhere. TestGammaincInv
compares the port with scipy.special.gammaincinv: exactly on x86-64 (Linux and
Windows CI agree bit for bit), and to 1e-11 relative elsewhere (a build of the
port with fused multiply-adds differs by at most 4e-13 over 600000 points).
The reference implementation bumps a parent only when a child is at least
as old, whereas constrain_ages keeps parents at least epsilon above their
children. Noise that leaves a parent within epsilon of a child makes the two
differ by up to epsilon, which fails the comparison in about 0.08% of seeds.
@nspope
nspope marked this pull request as ready for review November 27, 2026 03:35

@jeromekelleher-bot jeromekelleher-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 AI generated message

Thanks @nspope, this is a huge piece of work and the numerics look right to me: I get the same node times as main to 11 figures on all three methods, import drops from 45s to 2s, and variational_gamma is about 1.6x faster.

The part that needs more work before we merge is the Python C layer, which is where we're strictest elsewhere in tskit-dev, because it is hard to keep fully correct. I'd like it to be as small and as conventional as we can make it.

  1. Please cut _tsdate down to the functions tsdate calls. 53 of the 72 exports are there only so the tests can reach internal C functions: all 49 scalar functions, average_gammas, fixed_changepoints, poisson_changepoints and marginalize_over_ancestors. Each export has to be crash-proof and tested for argument handling, and that isn't worth it for functions nobody calls. Instead, test the internal functions in lib/tests/tests.c, with about 10 input/output examples each computed from your current oracle and picked to reach each branch. The C tests are already at 93% of lib/, so this is mostly adding value checks.

    That means most of the oracles can go once the tables are generated. They did their job: the port is bit-identical to the numba code everywhere I looked. I'd only keep an oracle where C tests can't reasonably cover the code, and I think that is at most oracle/phasing.py and oracle/util.py for the tree-sweep functions, which are single-tree in the C tests at the moment and are all in the minimal interface anyway. The EP oracle can't be kept by itself because it imports the approx and hypergeo ones. Before deleting anything, could you move the "NOTE: possibly a bug" list into an issue? Also, tests/test_hypergeo.py and tests/test_approximations.py (the checks against mpmath and quadrature) use the scalar exports; those are worth keeping as C tables of mpmath values.

  2. Could _tsdatemodule.c follow the pattern in _tskitmodule.c and _tsinfermodule.c more closely? One explicit wrapper per function in the static method table (no table-driven dispatch, which goes away with the scalar exports); PyArg_ParseTupleAndKeywords with the Python callers passing keywords; each array converted to a named variable with PyArray_FROMANY and released at out, without the parse_arrays/arrays[n] helpers; and one tests/test_python_c.py, which is what the shared CI workflow runs. At the moment that job runs 17 tests and reports 3% coverage of _tsdatemodule.c, because the new tests are in tests/test_python_c_*.py.

    The biggest part of this is the EP state. At the moment the factors go to every call as a tuple of eight arrays, with the posterior and log-constants updated in place. Could that be a tsd_ep_t in the library with tsd_ep_init/tsd_ep_free, wrapped by one Python type, with the passes as methods and the posteriors as read-only properties? That's how we hold state in tskit and tsinfer (AncestorBuilder in _tsinfermodule.c is a small example). It gets rid of parse_factors, get_inout_array and the 11-argument signatures, and the ids only need validating once in init, not on every pass. reallocate_unphased can then return a new array, and nothing updates a caller's array in place.

  3. The library doesn't validate ids, so most of the array functions segfault if called from Python with an out-of-range node or edge id, e.g. _tsdate.constrain_ages(np.array([0., 1.]), np.array([True, False]), np.array([2**30], dtype=np.int32), np.array([0], dtype=np.int32), 0.1, 3). I know tsdate never does this, but our rule is that nothing reachable from Python can crash the interpreter. Could the library return TSD_ERR_NODE_OUT_OF_BOUNDS-style errors, as tsd_reallocate_unphased already does for blocks, with C and Python-C tests for each? Some signatures will need a size argument added (tsd_block_singletons has no num_nodes, tsd_propagate_mutations has no num_mutations).

    Two related cases with ids in range: the tree sweep in contains_unary_nodes, count_mutations, mutation_frequency and block_singletons never terminates if an edge's right coordinate is greater than sequence_length, and block_singletons hits tsd_bug_assert at phasing.c:62 (so abort()) for an unphased individual with a zero-length edge. I think tsd_bug_assert should be kept for internal invariants and anything a caller can get wrong should come back as an error code.

  4. For the functions that remain, each needs tests for wrong argument counts, bad dtypes and dimensions for every array argument, mismatched lengths, and each library error. Thirteen of them have no wrong-argument-count test and eight have no bad-array test at the moment.

One question: inside_outside and maximization come out 10–35% slower for me, I think from swapping the jitted logsumexp for SciPy's in discrete.py. Is that expected and OK for those methods?

Smaller things inline.

Comment thread _tsdatemodule.c Resolved
Comment thread _tsdatemodule.c Resolved
Comment thread _tsdatemodule.c Resolved
Comment thread _tsdatemodule.c Resolved
Comment thread _tsdatemodule.c Resolved
Comment thread tsdate/rescaling.py Resolved
Comment thread lib/gammaincinv.c Resolved
Comment thread lib/tsdate.h Resolved
Comment thread tsdate/discrete.py Resolved
Comment thread CHANGELOG.md Resolved
@jeromekelleher

Copy link
Copy Markdown
Member

This looks great overall @nspope - hopefully you can pass the review directly to your agent, and that'll make iteration reasonably painless?

np.logaddexp.reduceat computes an exponential and a logarithm per element,
which made the inside-outside and maximization methods 10-15% slower than
the numba row sums. A max-shifted sum per row with np.maximum.reduceat and
np.add.reduceat is faster than both.
Functions given node, edge or individual ids now check them and return
TSD_ERR_NODE_OUT_OF_BOUNDS, TSD_ERR_EDGE_OUT_OF_BOUNDS or
TSD_ERR_INDIVIDUAL_OUT_OF_BOUNDS instead of reading or writing out of
bounds. The tree sweeps check that every edge has 0 <= left < right <=
sequence_length and that the insertion and removal indexes list every edge
once in order of position, the conditions under which the sweep terminates;
the ancestor walks stop with TSD_ERR_EDGES_FORM_CYCLE. tsd_block_singletons
takes the number of nodes. Too few tips and no breakpoints are errors of the
library rather than assertions or checks in the module.
BLOCK_OUT_OF_RANGE becomes BLOCK_OUT_OF_BOUNDS.
…ule conventionally

The library holds the EP state in tsd_ep_t, with tsd_ep_init (which copies
the inputs and validates the node ids once) and tsd_ep_free; the passes are
functions of it, and tsd_ep_propagate_mutations returns the posteriors and
phases of the mutations above given edges. _tsdate.ExpectationPropagation
wraps it, with the passes as methods and copies of the posteriors and log
normalising constants as read-only properties.

Each function of the module that tsdate calls has its own wrapper, parsing
keyword arguments (which the callers pass) into named arrays. No function
updates a caller's array: reallocate_unphased returns the reallocated
likelihoods. block_singletons no longer takes the unused edge parents, and
contains_unary_nodes takes the number of nodes from the mask.

The oracle has an ExpectationPropagation with the same methods, and the EP
equivalence tests run the same passes on both from the same inputs. States
that tests set directly to reach branches (single edges with chosen
cavities, scales at the rescaling threshold, failing projections) are tables
of the C tests, with expected values from the reference implementation,
compared within 4 ulps.
The low-level module's tests are in the one file that the shared CI workflow
runs. Every function that tsdate calls is tested for keyword and positional
arguments, too few or too many arguments, unknown keywords, the type and
dimension of each array, numerical arguments of the wrong type, arrays that
must have the same length, two-column arrays, and each error of the library
that it reports. The comparisons with the oracle on inputs that tree
sequences cannot produce join the other rescaling oracle tests.
_tsdate now exports only what tsdate calls, plus strerror and
raise_library_error. The scalar functions, average_gammas,
marginalize_over_ancestors, fixed_changepoints and poisson_changepoints are
tested by the tables in lib/tests/tests.c instead, and the reference
implementations of approx, hypergeo, prior, rescaling and variational are
deleted with their tests, as are the mpmath and quadrature tests that the
tables carry. tsd_average_gammas and tsd_poisson_changepoints had no callers
and are deleted with their error code.
…ctypes

meson also builds the library as a shared library, which evaluation/clib.py
loads with ctypes to call the scalar functions, which _tsdate no longer
exports. numerical_accuracy.py uses it, and microbench.py calls the current
module: the expectation propagation passes through
_tsdate.ExpectationPropagation, and every function with keyword arguments.
@nspope

nspope commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

on removing Python handles for low-level special functions: I need to access these for numerical benchmarking and debugging, as they're approximations that might break down in some regimes. I agree about not bloating the CPython API with a bunch of stuff no-one but me will access, however. So what I've done as a compromise is add a rule for a dynamic library to the meson build, and then use ctypes to load that in evaluation/numerical_accuracy.py.

… mutation

The library checks the edges of a block only when a mutation is in it, and
block 0 of the test's tree sequence need not hold one (it does not on Windows).
Each function has a class of plain tests: the arrays that must have the same
size, and each library error, with the arguments built inline. The tables of
argument specifications and edit combinators are gone. Argument parsing and
the checks of edge sweeps are parametrised over the functions, each with a
function that returns valid keyword arguments.
The tests call the functions and their oracles with keyword arguments, through
two helpers: assert_same_result and assert_same_error. The outcome classes and
their tests are gone, and the oracles no longer check the sizes of arrays,
which tests/test_python_c.py tests in the module.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Numba compilation takes a long time

3 participants