Skip to content

CI Investigate free-threaded tests slowness ~ 60 minutes rather than 10-15 minutes for other Linux builds #35101

Open

Description

@lesteve

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.

Look at a few logs and it consistently takes ~60 minutes which is quite slow. Part of the slowness is because we use pytest-run-parallel to stress-test free-threaded but still ...

From build log, see slowed tests below. The partial dependence taking each 2 minutes would be a start.

126.23s call     inspection/tests/test_partial_dependence.py::test_partial_dependence_non_null_weight_idx[1-estimator2]
125.97s call     inspection/tests/test_partial_dependence.py::test_partial_dependence_non_null_weight_idx[-1-estimator2]
125.65s call     inspection/tests/test_partial_dependence.py::test_partial_dependence_non_null_weight_idx[0-estimator2]
20.70s call     preprocessing/tests/test_target_encoder.py::test_fit_transform_not_associated_with_y_if_ordinal_categorical_is_not[42]
16.11s call     feature_selection/tests/test_rfe.py::test_rfe_cv_groups
15.51s call     cluster/tests/test_mean_shift.py::test_mean_shift[float64-1.2-False-4--1]
15.47s call     cluster/tests/test_mean_shift.py::test_max_iter[100]
15.40s call     cluster/tests/test_mean_shift.py::test_mean_shift[float64-1.2-True-3-0]
13.67s call     ensemble/_hist_gradient_boosting/tests/test_binning.py::test_subsampled_weighted_vs_repeated_equivalence[5-0]
13.21s call     ensemble/_hist_gradient_boosting/tests/test_binning.py::test_subsampled_weighted_vs_repeated_equivalence[3-1]
12.89s call     ensemble/_hist_gradient_boosting/tests/test_binning.py::test_subsampled_weighted_vs_repeated_equivalence[5-42]
12.89s call     ensemble/_hist_gradient_boosting/tests/test_binning.py::test_subsampled_weighted_vs_repeated_equivalence[3-0]
12.76s call     ensemble/_hist_gradient_boosting/tests/test_binning.py::test_subsampled_weighted_vs_repeated_equivalence[3-42]
12.75s call     ensemble/tests/test_forest.py::test_memory_layout[float32-ExtraTreesRegressor]
12.74s call     ensemble/_hist_gradient_boosting/tests/test_binning.py::test_subsampled_weighted_vs_repeated_equivalence[5-1]
12.60s call     ensemble/tests/test_forest.py::test_memory_layout[float32-RandomForestRegressor]
12.12s call     ensemble/tests/test_forest.py::test_memory_layout[float64-ExtraTreesRegressor]
11.86s call     ensemble/tests/test_forest.py::test_memory_layout[float64-RandomForestRegressor]
11.22s call     ensemble/tests/test_forest.py::test_memory_layout[float32-ExtraTreesClassifier]
10.75s call     ensemble/tests/test_forest.py::test_memory_layout[float64-ExtraTreesClassifier]

Activity

  1. added
    Needs Triage
    on Oct 8, 2026
  2. added
    Needs Investigation
    and removed
    Needs Triage
    on Oct 8, 2026
  3. lesteve commented on Oct 8, 2026

    @lesteve
    MemberAuthor

    Initial investigation with codex:

    There is a slowdown, but the big jump is August 25 → 26, 2026. These are whole-job durations, including setup and compilation:

    Scheduled run Commit Free-threaded job Change
    August 24 be5a8a8 28m 18s —
    August 25 53302ff 31m 50s +12.5%
    August 26 a456b32 52m 25s +64.7%

    The regular pylatest_pip_scipy_dev job stayed essentially unchanged: 10m 58s, 10m 57s, and 10m 53s in those runs.

    I followed the commit history between the runs:

    • August 24 → 25: seven commits, covering contingency_matrix Array API support, GitHub authentication scripts, other environments’ lock files, documentation, and a progress-bar fix. The free-threaded lock file did not change. The main computational change was #34785, which changed contingency_matrix and added tests. That is a possible lead, but insufficient evidence to explain the extra 3m 32s.
    • August 25 → 26: the free-threaded lock update, #34804, upgraded Python 3.14.6 → 3.14.7, Cython 3.2.5 → 3.3.0, and GCC runtime packages. NumPy, SciPy, OpenBLAS, pytest, and joblib stayed unchanged. This is a strong candidate for the larger jump. The same interval also included ExtraTree categorical hash splitting, #33972, changing tree internals and tests.

    I could not inspect the requested --durations output. The browser exposes summaries but requires sign-in for logs, and the authenticated CLI fails because this environment cannot resolve api.github.com. Consequently, I can confirm the job slowdown and identify relevant changes, but cannot yet identify the slowest tests or establish a cause.

    Please attach the downloaded free-threaded logs for these three runs; their duration tables and setup/build timings will let me distinguish a test regression from compilation or environment overhead.

  4. lesteve commented on Oct 8, 2026

    @lesteve
    MemberAuthor

    I can reproduce locally a similar behaviour, running a single test with --parallel-threads 4 take 40s, whereas it takes 3s without --parallel-threads and 5s with --parallel-threads 2

    pytest 'sklearn/inspection/tests/test_partial_dependence.py::test_partial_dependence_non_null_weight_idx[1-estimator2]'\
         --parallel-threads 4 --durations=10
  5. lesteve commented on Oct 8, 2026

    @lesteve
    MemberAuthor

    The slowdown is much smaller with Python 3.14.6

    Setting Python 3.14.6 Earlier Python 3.14.7
    No parallel option 2.09s 2.84s
    --parallel-threads 2 2.59s 4.30s
    --parallel-threads 4 4.80s 40.55s
  6. lesteve commented on Oct 8, 2026

    @lesteve
    MemberAuthor

    Similar slowdown with uv so this is not specific to the conda package:

    Setting Python 3.14.7, uv (new) Python 3.14.6, conda (earlier)
    No --parallel-threads 1.00 s 2.09 s
    --parallel-threads 2 2.22 s 2.59 s
    --parallel-threads 4 43.17 s 4.80 s
  7. lesteve commented on Oct 8, 2026

    @lesteve
    MemberAuthor

    I checked that applying the diff below to scikit-learn delayed wrapper does remove the slowdown with --parallel-threads 4 from ~45s to ~2.5s:

    diff --git a/sklearn/utils/parallel.py b/sklearn/utils/parallel.py
    index 5cd75bfb0a3..9137cd91b1e 100644
    --- a/sklearn/utils/parallel.py
    +++ b/sklearn/utils/parallel.py
    @@ -118,7 +118,14 @@ def delayed(function):
             keyword arguments.
         """
     
    -    @functools.wraps(function)
    +    @functools.wraps(
    +        function,
    +        assigned=tuple(
    +            attr
    +            for attr in functools.WRAPPER_ASSIGNMENTS
    +            if attr not in {"__module__", "__name__", "__qualname__", "__doc__"}
    +        ),
    +    )
         def delayed_function(*args, **kwargs):
             return _FuncWrapper(function), args, kwargs

    Here is what codex had to say about it (lightly edited to remove minor details):

    Python 3.14.7 changes how function attributes are modified. Setting __name__, __qualname__, __module__, or __doc__ now calls _PyEval_StopTheWorld() before the update and _PyEval_StartTheWorld() afterwards. This pauses all threads executing Python, even when modifying a newly created function. These pauses are absent from the corresponding setters in 3.14.6; they appear in 3.14.7.

    That connects directly to this test:

    • Scikit-learn’s delayed() (sklearn/utils/parallel.py:121) creates a function decorated with functools.wraps.
    • wraps() copies those four attributes, triggering four global pauses.
    • Our earlier profile recorded approximately 20,500 delayed() calls per test execution: potentially about 82,000 pauses, multiplied across concurrent test executions.

    The other candidates I examined are much weaker:

    • String interning: PR #153815 changes waiting on an interpreter-wide lock. Plausible for contention, but the experiment above makes it a secondary suspect.
    • Two-object critical sections: PR #151555 avoids redundant recursive locking. It was intended to improve performance and has a weaker connection to this test.

    My leading explanation is therefore repeated global pauses caused by functools.wraps inside delayed().

  8. lesteve commented on Oct 8, 2026

    @lesteve
    MemberAuthor

    cc @cakedev0 in case you have noticed something similar in your performance investigation with free-threaded recently.

    Note that this is running on my laptop so this one is not an issue only specific to many-cores server.

  9. cakedev0 commented on Oct 8, 2026

    @cakedev0
    Member

    It's a bug on its own that was introduced between 3.14.6 and 3.14.7 (my agent agrees with yours ^^).

    The issue I reported (python/cpython#158901) seems to make it worse, but my agent tried your reproducer with a fixed CPython it built (fixed for my bug), and your bug can still be quite bad it seems. I'll post my agent detailed findings when it's fully wrapped up.

    I think you can open an issue on CPython then 😄

  10. cakedev0 commented on Oct 8, 2026

    @cakedev0
    Member

    My agent findings (I read it, it's pretty informative):

    I can reproduce on my laptop (Intel Core Ultra 5 225H, 14 cores), conda-forge free-threaded Python, same numpy/scipy/Cython in both envs, scikit-learn main (14e0bae). Whole pytest run of test_partial_dependence_non_null_weight_idx[1-estimator2]:

    --parallel-threads 3.14.6 3.14.7
    none 3.7s 3.6s
    2 4.1s 5.9s
    4 5.2s 36s
    8 11s 129s
    14 30s 453s

    Your diagnosis is right: the slowdown comes from the stop-the-world pauses that 3.14.7 added to the function attribute setters. It reproduces with the standard library only:

    import functools
    import sys
    import threading
    import time
    
    
    def f():
        """Docstring."""
    
    
    def time_per_wraps(n_threads, n_calls=5_000):
        barrier = threading.Barrier(n_threads)
        durations = []
    
        def work():
            barrier.wait()
            tic = time.perf_counter()
            for _ in range(n_calls):
                functools.wraps(f)(lambda: None)
            durations.append(time.perf_counter() - tic)
    
        threads = [threading.Thread(target=work) for _ in range(n_threads)]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        return 1e6 * sum(durations) / len(durations) / n_calls
    
    
    print(sys.version.split()[0], "| GIL enabled:", sys._is_gil_enabled())
    for n in [1, 2, 4, 8, 14]:
        print(f"{n:>2} threads: {time_per_wraps(n):8.1f} µs per wraps call")

    On the same laptop (µs per functools.wraps call):

    threads 1 2 4 8 14
    3.14.6 2.6 3.4 11 13 47
    3.14.7 2.9 365 3743 4254 5503

    So no cost with a single thread, but already ~100x slower as soon as there is a second thread.


    Where it comes from. Two use-after-free fixes for the free-threaded build, merged on main in late July and backported to 3.14:

    functools.wraps sets 4 of them (__module__, __name__, __qualname__, __doc__), so every delayed() call pauses all the other threads 4 times. I found no discussion of the performance impact on these PRs. The 3.14.8 tag and main still have the pauses.


    It gets much worse on many-core machines, because of the PyMutex fair handoff. Stop-the-world requests are serialized by a PyMutex (stw->mutex in Python/pystate.c), which has the 1 ms fair handoff I reported in python/cpython#158901. On a 2 x 86-core Xeon 6787P, with CPython built from source with --disable-gil, stock vs TIME_TO_BE_FAIR_NS raised to 100 ms (µs per functools.wraps call, same idea as the script above with a decorator function, best of 3):

    threads 1 2 4 8 14
    3.14.6 1.5 3.1 6.9 15 40
    3.14.7 1.5 35 327 5481 10144
    3.14.7, 100 ms handoff 1.4 21 110 352 808

    Raising the threshold makes no difference on 3.14.6. Same machine, your test:

    --parallel-threads 3.14.6 3.14.7 3.14.7, 100 ms handoff
    4 6.0s 25s 22s
    8 16s 229s 79s

    So the handoff turns an already slow path into a collapse past ~8 threads, but even without it, 3.14.7 is ~5x slower than 3.14.6 at 8 threads.


    What could be done.

    • On our side, your delayed() patch removes the cost, whatever CPython does. I think it's worth merging regardless.
    • On CPython's side, I think a much cheaper fix exists. main already protects the generator __name__ setter by deferring the decref of the old value (_PyObject_XSetRefDelayed, the old value is freed once all threads have passed a quiescent state). As far as I can tell, this protects borrowed references as well as a stop-the-world does, but I may be missing a case. Skipping the pause when no other thread can see the function (the functools.wraps case) would also work, but it's narrower.
  11. added
    free-threading
    on Oct 8, 2026
  12. cakedev0 commented on Oct 20, 2026

    @cakedev0
    Member

    Nice! 🎉

  13. lesteve commented on Nov 4, 2026

    @lesteve
    MemberAuthor

    The fix has been back-ported in 3.14 and 3.15 branch (see previous message for links) so the fix should make it in Python 3.14.11 and 3.15.3 expected December 1st 2026, see Python 3.14 release schedule and Python 3.15 release schedule.

    I don't think it's worth doing a temporary work-around pinning to python<=3.14.6 to avoid the performance regression since the slow free-threaded CI doesn't annoy us too much right now. If you disagree, I will happily review a PR 😉.

    While I was at it I asked an agent to find some info about the future Python 3.15 free-threaded migration on conda-forge and the tl;dr is that it hasn't started yet and there is no precise start date in mind, see agent session below (TIL about /export in my agent ...)


    User

    Can you find some public comment on GitHub indicating when the conda-forge python3.15 free-threaded will start or when numpy plans to have a conda-forge package?

    Assistant

    Yes—there is a public plan, but I couldn’t find a firm date for Python 3.15 free-threaded packages or NumPy’s 3.15t build.

    The most relevant sources are:

    • conda-forge migration PR #8891, opened August 26, 2026. @h-vetinari explicitly proposes keeping the 3.14t migration running and then “remigrate for 3.15t,” following the earlier 3.13t → 3.14t process. No start date is given.

    • conda-forge’s September 3 announcement, on GitHub states:

      That initial migration will only cover the regular (non-freethreading) builds — the 3.14t migration keeps running in the meantime, and a 3.15t migration will start at a later date…

    • A more recent PR, October 20 says “conda-forge has no 3.15t migration yet.” This is supporting evidence from a package contributor; the description labels itself AI-generated.

    For NumPy specifically, I found PR #397, “Rebuild for python 3.15”, but that concerns the regular build. I found no NumPy-specific public commitment for 3.15t availability. The conda-forge migration plan above is the clearest indication of what it is waiting for.

  14. h-vetinari commented on Nov 4, 2026

    @h-vetinari

    I think we're ready to discuss migrating 3.15t; you can open an issue in https://github.com/conda-forge/conda-forge.github.io for that

  15. lesteve commented on Nov 4, 2026

    @lesteve
    MemberAuthor

    Ooops didn't mean to ping you @h-vetinari 😅 1, thanks for your answer, I created an issue conda-forge/conda-forge.github.io#2982.

    Footnotes

    1. I blindly copied and pasted an agent conversation without thinking enough about the consequences 😱 ↩

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs Investigationfree-threading

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions