Repository navigation
Description
Warning
This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.
Describe the bug and give evidence about its user-facing impact
In BinaryTree.query(), we have:
self.n_trims = 0
self.n_leaves = 0
self.n_splits = 0and these are incremented in methods called by query(). Since a tree can be simultaneously used from multiple threads:
- The statistics will be garbage, as the numbers will get overwritten by different threads.
- It's possible that this will slow down operation as the same memory needs to be pushed between caches across CPU cores.
Steps/Code to Reproduce
import threading
import numpy as np
from sklearn.neighbors import KDTree
samples = np.random.rand(10_000, 10)
query_points = np.random.rand(10_000, 10)
tree = KDTree(samples, 10)
def run_and_get_stats():
tree.query(query_points, dualtree=False, breadth_first=False, sort_results=False)
return tree.get_tree_stats()
# Single-threaded version, resets stats to zero:
print("Single threaded:")
assert run_and_get_stats() == run_and_get_stats()
print("OK")
# Threaded version:
print("Threaded:")
thread_stats = set()
threads = []
for _ in range(10):
t = threading.Thread(target=lambda: thread_stats.add(run_and_get_stats()))
threads.append(t)
t.start()
for t in threads:
t.join()
assert len(thread_stats) == 1
assert thread_stats.pop() == run_and_get_stats()
print("OK")Expected Results
Running in parallel should, given the current contract, give the same results. This is not really possible.
So really the API should be changed so query() does not reset to zero, and instead increments existing stats.
Actual Results
Single threaded:
OK
Threaded:
Traceback (most recent call last):
File "/home/itamarst/devel/scikit-learn/binarytree_threadsafety.py", line 29, in <module>
assert len(thread_stats) == 1
^^^^^^^^^^^^^^^^^^^^^^
AssertionError
Versions
System:
python: 3.14.5 free-threading build (main, May 11 2026, 11:48:49) [GCC 13.3.0]
executable: /home/itamarst/devel/scikit-learn/venv314t/bin/python machine: Linux-6.18.7-76061807-generic-x86_64-with-glibc2.39
Python dependencies:
sklearn: 1.10.dev0
pip: 26.1
setuptools: 82.0.1
numpy: 2.4.5
scipy: 1.17.1
Cython: 3.2.4
pandas: 3.0.3
matplotlib: 3.10.9
joblib: 1.5.3
threadpoolctl: 3.6.0
narwhals: 2.21.2
Built with OpenMP: True
threadpoolctl info:
user_api: blas
internal_api: openblas
num_threads: 12
prefix: libscipy_openblas
filepath: /home/itamarst/devel/scikit-learn/venv314t/lib/python3.14t/site-packages/numpy.libs/libscipy_openblas64_-32a4b2a6.so
version: 0.3.31.188.0
threading_layer: pthreads
architecture: Haswell
user_api: blas
internal_api: openblas
num_threads: 12
prefix: libscipy_openblas
filepath: /home/itamarst/devel/scikit-learn/venv314t/lib/python3.14t/site-packages/scipy.libs/libscipy_openblas-6cdc3b4a.so
version: 0.3.30
threading_layer: pthreads
architecture: Haswell
user_api: openmp
internal_api: openmp
num_threads: 12
prefix: libgomp
filepath: /usr/lib/x86_64-linux-gnu/libgomp.so.1.0.0
version: NoneInterest in fixing the bug
I might fix this, depending. The lack of thread safety isn't a significant correctness issue; might be a performance issue though.
#19884 was a previous attempt to remove these, stalled because it was unclear if performance was an issue.
My plan:
- Try to determine if this is a performance bottleneck.
- If it is a bottleneck, try switching to thread-locals to calculate this, and then stats would be correct. This will require a small API change: stats will not reset to zero at the start of
query(), but rather get incremented to existing stats. - If it's not a bottleneck, or the thread-local approach proves non-viable, or the small API change is unacceptable: deprecate the API, document that its results are garbage, and then in the future this can eventually be removed.
Activity
itamarst commentedon Jun 2, 2026
Initial experiment suggests that running
KDTree.query()on the same instance across multiple threads is indeed a performance bottleneck, and that switching to thread locals does indeed speed it up.Next I will see if this is visible in real benchmarks.
itamarst commentedon Jun 2, 2026
I ran the asv benchmark for
neighbors.KNeighborsClassifierBenchmark.time_predict, using 11 cores.With thread-local stats speed was significantly improved: run time dropped by ~6% for high dimension ball tree, 13% for high dimension kd tree, 57% for low dimension ball tree, 49% for low dimension kd tree. The former two may be noise; the latter seems like real improvement.
This is sufficiently compelling that I think this should be turned into a real PR.
itamarst commentedon Jun 2, 2026
Here's the approach I am suggesting: 83ea86b