Repository navigation
Description
Description
I am seeing non-deterministic results from a small iterative numerical routine that repeatedly calls np.linalg.lstsq and matrix multiplication from independent Python threads. The inputs are copied per worker and are never mutated concurrently.
This appears related to #27036, #31618, and #29391, but differs in that the reproducer uses np.linalg.lstsq inside an iterative Huber-style fit and reproduces with the current NumPy/OpenBLAS combination.
Reproducer
Run this with OPENBLAS_NUM_THREADS=1 set before importing NumPy:
from concurrent.futures import ThreadPoolExecutor
import numpy as np
def mad_scale(r):
med = np.median(r)
return float(np.median(np.abs(r - med)) * 1.4826)
def robust_fit(x, values):
x = np.asarray(x, dtype=float)
values = np.asarray(values, dtype=float)
x_center = float(np.mean(x))
x_scale = max(float(np.std(x)), 1.0)
design = np.column_stack([np.ones(len(x)), (x - x_center) / x_scale])
beta = np.linalg.lstsq(design, values, rcond=None)[0]
for _ in range(20):
residual = values - design @ beta
scale = max(mad_scale(residual), 1e-4, 1e-8)
z = residual / scale
weights = np.ones(len(values))
large = np.abs(z) > 1.5
weights[large] = 1.5 / np.abs(z[large])
weighted = design * np.sqrt(weights)[:, None]
target = values * np.sqrt(weights)
updated = np.linalg.lstsq(weighted, target, rcond=None)[0]
if np.max(np.abs(updated - beta)) < 1e-10:
beta = updated
break
beta = updated
residual = values - design @ beta
scale = max(mad_scale(residual), 1e-4, 1e-8)
z = residual / scale
absolute = np.abs(z)
rho = np.where(
absolute <= 1.5,
0.5 * z**2,
1.5 * (absolute - 0.75),
)
return (
float(beta[0] - beta[1] * x_center / x_scale),
float(beta[1] / x_scale),
float(np.sum(rho) * scale**2),
)
x = np.arange(32, dtype=float)
y = 0.0003 * x + 0.02 * np.sin(x / 7) + 0.01 * np.cos(x / 13)
def worker(_):
# Each worker owns independent input arrays.
return robust_fit(x.copy(), y.copy())
with ThreadPoolExecutor(max_workers=16) as executor:
results = list(executor.map(worker, range(32)))
print("unique results:", len(set(results)))
for result in list(dict.fromkeys(results))[:8]:
print(result)On my system, one run produced multiple distinct finite results, for example:
(0.0330952861772607, -0.0013041164152690274, 0.0015116775573068594)
(0.031245266598509718, -0.001214009467587504, 0.0015700547400308554)
(0.03309441280941684, -0.0013040748263240818, 0.0016594382845258528)
The serial version is deterministic. Protecting the entire robust_fit numerical region with a process-wide threading.Lock also makes the result deterministic.
With a larger outer caller count (120), I also see:
OpenBLAS warning: precompiled NUM_THREADS exceeded,
adding auxiliary array for thread metadata.
Note that your application may still crash,
if it is calling OpenBLAS from multiple threads in parallel
Environment
- Windows x86_64
- Python 3.14.4 free-threaded (
sys._is_gil_enabled() == False) - NumPy 2.5.1
- OpenBLAS 0.3.33.112.0, pthreads, Haswell
- OpenBLAS reports
MAX_THREADS=24 OMP_NUM_THREADS=1MKL_NUM_THREADS=1OPENBLAS_NUM_THREADS=1
The observed application failure is not merely a changed low-order floating-point rounding: the selected breakpoint can change, and some runs have raised SVD did not converge or produced non-finite downstream values.
Is this expected behavior for the current OpenBLAS build when there are many concurrent application-level callers, or should NumPy/OpenBLAS provide stronger isolation or a documented limit? If this belongs in OpenBLAS rather than NumPy, please redirect me to the appropriate issue tracker.
Activity
ChengYen-Tang commentedon Aug 2, 2026
Additional stress result
I reran the synthetic reproducer in 50 fresh trials with:
x.copy()andy.copy()per callOMP_NUM_THREADS=1,MKL_NUM_THREADS=1,OPENBLAS_NUM_THREADS=1Results:
The differing results are not just a different ordering of returned futures: the coefficient and loss values differ. A single direct
np.linalg.lstsqcall is not sufficient to reproduce the issue; the failure appears in the repeated adaptive sequence containing bothlstsqanddesign @ beta.Serial execution is deterministic. A process-wide lock around the entire numerical fit, rather than only around the final result collection, makes the concurrent run deterministic.
This intermittent behavior also appears in our real classifier as different selected breakpoints, and in some runs as
SVD did not converge/non-finite downstream values.ngoldbaum commentedon Aug 2, 2026
@kumaraditya303 @itamarst do either of you know what’s happening here? I’ll try to look closer at this on Monday if neither of you get to it.
itamarst commentedon Aug 2, 2026
Only thing I can think of is that the thread-safety fixes to OpenBLAS were done for pthreads and OpenMP... but Windows has its own threading backend, untouched so far.
ngoldbaum commentedon Aug 2, 2026
@ChengYen-Tang can we see the output of
np.show_config()on your system, after installingthreadpoolctlinto your environment?ngoldbaum commentedon Aug 2, 2026
I'm not able to reproduce this on my 6-core i5-8600k Intel CPU using NumPy 2.5.1 installed from the wheel on PyPI:
I'll also note that the matrices you're using in the reproducer script are too small to hit OpenBLAS's buffer path. Are you sure the overflow warning is coming from the script you shared? Is the script you shared the real script that actually had issues or a narrowed reproducer?
Here is my system info from
np.show_config().Details
That said, I did find a completely different crash in OpenBLAS that I'll be reporting upstream... I'll link back here as well.
Ping @martin-frbg FYI about this issue
ngoldbaum commentedon Aug 4, 2026
I marked this with the "close?" label because we don't have a way to reproduce this issue.
martin-frbg commentedon Aug 4, 2026
Indeed looks like the Windows build of OpenBLAS may lack a lock around the buffer slot selection loop. Also, building OpenBLAS for a larger NUM_THREADS should help as it reduces the risk of two callers settling for the same "free" slot. I'm not sure if I can find a Windows box big enough to reproduce this
ChengYen-Tang commentedon Aug 5, 2026
Hi @ngoldbaum ,
Sorry, I just saw you messaged me.
This is the result of np.show_config() after I installed threadpoolctl:
ChengYen-Tang commentedon Aug 5, 2026
Clarification on runtime information and the 120-thread warning
The NumPy-only reproducer requested above loads one OpenBLAS runtime. With the environment variables set before importing NumPy,
threadpool_info()reports:The full research process also imports
scipy.linalg. In that process,threadpool_info()reports two separately loaded OpenBLAS DLLs:The
precompiled NUM_THREADS exceededwarning was not claimed to occur on every run of the small 16-thread Huber script. It was observed in a separate stress run of the real classifier path with a larger case and 120 outerThreadPoolExecutorcallers, with independent input copies andOMP_NUM_THREADS=MKL_NUM_THREADS=OPENBLAS_NUM_THREADS=1.The small synthetic script has an intermittent failure rate rather than a guaranteed failure: 4 of 50 trials produced multiple finite results on the reported machine. The 6-core reproduction that always produced one result is therefore useful evidence that the failure probability depends on scheduling, caller count, workload, and possibly the Windows OpenBLAS buffer path.
martin-frbg commentedon Aug 5, 2026
Thank you very much for the clarification. I'll try to reproduce the problem, but one issue on the OpenBLAS side is clearly that the project has a decades-long history of nobody being deeply familiar with Windows. Where the Unix-oid builds employ a pthread_mutex_lock, the default Windows "equivalent" chosen (through the definition of LOCK_COMMAND in common.h) is an InterlockedExchange64() which should perhaps be a CriticalSection. (@ngoldbaum obviously this plays right into your OpenBLAS issue - perhaps adding
before the fallback to using blas_lock() around line 250 of common.h is all that's needed ?
ngoldbaum commentedon Aug 5, 2026
@ChengYen-Tang on the machine where you see non-determinism, can you tell us a little more about the CPU? What model? How many cores?
ChengYen-Tang commentedon Aug 5, 2026
Hi @ngoldbaum ,
Here are the environment details and experimental observations from the machine where I see the nondeterministic results.
Environment
Host:
VM:
The guest NUMA topology should not be interpreted as the physical host memory topology. Hyper-V presents a virtual NUMA topology, and some guest memory may be backed by remote physical NUMA nodes. This may affect performance and memory latency, but I do not have evidence that NUMA imbalance alone causes the incorrect numerical results.
Software:
pthreads, Haswell, and num_threads=1
Experimental observations
The problem occurs in an iterative Huber fitting routine used by our classifier. Each worker receives independent input arrays. The routine repeatedly performs least-squares fitting and matrix-vector calculations while selecting breakpoints.
With 16 Python threads and 32 calls per thread, repeated over 50 trials, 4 trials produced multiple distinct finite output variants.
In the actual classifier, concurrent execution produced:
A process-wide lock around the complete numerical section made the output deterministic. Independent copies of the input ndarray/DataFrame data did not eliminate the behavior.
The original implementation called threadpool_limits from worker threads. For controlled runs, I removed the per-worker configuration and configured the numerical thread count once before importing NumPy. The same high-level behavior still occurred under high application-level concurrency.
In a separate stress run of the real classifier with 120 outer ThreadPoolExecutor callers, independent input copies, and OMP_NUM_THREADS=MKL_NUM_THREADS=OPENBLAS_NUM_THREADS=1, the process emitted:
precompiled NUM_THREADS exceededThis message was not produced on every run of the smaller 16-thread synthetic test.
martin-frbg commentedon Aug 6, 2026
Unfortunately I cannot reproduce the problem on small non-NUMA hardware (10 core/20 threads Ryzen AI 9) either - guess it either needs a lot of cpus or HyperV in the mix for the intermittent problem to appear. Probably the best I can do is turn all interlocks to CriticalSections and see if it still runs with that change.
ChengYen-Tang commentedon Aug 7, 2026
Hi @ngoldbaum @martin-frbg,
I continued the investigation with an automated debugging workflow using Codex. The additional isolation points to a NumPy free-threading/SIMD ufunc problem rather than shared ndarray mutation or a confirmed OpenBLAS problem.
The key observations are:
This also explains why the earlier Huber and array-construction probes appeared to fail: their intermediate design and weighting calculations contain contiguous float64 divisions, so a bad division result contaminates the later operations. The constructors themselves are not yet shown to be the root cause.
The current working hypothesis is:
I have not established whether the remaining low-level cause is a NumPy SIMD/free-threading interaction or an AVX2 virtualization issue in this Hyper-V environment. The source change above is only a diagnostic workaround, not a proposed final fix. I am sharing these results in case they help narrow the issue or motivate a targeted concurrent float64-division test.
ChengYen-Tang commentedon Aug 8, 2026
Hi @ngoldbaum @martin-frbg,
I ran additional isolation tests on the machine where the nondeterministic results occur.
I am not claiming that OpenBLAS is defective. These are observations from the environment and from independent tests.
Environment:
1. Native host test
I booted the physical host with Hyper-V disabled. Windows reported:
I then ran a standalone C++ probe. It does not use Python, NumPy, OpenBLAS, or shared ndarrays. Each worker is pinned to one Windows logical processor and tests AVX2 vector division, broadcast division, AVX2 sqrt, and scalar arithmetic.
The host topology was:
The failures were localized to two logical processors in host group 0:
These processors produced incorrect results for AVX2 vector division, broadcast division, and sqrt, while scalar arithmetic remained correct. All processors in host group 1 passed.
The same behavior was observed across all input reload modes.
This means the numerical error can be reproduced without Python, NumPy, OpenBLAS, or Hyper-V.
2. Independent stress test
I also ran y-cruncher on the same host.
Dell ePSA deep tests for memory and processor passed. This can rule out common memory or general CPU failures, but it is not sufficient to rule out an instruction-specific CPU, firmware, or platform issue.
3. GIL comparison
The original NumPy test uses Python 3.14 free-threading. I also ran the same NumPy probe in a standard Python 3.12 environment with the GIL enabled.
The GIL version reduced the failure frequency in some affinity modes, but it still failed when running on the problematic processor group. This suggests that the GIL can change thread scheduling and failure probability, but is not the root cause.
The GIL and free-threading environments use different NumPy and BLAS builds, so this is not a fully controlled backend comparison.
Current interpretation:
One broader question: would it be useful for OpenBLAS or NumPy to provide an optional diagnostic tool or self-test for validating CPU SIMD instruction paths?
For example, a diagnostic could run fixed-input, known-answer tests across the CPU dispatch paths used by NumPy and OpenBLAS, including AVX2 and FMA where applicable.
Because the failure in our case was intermittent and depended on processor placement and scheduling, a single successful run would not be sufficient. The test should repeat each operation multiple times and require all repetitions to pass.
It would also be useful to run the checks separately on every logical processor within every Windows processor group, rather than testing only the machine as a whole. The diagnostic could then report the processor group, logical processor, operation, and repetition where a mismatch occurred.
ChengYen-Tang commentedon Aug 8, 2026
One additional thought: OpenBLAS and NumPy are widely used in data analysis, machine learning research, and quantitative finance.
It is possible that other users encounter similar environment-specific numerical issues but do not detect them because there is no straightforward way to validate SIMD arithmetic per logical processor and repeat the validation enough to catch intermittent failures.
In many workflows, an incorrect finite value may simply propagate into downstream calculations without producing an obvious crash or warning. An optional diagnostic or self-test could make this class of problem much easier to identify.
This does not imply that the issue is common or that either project is necessarily responsible; it is a suggestion for making environment-level numerical problems easier to diagnose.
ngoldbaum commentedon Aug 8, 2026
Could you perhaps make a more minimal reproducer script that demonstrates the issue you're having?
NumPy is a volunteer-run project and as such things get done as people have the time and interest to do them. Of course we don't want non-determinism to happen. Also if you could try to communicate in your own words, without copy/pasting AI-generated text, it would ease communication. We prefer to communicate with humans directly.
martin-frbg commentedon Aug 8, 2026
Maybe something like https://github.com/ColinIanKing/stress-ng would be appropriate for stress testing various aspects of the hardware (I haven't tried that particular code, there will certainly be both free and commercial alternatives)
martin-frbg commentedon Aug 8, 2026
@ngoldbaum anybody on the numpy team fluent in Mandarin ? While we're all three able to communicate in English, it might be easier to discuss this between native speakers in their language
martin-frbg commentedon Aug 8, 2026
(For all its importance, OpenBLAS is pretty much a typical case of that famous XKCD cartoon https://xkcd.com/2347/ so any generic cpu stress testing would be beyond the scope and capabilities of the project)
ChengYen-Tang commentedon Aug 9, 2026
Based on what we have observed so far, one possible explanation is that a CPU instruction path occasionally produces a small numerical deviation, for example around 0.00045. That deviation may look insignificant by itself, but in a complex iterative calculation it can be carried into later steps and become greatly amplified. It may change a later fitting result, threshold decision, or branch, eventually producing a substantially different final result.
At this stage, I do not assume that NumPy or OpenBLAS is the source of the deviation. It may instead originate from the underlying execution environment, such as a processor-specific hardware issue, a motherboard or firmware problem, or operating-system scheduling. NumPy and OpenBLAS may simply be the software layers where the incorrect instruction result becomes visible.
This type of problem is difficult for ordinary users, and possibly even experienced users, to detect. A new server or a Cloud VM may pass extensive hardware and memory diagnostics, while a particular CPU instruction path can still occasionally return an incorrect finite value. The computation may not crash or produce an obvious warning, so the wrong value can silently propagate through later analysis. Users may therefore trust the hardware, operating system, NumPy, and OpenBLAS while still receiving incorrect numerical results.
I have limited knowledge of the exact conditions under which NumPy and OpenBLAS select different CPU instruction paths. Different operations, data types, memory layouts, and runtime dispatch decisions may use different implementations, so I do not know enough about their internals to define a reliable diagnostic tool for this class of problem myself.
I am mentioning this only as a possible direction based on how difficult this issue was to detect. Such a diagnostic might need to run repeated known-answer tests across the relevant numerical paths and check individual logical processors and processor groups, but I do not have enough knowledge of the dispatch implementations to propose the correct design.