Skip to content

BUG: Linear algebra heavy calculations experience sudden slowdown after the size of 100 #29884

Closed as not planned

Description

@nabenabe0928

Describe the issue:

Please take a look at here:

Reproduce the code example:

import optuna

def objective(trial: optuna.Trial) -> float:
    x = trial.suggest_float("x", -5, 5)
    y = trial.suggest_float("y", -5, 5)
    return (x - 2.0) ** 2 + (y - 3.0) ** 2

sampler = optuna.samplers.GPSampler(seed=0)
study = optuna.create_study(sampler=sampler)
study.optimize(objective, n_trials=200)

Error message:

Python and NumPy Versions:

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.

Activity

  1. Csral commented on Oct 6, 2025

    @Csral

    TL;DR:

    • I don't think this is a Numpy issue.
    • The given code doesn't get slowed down on my end
    • 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))

    This is available in numeric.py at line 2374.

  2. nabenabe0928 commented on Oct 7, 2025

    @nabenabe0928
    Author

    @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:

    import json
    
    import numpy as np
    import optuna
    
    
    numpy_version = np.__version__
    print(f"{numpy_version=}")
    study = optuna.create_study(sampler=optuna.samplers.GPSampler(seed=0))
    study.optimize(lambda trial: sum(trial.suggest_float(f"x{i}", -5, 5)**2 for i in range(10)), n_trials=150)
    trials = study.trials
    with open(f"v{numpy_version}.json", "w") as f:
        json.dump([(t.datetime_complete - trials[0].datetime_start).total_seconds() for t in trials], f)

    The result of pip freeze:

    Dependencies
    alembic==1.16.5
    colorlog==6.9.0
    filelock==3.13.1
    fsspec==2024.6.1
    greenlet==3.2.4
    Jinja2==3.1.4
    Mako==1.3.10
    MarkupSafe==3.0.3
    mpmath==1.3.0
    networkx==3.3
    numpy==1.26.4  # 2.3.3 for v2.X
    optuna==4.6.0  <-- In principle, the latest master.
    packaging==25.0
    PyYAML==6.0.3
    scipy==1.16.2
    setuptools==70.2.0
    SQLAlchemy==2.0.43
    sympy==1.13.3
    torch==2.8.0+cpu
    tqdm==4.67.1
    typing_extensions==4.15.0
    

    Note

    For NumPy v2.X, I used numpy==2.3.3.

    The benchmarking result is available below:

    Image

    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.

  3. andyfaff commented on Oct 7, 2025

    @andyfaff
    Member

    Can you prepare a MWE that solely relies on numpy?

  4. nabenabe0928 commented on Oct 7, 2025

    @nabenabe0928
    Author

    @andyfaff
    I will try my best to do so, but let me take some time.

  5. andyfaff commented on Oct 7, 2025

    @andyfaff
    Member

    In the meantime check that you're only using a single thread in the blas libary.

  6. Csral commented on Oct 7, 2025

    @Csral

    @nabenabe0928

    TL;DR:

    • Its not a numpy problem
    • 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:

    Image

    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:

    def __init__(
            self,
            *,
            seed: int | None = None,
            independent_sampler: BaseSampler | None = None,
            n_startup_trials: int = 10,
            deterministic_objective: bool = False,
            constraints_func: Callable[[FrozenTrial], Sequence[float]] | None = None,
        ) -> None:
    

    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:

    Image --- Version 2.3.3: Image

    And results after comparing between versions:

    Image
    Image

    Cause: Sample relative function

    At line 199 of sampler.py in optuna module, we see the following code:

    def sample_relative(
            self, study: Study, trial: FrozenTrial, search_space: dict[str, BaseDistribution]
        ) -> dict[str, Any]:
            self._raise_error_if_multi_objective(study)
    
            if search_space == {}:
                return {}
    
            states = (TrialState.COMPLETE,)
            trials = study._get_trials(deepcopy=False, states=states, use_cache=True)
    
            if len(trials) < self._n_startup_trials:
                return {}
    
            (
                internal_search_space,
                normalized_params,
            ) = gp_search_space.get_search_space_and_normalized_params(trials, search_space)
    
           # MORE STUFF BELOW
    

    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.

  7. seberg commented on Oct 7, 2025

    @seberg
    Member

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

  8. nabenabe0928 commented on Oct 8, 2025

    @nabenabe0928
    Author

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

    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)
    N = args.n
    runtime = 0.0
    A = rng.normal(size=(N, N))
    X = A @ A.T
    start = time.time()
    np.linalg.inv(X)
    runtime += time.time() - start
    print(f"{np.__version__=}: {runtime:.3e}[s]")

    Note

    Please find the rough benchmarking results in my console below:

    numpy==2.2.3, n=100
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 100
    np.__version__='2.3.3': 4.604e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 100
    np.__version__='2.3.3': 1.363e-03[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 100
    np.__version__='2.3.3': 8.512e-02[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 100
    np.__version__='2.3.3': 4.563e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 100
    np.__version__='2.3.3': 1.552e-01[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 100
    np.__version__='2.3.3': 3.260e-03[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 100
    np.__version__='2.3.3': 1.867e-03[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 100
    np.__version__='2.3.3': 4.444e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 100
    np.__version__='2.3.3': 3.152e-01[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 100
    np.__version__='2.3.3': 5.014e-04[s]
    
    numpy==2.2.3, n=99
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 99
    np.__version__='2.3.3': 3.841e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 99
    np.__version__='2.3.3': 4.044e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 99
    np.__version__='2.3.3': 3.779e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 99
    np.__version__='2.3.3': 4.008e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 99
    np.__version__='2.3.3': 3.867e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 99
    np.__version__='2.3.3': 3.793e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 99
    np.__version__='2.3.3': 7.703e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 99
    np.__version__='2.3.3': 4.101e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 99
    np.__version__='2.3.3': 4.044e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np2-2-3/bin/python bench.py --n 99
    np.__version__='2.3.3': 4.094e-04[s]
    
    numpy==1.26.4,n=100
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 100
    np.__version__='1.26.4': 3.967e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 100
    np.__version__='1.26.4': 4.051e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 100
    np.__version__='1.26.4': 4.196e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 100
    np.__version__='1.26.4': 4.027e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 100
    np.__version__='1.26.4': 4.156e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 100
    np.__version__='1.26.4': 4.134e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 100
    np.__version__='1.26.4': 4.001e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 100
    np.__version__='1.26.4': 4.277e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 100
    np.__version__='1.26.4': 3.982e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 100
    np.__version__='1.26.4': 4.003e-04[s]
    
    numpy==1.26.4, n=99
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 99
    np.__version__='1.26.4': 4.518e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 99
    np.__version__='1.26.4': 3.870e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 99
    np.__version__='1.26.4': 3.817e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 99
    np.__version__='1.26.4': 3.791e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 99
    np.__version__='1.26.4': 5.062e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 99
    np.__version__='1.26.4': 4.072e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 99
    np.__version__='1.26.4': 4.375e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 99
    np.__version__='1.26.4': 3.879e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 99
    np.__version__='1.26.4': 3.858e-04[s]
    shuhei@EB-B9400CBA:~/pfn-work/optuna-dev/numpy-issue$ venv-np1-26-4/bin/python bench.py --n 99
    np.__version__='1.26.4': 4.537e-04[s]
    
  9. nabenabe0928 commented on Oct 8, 2025

    @nabenabe0928
    Author

    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.

  10. Csral commented on Oct 8, 2025

    @Csral

    @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:

    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:

    Image
  11. mattip commented on Oct 9, 2025

    @mattip
    Member

    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

    {'architecture': 'Haswell',
      'filepath': '/tmp/venv312/lib/python3.12/site-packages/numpy.libs/libscipy_openblas64_-8fb3d286.so',
      'internal_api': 'openblas',
      'num_threads': 24,
      'prefix': 'libscipy_openblas',
      'threading_layer': 'pthreads',
      'user_api': 'blas',
      'version': '0.3.30'}
    

    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")
    
    Using 10 threads
        NxN matmult, N= 95: mean:0.004secs std:0.00015secs
        NxN matmult, N= 96: mean:0.003secs std:0.00032secs
        NxN matmult, N= 97: mean:0.004secs std:0.00003secs
        NxN matmult, N= 98: mean:0.004secs std:0.00002secs
        NxN matmult, N= 99: mean:0.003secs std:0.00057secs
        NxN matmult, N=100: mean:0.004secs std:0.00012secs
        NxN matmult, N=101: mean:0.003secs std:0.00042secs
        NxN matmult, N=102: mean:0.003secs std:0.00013secs
        NxN matmult, N=103: mean:0.003secs std:0.00007secs
        NxN matmult, N=104: mean:0.003secs std:0.00007secs
    Using 20 threads
        NxN matmult, N= 95: mean:0.003secs std:0.00008secs
        NxN matmult, N= 96: mean:0.003secs std:0.00005secs
        NxN matmult, N= 97: mean:0.003secs std:0.00004secs
        NxN matmult, N= 98: mean:0.003secs std:0.00004secs
        NxN matmult, N= 99: mean:0.003secs std:0.00004secs
        NxN matmult, N=100: mean:0.005secs std:0.00022secs
        NxN matmult, N=101: mean:0.005secs std:0.00006secs
        NxN matmult, N=102: mean:0.005secs std:0.00005secs
        NxN matmult, N=103: mean:0.005secs std:0.00009secs
        NxN matmult, N=104: mean:0.005secs std:0.00016secs
    Using 22 threads
        NxN matmult, N= 95: mean:0.004secs std:0.00041secs
        NxN matmult, N= 96: mean:0.003secs std:0.00072secs
        NxN matmult, N= 97: mean:0.003secs std:0.00004secs
        NxN matmult, N= 98: mean:0.003secs std:0.00005secs
        NxN matmult, N= 99: mean:0.003secs std:0.00004secs
        NxN matmult, N=100: mean:0.006secs std:0.00345secs
        NxN matmult, N=101: mean:0.005secs std:0.00084secs
        NxN matmult, N=102: mean:0.005secs std:0.00132secs
        NxN matmult, N=103: mean:0.005secs std:0.00091secs
        NxN matmult, N=104: mean:0.005secs std:0.00060secs
    Using 24 threads
        NxN matmult, N= 95: mean:0.004secs std:0.00016secs
        NxN matmult, N= 96: mean:0.003secs std:0.00072secs
        NxN matmult, N= 97: mean:0.003secs std:0.00017secs
        NxN matmult, N= 98: mean:0.003secs std:0.00017secs
        NxN matmult, N= 99: mean:0.003secs std:0.00018secs
        NxN matmult, N=100: mean:0.807secs std:0.25254secs
        NxN matmult, N=101: mean:0.757secs std:0.14294secs
        NxN matmult, N=102: mean:0.839secs std:0.18092secs
        NxN matmult, N=103: mean:0.911secs std:0.08766secs
        NxN matmult, N=104: mean:0.754secs std:0.11751secs
    
  12. matthew-brett commented on Oct 9, 2025

    @matthew-brett
    Contributor

    Is it worth an issue for OpenBLAS do you think?

  13. mattip commented on Oct 9, 2025

    @mattip
    Member

    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.

  14. Csral commented on Nov 1, 2025

    @Csral

    @nabenabe0928

    TL;DR:

    • 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)

    • File: linalg.py -> function: inv(a)
    • File: umath_linalg.cpp -> function: inv(char **args, npy_intp const *dimensions npy_intp const *steps, void *NPY_UNUSED(func))
    • File: distributions.c -> function: void random_standard_uniform_fill(bitgen_t *bitgen_state, npy_intp cnt, double *out)
    • File: legacy-distributions.c -> function: double legacy_normal(aug_bitgen_t *aug_state, double loc, double scale)

    File: mtrand.pyx

    Multiple functions

    • cdef _initialize_bit_generator(self, bit_generator):
    • def random_sample(self, size=None):
    • def normal(self, loc=0.0, scale=1.0, size=None):

    File: _common.pyx

    Multiple functions

    • cdef object double_fill(void *func, bitgen_t *state, object size, object lock, object out):
    • cdef object cont_broadcast_3(void *func, void *state, object size, object lock, ...)
    • cdef object cont(void *func, void *state, object size, object lock, int narg, ...)

    File: mt19937.h

    Multiple functions

    • static inline double mt19937_next_double(mt19937_state *state)
    • static inline uint32_t mt19937_next(mt19937_state *state)

    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)​

    • 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)
    • Page alignment boundaries → possible TLB misses
  15. nabenabe0928 commented on Nov 1, 2025

    @nabenabe0928
    Author

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

  16. Csral commented on Nov 1, 2025

    @Csral

    @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!

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions