Repository navigation
Description
Describe the bug
I encountered the following bug while doing an outlier analysis on a large dataset:
To detect outliers in a dataset with known outliers, I followed these steps:
- compute the covariance for a set of preselected numerical features with either
MinCovDetorEmpiricalCovarianceand extracted the inverse matrix VI using theprecision_parameter. - I initialized the LocalOutlierFactor class with the metric
mahalanobis, passedVI, and set n_jobs to 1 - I used
fit_predict()to get the outlier predictions
Everything looked as expected.
Later on, I tried speeding up the computation by adding a few cores to n_jobs and had to realise that no outliers were detected anymore. After some debugging, I found that:
- outlier detection seems not to work when using multiple cores (all samples are marked as inliers)
- this effect seems to be tied to
mahalanobisdistance, because the bug does not appear with minkowski (p=2) distance regardless of the number of cores.
One workaround seems to be to precompute the mahalanobis distance and passing it to the LOF, but this is again using only one core for the computation and is not feasible for large datasets due to the size of the full pairwise distance matrix.
Steps/Code to Reproduce
import numpy as np
from sklearn.covariance import MinCovDet
from sklearn.neighbors import LocalOutlierFactor
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt
RNG = np.random.RandomState(42)
def make_data(n_inliers=200, n_outliers=10, n_features=10):
# Inliers: standard normal in 10D
X_in = RNG.normal(loc=0.0, scale=1.0, size=(n_inliers, n_features))
# Outliers: shifted by +8 in all dimensions
X_out = RNG.normal(loc=8.0, scale=1.0, size=(n_outliers, n_features))
X = np.vstack([X_in, X_out])
y_true = np.hstack([np.ones(n_inliers, dtype=int), -np.ones(n_outliers, dtype=int)])
return X, y_true
def robust_inverse_covariance(X, random_state=0):
# Fit robust covariance estimator
mcd = MinCovDet(random_state=random_state).fit(X)
cov = mcd.covariance_ # shape (n_features, n_features)
# Compute inverse covariance (VI) expected by 'mahalanobis' metric
VI = mcd.precision_
# ensure dtype=float64 and C-contiguous so it serializes safely across processes
VI = np.ascontiguousarray(VI, dtype=np.float64)
return VI, cov
def run_lof(X, VI, n_neighbors=20, n_jobs=1):
lof = LocalOutlierFactor(
n_neighbors=n_neighbors,
metric='mahalanobis',
metric_params={'VI': VI},
n_jobs=n_jobs
)
# fit_predict returns -1 for outliers and 1 for inliers
labels = lof.fit_predict(X)
return labels
def run_lof_precomputed(X, VI, n_neighbors=20, n_jobs=1):
# compute full pairwise Mahalanobis distance matrix in the main process
D = cdist(X, X, metric='mahalanobis', VI=VI)
lof = LocalOutlierFactor(
n_neighbors=n_neighbors,
metric='precomputed',
n_jobs=n_jobs
)
labels = lof.fit_predict(D)
return labels
def stats(labels):
unique, counts = np.unique(labels, return_counts=True)
return dict(zip(unique.tolist(), counts.tolist()))
# Executing example
## make data
X, y_true = make_data(n_inliers=200, n_outliers=10, n_features=10)
## plot data
plt.figure(figsize=(8, 6))
plt.scatter(X[:, 0], X[:, 1], c=y_true, cmap='coolwarm', edgecolor='k')
plt.title("Toy dataset with inliers (blue) and outliers (red)")
plt.xlabel("Feature 0")
plt.ylabel("Feature 1")
plt.show()
## Fit MinCovDet on the whole dataset
VI, cov = robust_inverse_covariance(X, random_state=42)
## Run LOF with a single core (n_jobs=1)
labels_n1 = run_lof(X, VI, n_neighbors=20, n_jobs=1)
print("n_jobs=1 unique counts:", stats(labels_n1))
## expected result: n_jobs=1 unique counts: {-1: 11, 1: 199}
## Run LOF allowing multiple cores (n_jobs=4)
labels_n4 = run_lof(X, VI, n_neighbors=20, n_jobs=4)
print("n_jobs=4 unique counts:", stats(labels_n4))
## exprected result: n_jobs=4 unique counts: {1: 210}
## fix attempt: precompute Mahalanobis with single core and LOF with multiple
labels_precomputed = run_lof_precomputed(X, VI, n_neighbors=20, n_jobs=4)
print("precomputed (n_jobs=4) unique counts:", stats(labels_precomputed))
## expected result: precomputed (n_jobs=4) unique counts: {-1: 11, 1: 199}
## Print outlier labels
pred_outliers = np.where(labels_n1 == -1)[0]
print("Indices detected as outliers by n_jobs=1", pred_outliers)
## expected output: Indices detected as outliers by n_jobs=1: [116 200 201 202 203 204 205 206 207 208 209]
y_true_outliers = np.where(y_true == -1)[0]
print("Indices of true outliers:", y_true_outliers)
## expected output: Indices of true outliers: [200 201 202 203 204 205 206 207 208 209]
Expected Results
It shouldn't matter how many cores are passed to the 'n_jobs' parameters. The results should be comparable, or at least detect some outliers.
Actual Results
Results for LOF should be comparable, but are wildly different based on changes to the 'n_jobs' parameter, with all other parameters staying the same:
Results for n_jobs=1:
n_jobs=1 unique counts: {-1: 11, 1: 199}
Results for n_jobs=4:
n_jobs=4 unique counts: {1: 210}
Versions
Python dependencies:
sklearn: 1.7.2
pip: 25.2
setuptools: 80.9.0
numpy: 2.3.4
scipy: 1.15.2
Cython: None
pandas: 2.2.3
matplotlib: 3.10.6
joblib: 1.5.2
threadpoolctl: 3.6.0
Built with OpenMP: True
threadpoolctl info:
user_api: blas
internal_api: openblas
num_threads: 5
prefix: libscipy_openblas
filepath: /home/USER/environments/conda_environments/MY_ENV/lib/python3.11/site-packages/numpy.libs/libscipy_openblas64_-8fb3d286.so
version: 0.3.30
threading_layer: pthreads
architecture: Haswell
user_api: blas
internal_api: openblas
num_threads: 5
prefix: libopenblas
filepath: /home/USER/environments/conda_environments/MY_ENV/lib/libopenblasp-r0.3.30.so
version: 0.3.30
threading_layer: pthreads
architecture: Zen
user_api: openmp
internal_api: openmp
num_threads: 5
prefix: libgomp
filepath: /home/USER/environments/conda_environments/MY_ENV/lib/libgomp.so.1.0.0
version: None
Activity
Aaraviitkgp commentedon Nov 21, 2025
@sroener I think the issue occurs when n_jobs>1 it requires parallel processing, joblib tries to pickle metric_params and the array gets pickled in non standard format, then when it gets unpickled it is incorrect or incomplete. In case of n_jobs=1 no parallel processing happens so different results are produced.
Aaraviitkgp commentedon Nov 21, 2025
@adrinjalali @lesteve can I raise a pr on this issue?
sroener commentedon Nov 21, 2025
@Aaraviitkgp I think you are right. I found a workaround apart from precomputing. Changing the joblib backend from "loky" to "multiprocessing" also fixed the issue.
Is there a way to make the serialization of the parameters more robust? I tried to minimize errors by using
np.ascontiguousarray(VI, dtype=np.float64), but it didn't help.Aaraviitkgp commentedon Nov 21, 2025
@sroener I think a change has to be made in the _lof.py file for more robust solution, I have looked into it and I think by the LOF pickles metric_params internally the VI array might have already been corrupted. I think that's why np.ascontiguousarray(VI, dtype=np.float64) does not work.
adrinjalali commentedon Nov 21, 2025
I'd be very surprised if
pickleis the issue. This requires investigation to figure out where exactly the difference comes from. Feel free to investigate @Aaraviitkgp , we'd appreciate that.Aaraviitkgp commentedon Nov 21, 2025
@adrinjalali you were right pickle is not the issue, I've traced the bug and found that LOF calls kneighbors multiple times on the same fitted NearestNeighbors instance, and these repeated calls with n_jobs > 1 cause the VI matrix in metric_params to become corrupted through concurrent access, resulting in NaN values in the distance calculations.
Aaraviitkgp commentedon Nov 21, 2025
import numpy as np
from sklearn.neighbors import LocalOutlierFactor
from sklearn.covariance import EmpiricalCovariance
rng = np.random.RandomState(42)
X = np.vstack([rng.randn(100, 5), rng.randn(10, 5) + 5])
cov = EmpiricalCovariance().fit(X)
VI = cov.precision_
print("Running LOF 10 times with n_jobs=4:")
for i in range(10):
lof = LocalOutlierFactor(n_neighbors=20, metric='mahalanobis',
metric_params={'VI': VI}, n_jobs=4)
predictions = lof.fit_predict(X)
has_nan = np.isnan(lof.negative_outlier_factor_).any()
print(f" Run {i+1}: NaN = {has_nan}")
print("\nRunning LOF 10 times with n_jobs=1:")
for i in range(10):
lof = LocalOutlierFactor(n_neighbors=20, metric='mahalanobis',
metric_params={'VI': VI}, n_jobs=1)
predictions = lof.fit_predict(X)
has_nan = np.isnan(lof.negative_outlier_factor_).any()
print(f" Run {i+1}: NaN = {has_nan}")
Aaraviitkgp commentedon Nov 25, 2025
@adrinjalali any update on this issue.
sroener commentedon Nov 25, 2025
@Aaraviitkgp Interesting, but why does changing the
parallel_backendto "multiprocessing" solve the issue? This sounds more to a backend problem in joblibs standard backend "loky". May have something to do with serialization of nested data structures like VI (an numpy array) in a dictionary. This would also explain why minkowski distance works without an error, havin only one parameter passed, which is an integer.Aaraviitkgp commentedon Nov 25, 2025
@sroener in parallel_backend threads share same memory space which means all threads access the same VI which in return causes the error whereas in multi_processing, all threads have different memory space so it does not cause the error. I think as loky default prefer the first way which is why in locky it causes error. but I can be wrong .
sroener commentedon Nov 26, 2025
I just tested different joblib backends/configurations in the following combinations using the
with joblib.parallel_backend()context manager:backends: ["loky", "multiprocessing", "threading", "sequential"]
The error occurs only with the backend set to threading, or when no backend context manager is used. This would add some evidence to the error being caused by multithreading. An interesting observation was that with multiprocessing, the results were always the same. With multithreading, the results sometimes varied.
adrinjalali commentedon Dec 15, 2025
Having a minimal reproducer where only relevant parts and maybe only some basic code with joblib parallelisation is included, should be a good next step for this issue to move forward. Thanks for the investigation so far.
Aaraviitkgp commentedon Dec 16, 2025
Aaraviitkgp commentedon Dec 16, 2025
simple code for bug reproduction
lesteve commentedon Dec 16, 2025
@Aaraviitkgp readability counts, a lot! Can you please edit your snippet and add triple back-quotes aka fenced code blocks to format error messages code snippets. Bonus points if you use syntax highlighting with
pyfor python snippets andpytbfor tracebacks.Aaraviitkgp commentedon Dec 16, 2025
I have edited it please check if any other issue.
adrinjalali commentedon Dec 16, 2025
Please share the output of the script when you post it.
This is the output now:
that indicates there are some numerical issues which might cause the disparity. We need an example where things run correctly.
Aaraviitkgp commentedon Dec 21, 2025
Aaraviitkgp commentedon Dec 21, 2025
this is output :
Detected outliers (n_jobs=1): [116 200 201 202 203 204 205 206 207 208 209]
True outliers: [200 201 202 203 204 205 206 207 208 209]
BillyLjm commentedon Dec 22, 2025
The non-thread-safe object seems to be the
self.bufferfor the Mahalanobis Distance implementation insklearn/metrics/_dist_metrics.pyx.tpexcerpted below.I imagine the class would have to be rewritten without that array and with multithreading in mind?
Shu6136713 commentedon Jan 21, 2026
If it's okey, we'd like to work on it to resolve this issue.
Shu6136713 commentedon Feb 2, 2026
@adrinjalali , @ogrisel
We thought of a number of approaches to the solution.
Solution 1 - Naive:
Do not use a shared buffer at all.
Advantage - solves the problem, disadvantage - exponential memory allocations.
Solution 2 - Medium:
Pass a flag to init of Mahalanobis, which will tell whether to use a shared buffer.
The flag will be True if and only if n_jobs == 1 (or None).
Advantage - when n_jobs = 1 there will be optimal performance, disadvantage - when n_jobs >1 there will be exponential as above.
Solution 3 - Advanced:
Allocate a buffer to each thread. Keep a map of buffers according to the current thread ID- using tss.
What do you think?
lesteve commentedon Aug 7, 2026
Here is a reproducer, this is due to our implementation of Mahalanobis distance with
self.bufferbeing shared of as mentioned by someone else.For potential contributors, more than a PR attempt, a reproducer like this is something super useful 1. This allow to have a better understanding of the problem and make sure there is a real problem:
I have opened a draft PR fixing the issue: #34671.
Footnotes
compared to the original reproducer (thanks @sroener for providing a reproducer in the first place 🙏) it is a bit simpler (only use BallTree and no joblib which shows that joblib is not to blame here) ↩