diff --git a/.github/workflows/test-winarm-gesv.yml b/.github/workflows/test-winarm-gesv.yml new file mode 100644 index 00000000..12760e5e --- /dev/null +++ b/.github/workflows/test-winarm-gesv.yml @@ -0,0 +1,104 @@ +name: Test numpy linalg on Windows on ARM + +# Reproducer for numpy/numpy#29442 (np.linalg.inv/solve crash or hang with +# fewer than 4 OpenBLAS threads). Runs tools/test_winarm_gesv.py against +# - builtin: the OpenBLAS bundled in numpy's PyPI win_arm64 wheel +# - latest: a scipy_openblas64 win_arm64 wheel, swapped in for the DLL in +# numpy.libs. By default the nightly from anaconda.org; pass +# run_id to take the wheel from a windows-arm.yml run instead. + +on: + workflow_dispatch: + inputs: + run_id: + description: 'windows-arm.yml run id to take the wheel from (empty: anaconda.org nightly)' + required: false + default: '' + numpy_version: + description: 'numpy version from PyPI (empty: latest)' + required: false + default: '' + +permissions: + contents: read + actions: read + +jobs: + test: + name: ${{ matrix.openblas }}, ${{ matrix.threads }} thread(s) + runs-on: windows-11-arm + timeout-minutes: 30 + # The builtin OpenBLAS is expected to fail with fewer than 4 threads + continue-on-error: ${{ matrix.openblas == 'builtin' }} + strategy: + fail-fast: false + matrix: + openblas: [builtin, latest] + threads: [1, 2, 3, 4] + + steps: + - uses: actions/checkout@v6.0.1 + + - uses: actions/setup-python@v6.2.0 + with: + python-version: 3.12 + architecture: arm64 + + - name: Install numpy + shell: bash + run: | + python -m pip install "numpy${{ inputs.numpy_version && format('=={0}', inputs.numpy_version) || '' }}" + + - name: Download scipy_openblas64 wheel from run ${{ inputs.run_id }} + if: matrix.openblas == 'latest' && inputs.run_id != '' + uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + name: wheels-arm64-1 + path: dist + run-id: ${{ inputs.run_id }} + github-token: ${{ github.token }} + + - name: Download nightly scipy_openblas64 wheel + if: matrix.openblas == 'latest' && inputs.run_id == '' + shell: bash + run: | + python -m pip download --no-deps --only-binary=:all: --pre -d dist \ + -i https://pypi.anaconda.org/scientific-python-nightly-wheels/simple \ + scipy-openblas64 + + - name: Swap the new OpenBLAS into numpy.libs + if: matrix.openblas == 'latest' + shell: bash + run: | + set -xe + ls dist + python -m pip install --no-deps --force-reinstall dist/scipy_openblas64-*.whl + python - <<'EOF' + import glob, os, shutil, sysconfig + import scipy_openblas64 + site = sysconfig.get_paths()["purelib"] + old = glob.glob(os.path.join(site, "numpy.libs", "*openblas*.dll")) + assert len(old) == 1, old + new = os.path.join(scipy_openblas64.get_lib_dir(), "scipy_openblas_64.dll") + print(f"copying {new} -> {old[0]}") + shutil.copyfile(new, old[0]) + EOF + + - name: Show the OpenBLAS numpy loads + shell: bash + run: | + python - <<'EOF' + import ctypes, glob, os, sysconfig + import numpy as np + print("numpy", np.__version__) + site = sysconfig.get_paths()["purelib"] + dll = glob.glob(os.path.join(site, "numpy.libs", "*openblas*.dll"))[0] + lib = ctypes.CDLL(dll) + for name in ("scipy_openblas_get_config64_", "scipy_openblas_get_corename64_"): + fn = getattr(lib, name) + fn.restype = ctypes.c_char_p + print(f"{name}: {fn().decode()}") + EOF + + - name: Run reproducer + run: python tools/test_winarm_gesv.py --threads ${{ matrix.threads }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 81c76db5..ce3a9dfd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ## OpenBLAS v0.3.34 (v0.3.34) +### 0.3.34.481.5 (2026-11-30) + +- Patch threading in gesv on win-arm64 + ### 0.3.34.481.4 (2026-11-19) - Drop 32-bit windows wheels, use clang/flang for win-x86-64 builds diff --git a/patches-windows/gesv-woa-nthreads.patch b/patches-windows/gesv-woa-nthreads.patch new file mode 100644 index 00000000..e09c1f41 --- /dev/null +++ b/patches-windows/gesv-woa-nthreads.patch @@ -0,0 +1,13 @@ +diff --git a/interface/lapack/gesv.c b/interface/lapack/gesv.c +index ae108f336..87eedabbe 100644 +--- a/interface/lapack/gesv.c ++++ b/interface/lapack/gesv.c +@@ -124,7 +124,7 @@ void NAME(blasint *N, blasint *NRHS, FLOAT *a, blasint *ldA, blasint *ipiv, + #endif + args.nthreads = 1; + else if (args.m * args.m <= 1000) +- args.nthreads = 4; ++ args.nthreads = MIN(4, num_cpu_avail(4)); + else + args.nthreads = num_cpu_avail(4); + #else diff --git a/pyproject.toml b/pyproject.toml index 1a9b3199..f0ff9525 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ build-backend = "setuptools.build_meta" [project] name = "scipy-openblas64" # 0.3.34-481-g5137bb62 -version = "0.3.34.481.4" +version = "0.3.34.481.5" requires-python = ">=3.7" description = "Provides OpenBLAS for python packaging" readme = "README.md" diff --git a/tools/test_winarm_gesv.py b/tools/test_winarm_gesv.py new file mode 100644 index 00000000..e757b35d --- /dev/null +++ b/tools/test_winarm_gesv.py @@ -0,0 +1,97 @@ +"""Reproducer for numpy/numpy#29442: np.linalg.inv crashing or hanging on +Windows on ARM. + +OpenBLAS's ?gesv has a WoA-only branch that forced 4 threads for mid-sized +matrices (n*n <= 1000; for complex, from n*n > 300), whatever the size of the +thread pool. With fewer than 4 threads at startup that crashes (1 thread) or +hangs (2-3 threads). See patches-windows/gesv-woa-nthreads.patch. + +Each (dtype, n) runs in its own process with OPENBLAS_NUM_THREADS set, since +what matters is the thread count when OpenBLAS initializes. A process that +exits non-zero is a crash; one that runs past the timeout is a hang. + +Usage: python test_winarm_gesv.py [--threads 1] [--sizes 1-40] [--timeout 20] +""" +import argparse +import concurrent.futures +import os +import subprocess +import sys + +DTYPES = ["float32", "float64", "complex64", "complex128"] + +# Same shape as the SciPy test in the issue: a symmetric matrix, plus the +# identity, which is enough on its own to crash. +CHILD = """ +import sys +import numpy as np +dtype, n = sys.argv[1], int(sys.argv[2]) +rng = np.random.default_rng(1723059677121834) +A = rng.random((n, n)) +if dtype.startswith("complex"): + A = A + rng.random((n, n)) * 1j +A = A.astype(dtype) +A = A + A.T + n * np.eye(n, dtype=dtype) +np.linalg.inv(A) +np.linalg.solve(A, np.ones(n, dtype=dtype)) +np.linalg.inv(np.eye(n, dtype=dtype)) +""" + + +def parse_sizes(spec): + sizes = [] + for part in spec.split(","): + lo, _, hi = part.partition("-") + sizes.extend(range(int(lo), int(hi or lo) + 1)) + return sizes + + +def run_one(dtype, n, threads, timeout): + env = dict(os.environ, OPENBLAS_NUM_THREADS=str(threads)) + try: + proc = subprocess.run( + [sys.executable, "-c", CHILD, dtype, str(n)], + env=env, capture_output=True, text=True, timeout=timeout, + ) + except subprocess.TimeoutExpired: + return dtype, n, "hang", "" + if proc.returncode != 0: + code = proc.returncode & 0xFFFFFFFF + return dtype, n, f"crash (0x{code:08X})", proc.stderr.strip()[-500:] + return dtype, n, "ok", "" + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--threads", type=int, default=1) + parser.add_argument("--sizes", default="1-40") + parser.add_argument("--timeout", type=float, default=20) + parser.add_argument("--jobs", type=int, default=4) + args = parser.parse_args() + + sizes = parse_sizes(args.sizes) + print(f"OPENBLAS_NUM_THREADS={args.threads}, sizes {args.sizes}, " + f"timeout {args.timeout}s", flush=True) + + failures = [] + with concurrent.futures.ThreadPoolExecutor(args.jobs) as pool: + futures = [pool.submit(run_one, d, n, args.threads, args.timeout) + for d in DTYPES for n in sizes] + for fut in concurrent.futures.as_completed(futures): + dtype, n, status, err = fut.result() + if status != "ok": + failures.append((dtype, n, status, err)) + + for dtype in DTYPES: + bad = sorted((n, s) for d, n, s, _ in failures if d == dtype) + summary = ", ".join(f"{n}:{s}" for n, s in bad) or "all ok" + print(f"{dtype:>10}: {summary}") + for dtype, n, status, err in sorted(failures)[:3]: + if err: + print(f"--- {dtype} n={n} {status}\n{err}") + + sys.exit(1 if failures else 0) + + +if __name__ == "__main__": + main()