You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
BUG: Linear algebra heavy calculations experience sudden slowdown after the size of 100 #29884
Python: 3.11
OS: Ubuntu 22.04
NumPy: 2.0.0+ (this problem seems to go away for v1.X)
Runtime Environment:
No response
Context for the issue:
Are there any thresholdings to switch which implementations to use in some operations?
Tbh, the sudden slowdown appears very strange to me without such a manual algorithm switch.
In Numpy there is no internal algorithm switching - only datatype switching.
My environment: Numpy 2.3.3, python 3.11
Quick debug tips:
Try checking resource usage and system time to identify the slowdown reason
Tip: Vectorize (or convert data into numpy arrays) to reduce internal conversions.
Okay so, I have checked the definitions of optimize and suggest_float functions, suggest_float doesn't use numpy internally - never imported. The optimize function however does use numpy twice and i verified their definitions.
At study.py line 1099: is_repeated = ( np.isnan(float(param_value)) or np.isclose(float(param_value), float(existing_param), atol=0.0) if isinstance(param_value, Real) else param_value == existing_param )
The above snippet (part of _should_skip_enqueue function) helps in identifying if same trial parameters were encountered previously and to skip the trial.
This part is called in every trial and hence should not slow down after 100th iteration. It either always slows down the code or never will.
At study.py line 829:
`
if not isinstance(params, dict):
raise TypeError("params must be a dictionary.")
if skip_if_exists and self._should_skip_enqueue(params):
_logger.info(f"Trial with params {params} already exists. Skipping enqueue.")
return
self.add_trial(
create_trial(
state=TrialState.WAITING,
system_attrs={"fixed_params": params},
user_attrs=user_attrs,
)
)
`
Coming to the numpy part,
isnan function is implemented in C.
The isclose function was implemented in python and if we check it, there is no sudden algorithm changes for large data, there is however some data modifications.
Data Conversions noticed:
Scalar types, i.e., int, float, complex remains the same
Non-scalar types (lists, tuples etc) are converted into numpy arrays
integers are promoted to float
The result of this functions is just evaluation of this formula: absolute(a - b) <= (atol + rtol * absolute(b))
Although NumPy v2.X speeds up the whole pipeline, it does slows down after 100 Trials while NumPy 1.26 does not.
This looks very odd to me.
SciPy and Optuna are the only dependencies that require NumPy.
As an Optuna developer, I am pretty sure we are not switching any algorithms based on NumPy version, neither SciPy does.
The problem is from n_startup_trials in optuna for GP sampler.
The algorithm does change in optuna after startup trials are completed.
During startup trials, the algorithm simply returns an empty dict
References: sampler.py at line 210 under sample_relative function under GPSampler class. if len(trials) < self._n_startup_trials: return {}
Alright, so after running the code snippet provided, I did notice there was a difference but for me it was after 10 trials which seemed even weird. The result is as follows:
So, I looked into the code of GP Sampler class and found this: self._n_startup_trials = n_startup_trials under init at line 85:
This variable is used to early return the sampler functions (mentioned at the end of this comment.)
Its defaulted to 10 for me and that's why I noticed difference in speed after 10 trials. Maybe its 100 for you.
To validate this, I did multiple benchmarks by modifying the startup trials count. Here's the results:
Version 1.26.4:
---
Version 2.3.3:
And results after comparing between versions:
Cause: Sample relative function
At line 199 of sampler.py in optuna module, we see the following code:
@nabenabe0928 there is unlikely anything to do with NumPy. What is plausible though is that we (or the linear algebra toolkit) sped something up a lot and that transformed it from being CPU bound to being memory bound.
I.e. it seems there is some logic retaining all old samples and "doing things" with it. That data is retained and you just see things slow down like crazy.
Cache sizes/CPU speed, etc. would then determine where you see the transition between the two. Also on the old NumPy version you do see a slowdown after all, it is just a lot smoother.
Also everyone else who doesn't see one, would see one at 1000 trials.
Anyway, I'll close this, it seems exceedingly unlikely to have anything to do with NumPy (if it did, I think it would have to be a memory leak).
As a general rule, you might want to ru a profiler to see where the time even is spend, that would probably have clarified this from the start.
Plus, doing that might point to some obvious change in optuna to avoid/improve the slow-down.
I found one of the issues. (the other issue probably relates to PyTorch.)
But it seems the slowdown happens only stochastically.
I see the slowdown around 20% of the time when using numpy>=2.0.0 and n >= 100.
But no slowdown happens when I use numpy<2.0.0 or n < 100.
My environment is:
Ubuntu 22.04
Python 3.12
Important
My colleagues, who use a MacBook, do not get this issue, so it is very likely to relate to Linux, as mentioned previously.
Since I fixed the random seed in the benchmarking code, each run should ideally be executed roughly in the same amount of time.
I did not open any browser and did not run any other programs in the meantime to ensure a fair comparison.
Okay, there really is some absurd time difference this time. I'll try looking into numpy's C internals (will take a good time cause this will be my first ever lookup). I'm not sure if I can help, but I'll try.
Here's my code:
from argparse import ArgumentParser
import time
import numpy as np
parser = ArgumentParser()
parser.add_argument("--n", type=int, required=True)
args = parser.parse_args()
rng = np.random.RandomState(0)
l = []
N = args.n
for __ in range(10):
runtime = 0.0
A = rng.normal(size=(N, N))
X = A @ A.T
for _ in range(100):
start = time.time()
np.linalg.inv(X)
runtime += time.time() - start
l.append(runtime)
with open(f"records_m_{N}_{np.__version__}.txt", "a") as out:
out.write("[")
out.write(",".join(str(x) for x in l))
out.write("]")
out.write("\n")
print(f"{np.__version__=}: {np.mean(l):.3e}[s]")
I looped multiple times to take the average. Result:
Thanks for the NumPy-only reproducer. Tweaking it to use 10 iterations and use threadpoolctl to limit the number of threads used by OpenBLAS shows the problem on a 24-core Ryzen machine. Everything is fine until OpenBLAS decides to use all the cores of the machine. But then the worker threads step all over eachother, causing a 200x slowdown (in the last 5 lines). This is with np.show_runtime() of
and OpenBLAS config of OpenBLAS 0.3.30 USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=64
Maybe we should compile OpenBLAS with a shim to only use 0.9 * ncores when ncores>20.
script to test using threads for OpenBLAS
import time
import numpy as np
import threadpoolctl
rng = np.random.RandomState()
def gettimes(N):
ret = []
for __ in range(10):
runtime = 0.0
A = rng.normal(size=(N, N))
X = A @ A.T
for _ in range(10):
start = time.time()
np.linalg.inv(X)
runtime += time.time() - start
ret.append(runtime)
return ret
for limits in [10, 20, 22, 24]:
print(f"Using {limits} threads")
with threadpoolctl.threadpool_limits(limits=limits, user_api='blas'):
results = {}
for n in range(95, 105):
times = gettimes(n)
results[n] = (np.mean(times), np.std(times))
print(f" NxN matmult, N={n:3d}: mean:{results[n][0]:.3f}secs std:{results[n][1]:.5f}secs")
I commented on OpenMathLib/OpenBLAS#5469. BTW, the test as written X = A @ A.T uses the OpenBLAS syrk routines. Doing X = A @ A hits the gemm routines, and sees the same slowdown. A.dtype is float64.
I can confirm that there is no issue with numpy - at least with what I've seen
I highly suspect the issue is with the way certain algorithms use cache lines.
OpenBLAS (yet to confirm myself) maybe switches between alignments or the way they compute matrix inverse to get more cache hits (which can explain the time difference)
Files and functions referred/involved (in case anyone wants to explore)
I think the reason is cache associativity conflicts. When your matrix is 100×100 with double precision (8 bytes), each row occupies exactly 800 bytes. This stride creates pathological cache behavior. Modern CPUs use 64-byte cache lines and each row stride of 800 bytes = 12.5 cache lines (not cleanly aligned)
In set-associative caches (typically 4-way to 16-way), memory addresses are mapped to cache sets using modular arithmetic based on the address
When multiple matrix rows are accessed (as happens during A @ A.T), elements from different rows with similar column indices compete for the same cache sets
But with 99x99 -> 99*8 = 792 bytes. 792 is not a "round" number in cache terms and distributes accesses more evenly across cache sets
I also suspect that OpenBLAS changes algorithm or probably uses multi threading when reaching matrices of size 100 or so but I have to confirm this.
If we look at the matrix as a whole right, 800 * 100 (100x100 matrix) is 80000 and 80,000 is a round number that can cross:
64 KB or 128 KB L1/L2 cache boundary
glibc malloc bin thresholds (so it allocates from a different pool)
Activity
Csral commentedon Oct 6, 2025
TL;DR:
Quick debug tips:
Okay so, I have checked the definitions of optimize and suggest_float functions, suggest_float doesn't use numpy internally - never imported. The optimize function however does use numpy twice and i verified their definitions.
At study.py line 1099:
is_repeated = ( np.isnan(float(param_value)) or np.isclose(float(param_value), float(existing_param), atol=0.0) if isinstance(param_value, Real) else param_value == existing_param )The above snippet (part of _should_skip_enqueue function) helps in identifying if same trial parameters were encountered previously and to skip the trial.
This part is called in every trial and hence should not slow down after 100th iteration. It either always slows down the code or never will.
At study.py line 829:
`
if not isinstance(params, dict):
raise TypeError("params must be a dictionary.")
`
Coming to the numpy part,
isnan function is implemented in C.
The isclose function was implemented in python and if we check it, there is no sudden algorithm changes for large data, there is however some data modifications.
Data Conversions noticed:
This is available in numeric.py at line 2374.
nabenabe0928 commentedon Oct 7, 2025
@Csral
Thank you for your comment!
I forgot to mention, but this problem seems to be very specific to Linux.
I benchmarked with the following code:
The result of
pip freeze:Dependencies
Note
For NumPy v2.X, I used
numpy==2.3.3.The benchmarking result is available below:
Although NumPy v2.X speeds up the whole pipeline, it does slows down after 100 Trials while NumPy 1.26 does not.
This looks very odd to me.
SciPy and Optuna are the only dependencies that require NumPy.
As an Optuna developer, I am pretty sure we are not switching any algorithms based on NumPy version, neither SciPy does.
andyfaff commentedon Oct 7, 2025
Can you prepare a MWE that solely relies on numpy?
nabenabe0928 commentedon Oct 7, 2025
@andyfaff
I will try my best to do so, but let me take some time.
andyfaff commentedon Oct 7, 2025
In the meantime check that you're only using a single thread in the blas libary.
Csral commentedon Oct 7, 2025
@nabenabe0928
TL;DR:
References: sampler.py at line 210 under sample_relative function under GPSampler class.
if len(trials) < self._n_startup_trials: return {}Alright, so after running the code snippet provided, I did notice there was a difference but for me it was after 10 trials which seemed even weird. The result is as follows:
So, I looked into the code of GP Sampler class and found this:
self._n_startup_trials = n_startup_trialsunder init at line 85:This variable is used to early return the sampler functions (mentioned at the end of this comment.)
Its defaulted to 10 for me and that's why I noticed difference in speed after 10 trials. Maybe its 100 for you.
To validate this, I did multiple benchmarks by modifying the startup trials count. Here's the results:
Version 1.26.4:
And results after comparing between versions:
Cause: Sample relative function
At line 199 of sampler.py in optuna module, we see the following code:
So as we can see, the function returns early for all n startup trials. That produces this slowdown after the startup trials.
To conclude: the issue is from the way optuna handles trial samples.
seberg commentedon Oct 7, 2025
@nabenabe0928 there is unlikely anything to do with NumPy. What is plausible though is that we (or the linear algebra toolkit) sped something up a lot and that transformed it from being CPU bound to being memory bound.
I.e. it seems there is some logic retaining all old samples and "doing things" with it. That data is retained and you just see things slow down like crazy.
Cache sizes/CPU speed, etc. would then determine where you see the transition between the two. Also on the old NumPy version you do see a slowdown after all, it is just a lot smoother.
Also everyone else who doesn't see one, would see one at 1000 trials.
Anyway, I'll close this, it seems exceedingly unlikely to have anything to do with NumPy (if it did, I think it would have to be a memory leak).
As a general rule, you might want to ru a profiler to see where the time even is spend, that would probably have clarified this from the start.
Plus, doing that might point to some obvious change in
optunato avoid/improve the slow-down.nabenabe0928 commentedon Oct 8, 2025
@seberg @Csral @andyfaff
I found one of the issues. (the other issue probably relates to PyTorch.)
But it seems the slowdown happens only stochastically.
I see the slowdown around 20% of the time when using
numpy>=2.0.0andn >= 100.But no slowdown happens when I use
numpy<2.0.0orn < 100.My environment is:
Important
My colleagues, who use a MacBook, do not get this issue, so it is very likely to relate to Linux, as mentioned previously.
Note
Please find the rough benchmarking results in my console below:
numpy==2.2.3, n=100
numpy==2.2.3, n=99
numpy==1.26.4,n=100
numpy==1.26.4, n=99
nabenabe0928 commentedon Oct 8, 2025
Since I fixed the random seed in the benchmarking code, each run should ideally be executed roughly in the same amount of time.
I did not open any browser and did not run any other programs in the meantime to ensure a fair comparison.
Csral commentedon Oct 8, 2025
@nabenabe0928
Okay, there really is some absurd time difference this time. I'll try looking into numpy's C internals (will take a good time cause this will be my first ever lookup). I'm not sure if I can help, but I'll try.
Here's my code:
I looped multiple times to take the average. Result:
mattip commentedon Oct 9, 2025
Thanks for the NumPy-only reproducer. Tweaking it to use 10 iterations and use threadpoolctl to limit the number of threads used by OpenBLAS shows the problem on a 24-core Ryzen machine. Everything is fine until OpenBLAS decides to use all the cores of the machine. But then the worker threads step all over eachother, causing a 200x slowdown (in the last 5 lines). This is with
np.show_runtime()ofand OpenBLAS config of
OpenBLAS 0.3.30 USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=64Maybe we should compile OpenBLAS with a shim to only use
0.9 * ncoreswhenncores>20.script to test using threads for OpenBLAS
matthew-brett commentedon Oct 9, 2025
Is it worth an issue for OpenBLAS do you think?
mattip commentedon Oct 9, 2025
I commented on OpenMathLib/OpenBLAS#5469. BTW, the test as written
X = A @ A.Tuses the OpenBLASsyrkroutines. DoingX = A @ Ahits thegemmroutines, and sees the same slowdown.A.dtypeisfloat64.Csral commentedon Nov 1, 2025
@nabenabe0928
TL;DR:
Files and functions referred/involved (in case anyone wants to explore)
File: mtrand.pyx
Multiple functions
File: _common.pyx
Multiple functions
File: mt19937.h
Multiple functions
Bitgen struct
typedef struct bitgen {
void *state;
uint64_t (*next_uint64)(void *st);
uint32_t (*next_uint32)(void *st);
double (*next_double)(void *st);
uint64_t (*next_raw)(void *st);
} bitgen_t;
Potential Issues:
I think the reason is cache associativity conflicts. When your matrix is 100×100 with double precision (8 bytes), each row occupies exactly 800 bytes. This stride creates pathological cache behavior. Modern CPUs use 64-byte cache lines and each row stride of 800 bytes = 12.5 cache lines (not cleanly aligned)
But with 99x99 -> 99*8 = 792 bytes. 792 is not a "round" number in cache terms and distributes accesses more evenly across cache sets
I also suspect that OpenBLAS changes algorithm or probably uses multi threading when reaching matrices of size 100 or so but I have to confirm this.
If we look at the matrix as a whole right, 800 * 100 (100x100 matrix) is 80000 and 80,000 is a round number that can cross:
nabenabe0928 commentedon Nov 1, 2025
@Csral
Hey, thank you for the investigation:)
Btw, the slowdown relates to here?
This change was included on 2021, so I am wondering why NumPy experienced the slowdown.
Anyways, my use case has currently no problem because I switch to
np.linalg.cholesky.Csral commentedon Nov 1, 2025
@nabenabe0928
So OpenBLAS does switch the number of threads. NumPy and a lot of other linear algebra modules depend on OpenBLAS so it does make sense.
Glad I was of help!