Skip to content

Initial numba module - #3225

Merged
benjeffery merged 1 commit into
tskit-dev:mainfrom
benjeffery:numba
Aug 15, 2025
Merged

benjeffery merged 1 commit into
tskit-dev:mainfrom
benjeffery:numba

Conversation

@benjeffery

Copy link
Copy Markdown
Member

Part of #3135

@benjeffery

Copy link
Copy Markdown
Member Author

I've done quite a bit of numba investigation and found a way to use dataclasses in numba code. This seems to come at very little performance cost compared to tuples and is a lot nicer. Using a generator also seems to work fine!

@codecov

codecov Bot commented Jun 18, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.91667% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.72%. Comparing base (0ea8e64) to head (7763594).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
python/tskit/jit/numba.py 97.91% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3225      +/-   ##
==========================================
+ Coverage   89.67%   89.72%   +0.04%     
==========================================
  Files          28       29       +1     
  Lines       32308    32500     +192     
  Branches     5933     5949      +16     
==========================================
+ Hits        28972    29160     +188     
- Misses       1892     1894       +2     
- Partials     1444     1446       +2     
Flag Coverage Δ
c-tests 86.71% <ø> (ø)
lwt-tests 80.38% <ø> (ø)
python-c-tests 88.24% <ø> (ø)
python-tests 98.79% <ø> (ø)
python-tests-no-jit 32.61% <97.91%> (?)
python-tests-numpy1 50.99% <0.00%> (-1.29%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
python/tskit/jit/numba.py 97.91% <97.91%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@benjeffery

Copy link
Copy Markdown
Member Author

Having some CI weirdness that I'm not yet able to recreate.

@benjeffery

Copy link
Copy Markdown
Member Author

CI Fixed.

Here's some benchmarking with the "coalescent_nodes" method from #2778 on a TS with 12M edges:

Using ts.edge_diffs: 23.3s
Calculating edge diffs and coalescent nodes in a single numba.njit function: 0.085s
Using the classes here, calculating coalescent nodes in separate client numba.njit function: 0.093s

@jeromekelleher

Copy link
Copy Markdown
Member

Shall we move the first commit into its own PR? It's cluttering up this one and making it hard to see the real changes.

@jeromekelleher

Copy link
Copy Markdown
Member

I had imagined something lower level that was basically a copy of the TreePosition class from here: https://github.com/jeromekelleher/sc2ts/blob/7758245c3dc537aeec3b7cd6282241b65f8843dd/sc2ts/jit.py#L107

So, we don't try to provide Pythonic APIs, but just provide direct access to the edges out and edges in, which can be numba compiled like the example in the sc2ts code.

@benjeffery

benjeffery commented Jun 19, 2025 •

Copy link
Copy Markdown
Member Author

just provide direct access to the edges out and edges in

That's how this code works,
Your sc2ts code here:

    while tree_pos.next():
        for j in range(tree_pos.out_range[0], tree_pos.out_range[1]):
            e = tree_pos.edge_removal_order[j]
            c = edges_child[e]
            p = edges_parent[e]
            parent[c] = -1
            u = p
            while u != -1:
                num_samples[u] -= num_samples[c]
                u = parent[u]

becomes

    for tree_pos in numba_ts.edge_diffs():
        for j in range(*tree_pos.edges_out_index_range):
            e = numba_ts.indexes_edge_removal_order[j]
            c = edges_child[e]
            p = edges_parent[e]
            parent[c] = -1
            u = p
            while u != -1:
                num_samples[u] -= num_samples[c]
                u = parent[u]

It is still compiled, and 30% faster (for the coalesent nodes example)!

@jeromekelleher

Copy link
Copy Markdown
Member

Ahh, I didn't spot that sorry. How is it faster then?

I do think we should just stick with the TreePosition interface though, because we want to support seeking backwards as well, and ultimately randomly. There's no point in adding a layer for indirection on top of that.

@benjeffery

Copy link
Copy Markdown
Member Author

How is it faster then?

Mutating numpy arrays to maintain the state involves the following:

  1. Creating a temporary list (build_list).
  2. Performing bounds checks for the slice.
  3. Copying the data from the list into the array's memory.

Whereas yielding lightweight immuatable objects is much more amenable to numba optimisation. We might be able to get the same gains by using native objects for the state rather than numpy arrays if you are set against iteration.

@jeromekelleher

Copy link
Copy Markdown
Member

Let's talk it through in person - I don't have time to form an educated opinion I'm afraid.

@benjeffery
benjeffery force-pushed the numba branch 2 times, most recently from 7aa7151 to 5d22c6c Compare June 27, 2025 15:22
@benjeffery

Copy link
Copy Markdown
Member Author

I've tried to closely match the exisiting tsutil implementation with next and prev. Need to so some perf checks with this new code under numba.

@benjeffery

Copy link
Copy Markdown
Member Author

New code looks just as fast, proceeding to add some more tests. Will merge this then before doign docs.

@benjeffery

Copy link
Copy Markdown
Member Author

Getting some weird failures on Windows here, and coverage not counting for the new module, will fix.

I've added a stab at some docs.

@hyanwong

hyanwong commented Jul 3, 2025 •

Copy link
Copy Markdown
Member

Re docs, eventually we probably want a "high performance" tutorial with some of this stuff, but I can have a stab at that after 1.0. There's some comments here: tskit-dev/tutorials#150 (comment) and some code examples at tskit-dev/tutorials#63

Comment thread docs/numba.md Outdated
print(type(numba_ts))
```

## Tree Traversal

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I normally think of "tree traversal" as iterating through the tree structure itself. Do you mean "Iterating through trees" here? I can't see any pre/postorder traversal code here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good point, I was avoiding the word "iteration" not not confuse it with a Python iterator - but I'll change it back as this is more confusing!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe just "moving between trees"?

Comment thread python/tskit/jit/numba.py Resolved

@jeromekelleher jeromekelleher left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks great. Not obvious to me why we're setting up the tests like this though.

Comment thread python/tests/test_jit.py

NODE_IS_SAMPLE = tskit.NODE_IS_SAMPLE

@numba.njit

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why are importing the jit module within the test functions here and defining the algorithm? I think we can assume that developers have numba installed, and there's pytest ways of skipping the module for CI?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Further up the test file we test importing the tskit.jit.numba module while it is mocked out, which needs the module to not be imported. I could try and find another way to do that which doesn't require all the local imports?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe do that test in its own module so? The local import stuff will confuse people in to thinking it's necessary and the LLMs might also get this idea from the example code.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I've fixed by making the imported module look absent in the test that requires it to be, and have removed the function-local imports.

@benjeffery
benjeffery force-pushed the numba branch 4 times, most recently from 4e4c0d3 to 40aa349 Compare August 13, 2025 11:59
@benjeffery
benjeffery marked this pull request as ready for review August 13, 2025 13:06
@benjeffery

Copy link
Copy Markdown
Member Author

@jeromekelleher Still a coverage issue that I understand and am fixing - but modolo that this is ready for a review and merge. I've started some benchmarking with the French-Canadian dataset, but will PR changes from that separately.

@benjeffery benjeffery mentioned this pull request Aug 13, 2025

@jeromekelleher jeromekelleher left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks great overall. I'm still uncomfortable with the code duplication (especially docstring comments - they are guaranteed to diverge). Maybe we could have the main version of the class be compiled assuming that we have single-char alleles, and do the funky stuff otherwise?

See also comment about names and external API

Comment thread python/tskit/jit/numba.py Outdated
"""
return NumbaTreeIndex(self)

def diversity(self):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't think this belongs here - diversity is an example calculation that provide that uses the jit wrapper, it's not an API we provide. The jit wrapper only provides functionality for people to write their own algorithms.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, sorry forgot to move it back as it was easier to develop in the class.

Moved to tests and docs in a172606

Comment thread python/tskit/jit/numba.py Outdated
tree_index_spec = []
else:
tree_index_spec = [
("ts", NumbaTreeSequence.class_type.instance_type),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Does this class (NumbaTreeIndex) also depend on the size of alleles? Can we shift it outside of the cache?

@benjeffery benjeffery Aug 14, 2025 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This class has to hold a reference to the tree sequence, so numba has to be told the concrete type of NumbaTreeSequence, which we only know once allele lengths are known.

Comment thread python/tskit/jit/numba.py Outdated
return NumbaTreeSequence


def numba_tree_sequence(ts):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

API-wise, I wonder if we're overnaming things here with tskit.jit.numba.numba_tree_sequence() - it's getting almost Java-esque! How about something like

nts = tskit.numba.jitwrap(ts) # Returns a NumbaTreeSequence

"jitwrap" is descriptive and feels like it's something that could in principle be extended to other JIT engines

tree_index = jts.tree_index()

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Renamed to jitwrap in de1d804

@jeromekelleher jeromekelleher left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Some more comments

Comment thread python/tests/test_jit.py Resolved
Comment thread python/tests/test_jit.py Outdated
assert numba_ts.indexes_edge_insertion_order.dtype == np.int32
assert numba_ts.indexes_edge_removal_order.dtype == np.int32
assert numba_ts.breakpoints.dtype == np.float64
np.testing.assert_array_equal(numba_ts.breakpoints, ts.breakpoints(as_array=True))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We're not testing the string fields here - what about sites_ancestral_state etc?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 29759d0

Comment thread python/tests/test_jit.py Outdated
assert numba_ts.num_trees == ts.num_trees
assert numba_ts.num_edges == ts.num_edges
assert numba_ts.sequence_length == ts.sequence_length
np.testing.assert_array_equal(numba_ts.edges_left, ts.edges_left)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

usually use ``import numpy.testing as nt; nt.assert_array_equal()```

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 6686ad0

Comment thread docs/numba.md

assert jit_num_edges == python_num_edges, "JIT and normal results do not match!"
```

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think we want to include the diversity calculation here in the documentation - we want to have a real example that people can use as a starting point.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done in a172606

@benjeffery

Copy link
Copy Markdown
Member Author

I'm still uncomfortable with the code duplication

I've figured out a solution to this in 41f5927

I've addressed the rest of the comments

@jeromekelleher jeromekelleher left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fantastic! Let's this much in and build on it.

@benjeffery
benjeffery force-pushed the numba branch 4 times, most recently from 4b73401 to f43c89e Compare August 15, 2025 10:00
@benjeffery
benjeffery enabled auto-merge August 15, 2025 10:22
@benjeffery
benjeffery added this pull request to the merge queue Aug 15, 2025
Merged via the queue into tskit-dev:main with commit d1eb1b4 Aug 15, 2025
@benjeffery benjeffery mentioned this pull request Sep 22, 2025
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.

3 participants