Skip to content

Proof of concept: Thread oversaturation mitigation - #34171

Closed
itamarst wants to merge 9 commits into
scikit-learn:mainfrom
itamarst:thread-oversaturation-experiments
Closed

itamarst wants to merge 9 commits into
scikit-learn:mainfrom
itamarst:thread-oversaturation-experiments

Conversation

@itamarst

@itamarst itamarst commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

This is a sketch of what a fix for #34070 might look like.

You can enable thread pools globally by setting an environment variable SKLEARN_THREADING=1 (this was added just for experimentation purposes, it's not intended to be merged.)

The changes in parallel.py then prevent oversaturation (tested with OpenBLAS pthreads and OpenBLAS OpenMP variants). Plausibly these changes should be done upstream in joblib, rather than here.

@ogrisel

ogrisel commented Jun 3, 2026

Copy link
Copy Markdown
Member

Any idea if the failures for the debian build are deterministic and related to this PR? Can you try to push an empty commit to trigger a new CI run?

@ogrisel

ogrisel commented Jun 3, 2026

Copy link
Copy Markdown
Member

Plausibly these changes should be done upstream in joblib, rather than here.

I agree, but it's good to draft this here to test that this is does not cause regressions when running the full scikit-learn test suite.

You can also push an empty commit with the "[free-threaded]" marker somewhere in the commit message to also run the CI workflow with the free-threading CPython on this PR.

@ogrisel ogrisel 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.

Thanks for the PR. I think we should consolidate some experimental results with various runtimes (different blas and openmp implementations and configuration on different platforms and distribution channels) either here or in a gist/side repo to assess the robustness of this proof of concept.

I will push a few scripts with high level use cases in a gist.

Comment thread sklearn/utils/parallel.py
# pools, or choosing a better BLAS library.
with _get_threadpool_controller().limit(
limits=max(joblib.cpu_count() // self.n_jobs, 1)
):

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.

In the final version would rather like to find a way to avoid calling this context manager if the backend is not a threading backend.

@itamarst

itamarst commented Jun 3, 2026

Copy link
Copy Markdown
Contributor Author

Any idea if the failures for the debian build are deterministic and related to this PR? Can you try to push an empty commit to trigger a new CI run?

Done, we'll see how it goes. But also... does anyone actually do 32-bit these days?

@itamarst

itamarst commented Jun 3, 2026

Copy link
Copy Markdown
Contributor Author

I guess it's plausible that I broke Debian. This is gonna be fun debugging, I can already tell 😁

@ogrisel

ogrisel commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

Done, we'll see how it goes. But also... does anyone actually do 32-bit these days?

It's a useful proxy to catch some pyodide problems :)

Comment thread sklearn/utils/parallel.py
# Given this limitation, algorithms that cannot saturate all cores
# should having documentation suggesting either sticking to process
# pools, or choosing a better BLAS library.
# TODO don't do this on process pools:

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.

You can use git commit --allow-empty -m "Trigger [free-threaded] CI" if you don't want to change a file.

@itamarst

itamarst commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

Some progress on the 32-bit Debian failures: they only happen when tests are run with pytest-xdist with more than one worker, e.g. this fails much like CI:

pytest -n2 sklearn/ensemble/tests/test_bagging.py::test_estimators_samples_deterministic

but these succeed:

pytest sklearn/ensemble/tests/test_bagging.py::test_estimators_samples_deterministic
pytest -n1 sklearn/ensemble/tests/test_bagging.py::test_estimators_samples_deterministic

@itamarst

Copy link
Copy Markdown
Contributor Author

Digging a bit deeper, it's not so much pytest-xdist as, I believe, that as a result of constraining workers these tests calculate a result two ways: with multiple OpenBLAS threads, and a single OpenBLAS thread.

Fundamentally, many operations cannot be guaranteed to give the same answer, given floating point isn't commutative. So for example the @ operator will give different results on 64-bit too if you use a differing number of threads, because that changes the order of operations.

There is question is why 32-bit is causing this to be so much more different. And I think it's worth filing a bug fore.

However: this is a pre-existing problem. As far as I can tell, if you run code under 32-bit you will get somewhat different results depending on the number of OpenBLAS threads. So a hypothetical user on a 4-core 32-bit machine will get different results than a user on a 1-core 32-bit machine. All this branch does is expose that to a test, it's not creating a new problem.

Also it's not clear to me if this is even relevant to WASM (does NumPy use OpenBLAS there, and does OpenBLAS use web workers?).

I have also spent quite a lot of time digging into this, and I don't want to spend more, since the payoff is pretty low (it's a preexisting problem for the least-popular target platform).

So I suggest:

  1. File a bug. Quite possibly underlying issue is scipy, or OpenBLAS.
  2. When this mechanism gets merged (joblib, or maybe here), make the tests use consistent number of OpenBLAS threads in these 4 tests on 32-bit computers.

@ogrisel had a chance to come up with some relevant high-level benchmarks?

@itamarst

Copy link
Copy Markdown
Contributor Author

Oh and looks like pyodide has no threads so inconsistent behavior is not really relevant there for now.

Comment thread sklearn/utils/parallel.py
with _get_threadpool_controller().limit(
limits=max(joblib.cpu_count() // self.n_jobs, 1)
):
return super().__call__(iterable_with_config_and_warning_filters)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This needs to handle the case where the result is lazy (an iterable) rather than synchronous (all results immediately available as a list).

@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Jun 15, 2026
@github-actions

Copy link
Copy Markdown

❌ Linting issues

This PR is introducing linting issues. Here's a summary of the issues. Note that you can avoid having linting issues by enabling pre-commit hooks. Instructions to enable them can be found here.

You can see the details of the linting issues under the lint job here


mypy

mypy detected issues. Please fix them locally and push the changes. Here you can see the detected issues. Note that the installed mypy version is mypy=1.15.0.

Details

sklearn/neighbors/tests/test_graph.py:84: error: List item 0 has incompatible type "type[KNeighborsTransformer]"; expected "type[NeighborsBase]"  [list-item]
sklearn/svm/tests/test_svm.py:631: error: List item 1 has incompatible type "tuple[type[NuSVC], str]"; expected "tuple[type[BaseSVC], str]"  [list-item]
sklearn/svm/tests/test_svm.py:650: error: List item 1 has incompatible type "tuple[type[NuSVC], dict[str, list[float]]]"; expected "tuple[type[BaseSVC], dict[str, list[float]]]"  [list-item]
sklearn/svm/tests/test_svm.py:1252: error: List item 0 has incompatible type "type[SVC]"; expected "type[BaseSVC]"  [list-item]
sklearn/svm/tests/test_svm.py:1267: error: List item 0 has incompatible type "type[SVC]"; expected "type[BaseSVC]"  [list-item]
sklearn/svm/tests/test_svm.py:1520: error: List item 1 has incompatible type "tuple[type[NuSVC], str]"; expected "tuple[type[BaseSVC], str]"  [list-item]
sklearn/svm/tests/test_svm.py:1529: error: List item 0 has incompatible type "type[SVC]"; expected "type[BaseSVC]"  [list-item]
sklearn/neighbors/tests/test_neighbors.py:335: error: List item 0 has incompatible type "type[KNeighborsClassifier]"; expected "type[NeighborsBase]"  [list-item]
sklearn/neighbors/tests/test_neighbors.py:336: error: List item 1 has incompatible type "type[KNeighborsRegressor]"; expected "type[NeighborsBase]"  [list-item]
sklearn/linear_model/tests/test_least_angle.py:209: error: List item 0 has incompatible type "type[Lars]"; expected "type[Lars]"  [list-item]
sklearn/linear_model/tests/test_least_angle.py:209: error: List item 1 has incompatible type "type[LarsCV]"; expected "type[Lars]"  [list-item]
sklearn/ensemble/tests/test_stacking.py:566: error: List item 1 has incompatible type "tuple[type[StackingRegressor], type[DummyRegressor], str, LinearRegression, Any, Any]"; expected "tuple[ABCMeta, type[BaseEstimator], str, BaseEstimator, Any, Any]"  [list-item]
sklearn/ensemble/tests/test_gradient_boosting.py:1352: error: List item 2 has incompatible type "tuple[type[GradientBoostingRegressor], Any, type[DummyRegressor]]"; expected "tuple[ABCMeta, Any, type[BaseEstimator]]"  [list-item]
sklearn/ensemble/_hist_gradient_boosting/tests/test_warm_start.py:32: error: List item 1 has incompatible type "tuple[type[HistGradientBoostingRegressor], Any, Any]"; expected "tuple[type[BaseHistGradientBoosting], Any, Any]"  [list-item]
sklearn/ensemble/_hist_gradient_boosting/tests/test_warm_start.py:54: error: List item 1 has incompatible type "tuple[type[HistGradientBoostingRegressor], Any, Any]"; expected "tuple[type[BaseHistGradientBoosting], Any, Any]"  [list-item]
sklearn/ensemble/_hist_gradient_boosting/tests/test_warm_start.py:80: error: List item 1 has incompatible type "tuple[type[HistGradientBoostingRegressor], Any, Any]"; expected "tuple[type[BaseHistGradientBoosting], Any, Any]"  [list-item]
sklearn/ensemble/_hist_gradient_boosting/tests/test_warm_start.py:108: error: List item 1 has incompatible type "tuple[type[HistGradientBoostingRegressor], Any, Any]"; expected "tuple[type[BaseHistGradientBoosting], Any, Any]"  [list-item]
sklearn/ensemble/_hist_gradient_boosting/tests/test_warm_start.py:137: error: List item 1 has incompatible type "tuple[type[HistGradientBoostingRegressor], Any, Any]"; expected "tuple[type[BaseHistGradientBoosting], Any, Any]"  [list-item]
sklearn/ensemble/_hist_gradient_boosting/tests/test_warm_start.py:157: error: List item 1 has incompatible type "tuple[type[HistGradientBoostingRegressor], Any, Any]"; expected "tuple[type[BaseHistGradientBoosting], Any, Any]"  [list-item]
sklearn/ensemble/_hist_gradient_boosting/tests/test_warm_start.py:183: error: List item 1 has incompatible type "tuple[type[HistGradientBoostingRegressor], Any, Any]"; expected "tuple[type[BaseHistGradientBoosting], Any, Any]"  [list-item]
sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py:66: error: List item 1 has incompatible type "tuple[type[HistGradientBoostingRegressor], Any, Any]"; expected "tuple[type[BaseHistGradientBoosting], Any, Any]"  [list-item]
sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py:953: error: List item 1 has incompatible type "tuple[type[HistGradientBoostingRegressor], HalfSquaredError, Any, Any]"; expected "tuple[type[BaseHistGradientBoosting], BaseLoss, Any, Any]"  [list-item]
sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py:970: error: List item 1 has incompatible type "tuple[type[HistGradientBoostingRegressor], Any, Any]"; expected "tuple[type[BaseHistGradientBoosting], Any, Any]"  [list-item]
sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py:1461: error: List item 1 has incompatible type "tuple[type[HistGradientBoostingRegressor], Any]"; expected "tuple[type[BaseHistGradientBoosting], Any]"  [list-item]
sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py:1554: error: List item 0 has incompatible type "type[HistGradientBoostingClassifier]"; expected "type[BaseHistGradientBoosting]"  [list-item]
sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py:1609: error: List item 0 has incompatible type "type[HistGradientBoostingClassifier]"; expected "type[BaseHistGradientBoosting]"  [list-item]
sklearn/model_selection/tests/test_split.py:430: error: List item 0 has incompatible type "type[StratifiedKFold]"; expected "type[_BaseKFold]"  [list-item]
sklearn/model_selection/tests/test_split.py:457: error: List item 0 has incompatible type "type[StratifiedKFold]"; expected "type[_BaseKFold]"  [list-item]
sklearn/model_selection/tests/test_split.py:499: error: List item 0 has incompatible type "type[StratifiedKFold]"; expected "type[_BaseKFold]"  [list-item]
sklearn/model_selection/tests/test_split.py:542: error: List item 0 has incompatible type "type[KFold]"; expected "type[_BaseKFold]"  [list-item]
sklearn/model_selection/tests/test_split.py:542: error: List item 1 has incompatible type "type[StratifiedKFold]"; expected "type[_BaseKFold]"  [list-item]
sklearn/model_selection/tests/test_split.py:1660: error: List item 0 has incompatible type "type[GroupKFold]"; expected "type[_BaseKFold]"  [list-item]
Found 32 errors in 9 files (checked 596 source files)

Generated for commit: b15f27d. Link to the linter CI: here

@itamarst

Copy link
Copy Markdown
Contributor Author

Running with the given benchmark in the gist, with:

  • taskset -c 0-7 so it's only 8 cores.
  • Only looking at 8 job run.

Then:

  • loky backend has essentially no involuntary context switches (~5K).
  • threading backend has 384K involuntary context switches.

This suggests there's still some oversaturation happening somewhere, that this branch isn't catching...

@itamarst

Copy link
Copy Markdown
Contributor Author

I think what's happening is nested Parallel, so in this case thread pools starting (overly large) thread pools in their worker threads.

Solving this probably requires switching joblib.parallel_config to use a thread local config, or better yet contextvars for the context copying, instead of a module-level global. Then thread pools can scope within their threads usage of serialized execution (or thread pool of size that fits number of cores, similar to OpenMP/OpenBLAS settings).

This probably means this prototype needs to be implemented in a branch in joblib, and then installed as package update, rather than being tested via a branch in scikit-learn.

@itamarst itamarst closed this Aug 10, 2026
@itamarst

Copy link
Copy Markdown
Contributor Author

Work has moved to joblib.

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

Labels

CI:Linter failure The linter CI is failing on this PR module:utils

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants