Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .github/workflows/wheels.yml
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ jobs:
run: |
brew fetch --retry coreutils && brew install coreutils
prefix="$RUNNER_TEMP/libomp"
# The newest at each release: libraries loaded after GraphBLAS share it, and fail if it's too old
micromamba create --yes --prefix "$prefix" --override-channels --channel conda-forge "llvm-openmp=23.1.6"
# The build string (the pin is on the version only) and the minimum macOS it supports
micromamba list --prefix "$prefix"
Expand Down Expand Up @@ -241,6 +242,16 @@ jobs:
# see https://github.com/adang1345/delvewheel/issues/33
CIBW_REPAIR_WHEEL_COMMAND_WINDOWS: "delvewheel repair --add-path \"C:\\GraphBLAS\\bin\" --no-mangle \"libgomp-1.dll;libgcc_s_seh-1.dll\" -w {dest_dir} {wheel}"

# macOS: cibuildwheel's default (delocate), then share_libomp.py, which links the libomp
# that delocate bundled as @rpath/libomp.dylib. GraphBLAS then uses an LLVM OpenMP
# runtime already in the process (e.g., from conda-forge's NumPy or numba) instead of
# starting a second one, which aborts ("OMP: Error #15"). It must run last: delocate
# would undo it. The repair runs in the build venv, where `python` is the Python
# being built for and has delocate.
CIBW_REPAIR_WHEEL_COMMAND_MACOS: >-
delocate-wheel --require-archs {delocate_archs} -w {dest_dir} -v {wheel} &&
python {project}/continuous_integration/share_libomp.py {dest_dir}

# make cibuildwheel install test dependencies from pyproject.toml
CIBW_TEST_EXTRAS: "test"

Expand Down
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@ or
conda install -c conda-forge python-suitesparse-graphblas
```

### OpenMP on macOS
The macOS wheels bundle LLVM's OpenMP runtime (`libomp`) as `@rpath/libomp.dylib`, the name that
conda-forge's packages and numba link theirs by, so these libraries share one runtime: whichever
of them loads first serves them all. If that is a `libomp` older than LLVM 19, which lacks
`__kmpc_dispatch_deinit`, importing this package fails. Update it (in conda: `llvm-openmp>=19`),
or, unless it came with NumPy (which this package imports first), import this package before the
one that loads it.

Libraries that load a `libomp` under another name don't share it, and two OpenMP runtimes in one
process can abort with "OMP: Error #15" (or hang, with `KMP_DUPLICATE_LIB_OK=TRUE`). Homebrew's
`libomp`, which the xgboost and lightgbm wheels use, shares only if this package loads first; the
copies bundled in the scikit-learn wheel and recent PyTorch wheels never do. In a conda
environment, prefer conda-forge's `python-suitesparse-graphblas`.

### In the browser (Pyodide)
PyPI also has WebAssembly wheels for [Pyodide](https://pyodide.org) 314 (Python 3.14) and
0.29.4 or later (Python 3.13), the `pyemscripten` platform of
Expand Down
220 changes: 220 additions & 0 deletions continuous_integration/share_libomp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
"""Make the libomp in a delocated macOS wheel shareable: link it as @rpath/libomp.dylib.

Usage: python share_libomp.py WHEEL_OR_DIRECTORY (a directory must hold exactly one wheel)

It runs after delocate-wheel (see CIBW_REPAIR_WHEEL_COMMAND_MACOS in wheels.yml). delocate
copies libomp into suitesparse_graphblas/.dylibs/, gives the copy an install name of its own
(/DLC/suitesparse_graphblas/.dylibs/libomp.dylib) and links libgraphblas to it by path. A
process that already has an LLVM OpenMP runtime (conda-forge's OpenBLAS, numba's omp layer)
then gets a second one, and libomp aborts with "OMP: Error #15" (with KMP_DUPLICATE_LIB_OK=TRUE,
the two deadlock). Loading the copy privately can't avoid that: libomp registers itself per
process whatever its file or install name, and dyld binds both copies' weak symbols to the one
loaded first.

conda-forge's libomp has the install name @rpath/libomp.dylib, which is also what numba's omp
layer and conda-forge's OpenBLAS link, and dyld resolves @rpath/libomp.dylib to an already-loaded
image with that install name before it searches LC_RPATHs. So the copy gets that install name,
and libgraphblas links @rpath/libomp.dylib with an LC_RPATH that reaches the copy: GraphBLAS
uses a libomp that is already loaded, or else loads the copy, which libraries loaded later then
share. One runtime either way. The file stays where it is: python-graphblas looks for it there.

An @rpath/libomp.dylib loaded before GraphBLAS must be LLVM 19 or newer, which has
__kmpc_dispatch_deinit; otherwise importing suitesparse_graphblas fails with "Symbol not found".
That minimum comes from the OpenMP functions that libgraphblas calls, so the script fails if it
calls one that isn't in OPENMP_IMPORTS.
"""

import os
import re
import subprocess
import sys
from pathlib import Path

from delocate.wheeltools import InWheelCtx

OMP = Path("suitesparse_graphblas/.dylibs/libomp.dylib")
SHARED = "@rpath/libomp.dylib"
# libomp, libiomp5, libgomp: a wheel holding any other one isn't the layout this script knows
OPENMP = re.compile(r"lib[gi]?omp[\d.]")
LINKS = {
"LC_LOAD_DYLIB",
"LC_LOAD_WEAK_DYLIB",
"LC_LOAD_UPWARD_DYLIB",
"LC_LAZY_LOAD_DYLIB",
"LC_REEXPORT_DYLIB",
}
# What libgraphblas imports from libomp (10.5.2 and 10.5.3). __kmpc_dispatch_deinit is the
# newest, from LLVM 19. If it imports another one, the oldest libomp it can share may be newer:
# check, then update this list, the README and the ImportError message in __init__.py.
OPENMP_IMPORTS = {
"__kmpc_dispatch_deinit",
"__kmpc_dispatch_init_4",
"__kmpc_dispatch_init_8",
"__kmpc_dispatch_init_8u",
"__kmpc_dispatch_next_4",
"__kmpc_dispatch_next_8",
"__kmpc_dispatch_next_8u",
"__kmpc_end_reduce_nowait",
"__kmpc_flush",
"__kmpc_for_static_fini",
"__kmpc_for_static_init_4",
"__kmpc_for_static_init_8",
"__kmpc_for_static_init_8u",
"__kmpc_fork_call",
"__kmpc_global_thread_num",
"__kmpc_push_num_threads",
"__kmpc_reduce_nowait",
"omp_destroy_lock",
"omp_get_max_threads",
"omp_get_wtime",
"omp_init_lock",
"omp_set_lock",
"omp_unset_lock",
}
# Apple's tools, not whichever come first on PATH (a conda env can have cctools-port's)
CODESIGN = "/usr/bin/codesign"
INSTALL_NAME_TOOL = "/usr/bin/install_name_tool"
NM = "/usr/bin/nm"
OTOOL = "/usr/bin/otool"


def fail(message):
sys.exit(f"share_libomp: {message}")


def run(*args):
proc = subprocess.run(args, capture_output=True, text=True)
if proc.returncode:
fail(f"{' '.join(map(str, args))} failed:\n{proc.stderr}")
return proc.stdout


def load_commands(path):
"""[(command, install name or rpath)] for the load commands of a Mach-O file."""
pattern = r"cmd (LC_\w+)\n +cmdsize \d+\n +(?:name|path) (.*) \(offset \d+\)"
return re.findall(pattern, run(OTOOL, "-l", path))


def install_ids(path):
return [name for cmd, name in load_commands(path) if cmd == "LC_ID_DYLIB"]


def rpaths(path):
# conda-forge's libraries have "@loader_path/", which is the same as "@loader_path"
return [name.rstrip("/") for cmd, name in load_commands(path) if cmd == "LC_RPATH"]


def machos():
# InWheelCtx has changed into the unpacked wheel, so paths are relative to its root
return sorted(p for p in Path().rglob("*") if p.suffix in {".so", ".dylib"} and p.is_file())


def omp_users():
"""{Mach-O file: its links to OpenMP runtimes}, for the files that have any."""
users = {}
for path in machos():
links = [n for c, n in load_commands(path) if c in LINKS and OPENMP.match(n.split("/")[-1])]
if links:
users[path] = links
return users


def openmp_imports(path):
# nm -u lists undefined symbols with C's leading underscore
names = (line.removeprefix("_") for line in run(NM, "-u", path).split())
return {name for name in names if name.startswith(("__kmpc_", "omp_"))}


def rpath_to_omp(path):
rel = os.path.relpath(OMP.parent, path.parent)
return "@loader_path" if rel == "." else f"@loader_path/{rel}"


def share():
"""Link the bundled libomp as @rpath/libomp.dylib in the unpacked wheel; return what changed."""
if not OMP.is_file():
fail(f"no {OMP} in the wheel; did delocate bundle libomp?")
others = [p for p in machos() if OPENMP.match(p.name) and p != OMP]
if others:
fail(f"OpenMP runtimes other than {OMP} in the wheel: {others}")
changed = []
if install_ids(OMP) != [SHARED]:
run(INSTALL_NAME_TOOL, "-id", SHARED, OMP)
changed.append(OMP)
for path, links in omp_users().items():
args = []
for link in links:
if link == SHARED:
continue
# delocate links the copy relative to the file that uses it
target = link.removeprefix("@loader_path/")
if target == link or Path(os.path.normpath(path.parent / target)) != OMP:
fail(f"{path} links {link}, which is not {OMP}")
args += ["-change", link, SHARED]
if rpath_to_omp(path) not in rpaths(path):
args += ["-add_rpath", rpath_to_omp(path)]
if args:
run(INSTALL_NAME_TOOL, *args, path)
changed.append(path)
for path in changed:
# install_name_tool invalidates the signature, and arm64 won't load unsigned code
run(CODESIGN, "--force", "--sign", "-", path)
return changed


def check():
"""Fail unless the unpacked wheel shares libomp as intended; return the files that link it."""
if install_ids(OMP) != [SHARED]:
fail(f"{OMP} has install name {install_ids(OMP)}, not {SHARED}")
users = omp_users()
if not users:
fail(f"nothing in the wheel links {OMP}")
for path, links in users.items():
if links != [SHARED]:
fail(f"{path} links {links}, not [{SHARED!r}]")
# dyld searches them in order, so another one could find another libomp first
if rpaths(path) != [rpath_to_omp(path)]:
fail(f"{path} has rpaths {rpaths(path)}, not just {rpath_to_omp(path)!r}")
new = openmp_imports(path) - OPENMP_IMPORTS
if new:
fail(
f"{path} imports OpenMP functions it didn't before: {sorted(new)}. The oldest "
"libomp it can share may be newer now; see OPENMP_IMPORTS"
)
for path in machos():
# x86_64 linkers don't sign, and unsigned code runs there; code with a bad signature doesn't
proc = subprocess.run([CODESIGN, "--verify", path], capture_output=True, text=True)
if proc.returncode and "code object is not signed at all" not in proc.stderr:
fail(f"bad signature: {proc.stderr}")
return sorted(users)


def main(arg):
wheel = Path(arg)
if wheel.is_dir():
wheels = sorted(wheel.glob("*.whl"))
if len(wheels) != 1:
fail(f"expected one wheel in {arg}, found {[w.name for w in wheels]}")
[wheel] = wheels
wheel = wheel.resolve() # InWheelCtx changes directory
# Not *.whl, so that cibuildwheel can't take it for the repaired wheel
tmp = wheel.with_suffix(".whl.tmp")
with InWheelCtx(wheel) as ctx:
changed = share()
users = check()
if changed:
# Write it (with a new RECORD) on leaving the block; on an error, don't
ctx.out_wheel = str(tmp)
if changed:
# Only now, so that an error while writing can't leave a truncated wheel
os.replace(tmp, wheel)
print(
f"share_libomp: {wheel.name}: {', '.join(map(str, users))} link {SHARED}; "
f"changed: {', '.join(map(str, changed)) or 'nothing'}"
)


if __name__ == "__main__":
if len(sys.argv) != 2:
fail("usage: python share_libomp.py WHEEL_OR_DIRECTORY")
main(sys.argv[1])
37 changes: 35 additions & 2 deletions suitesparse_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,41 @@
import struct as _struct

from . import exceptions as ex
from . import utils
from ._graphblas import ffi, lib


def _old_libomp_error(error):
"""A clearer ImportError than `error` if a loaded libomp lacks what GraphBLAS needs, or None.

The macOS wheels share an LLVM OpenMP runtime that is already loaded (see the README), and
dyld then fails to load libgraphblas if that runtime lacks an OpenMP function it calls.
"""
import re

text = str(error)
missing = re.search(r"Symbol not found: _(__kmpc_\w+|omp_\w+)", text)
if not missing:
return None
where = re.search(r"Expected in:\s+(?:<[^>]*>\s+)?(.+)", text)
loaded = f" ({where[1].strip()})" if where else ""
return ImportError(
f"Another package already loaded an LLVM OpenMP runtime (libomp) older than LLVM 19"
f"{loaded}, which lacks {missing[1]} and so can't serve this build of "
"SuiteSparse:GraphBLAS. Update that libomp (in conda: llvm-openmp>=19), or in a conda "
"environment install conda-forge's python-suitesparse-graphblas instead. If the package "
"that loaded it isn't NumPy (which suitesparse_graphblas imports first), importing "
"suitesparse_graphblas before that package also works."
)


try:
# utils imports NumPy, then _graphblas, which loads libgraphblas and with it libomp
from . import utils
from ._graphblas import ffi, lib
except ImportError as exc: # pragma: no cover (an import that fails)
error = _old_libomp_error(exc)
if error is None:
raise
raise error from exc

_is_osx_arm64 = platform.machine() == "arm64"
_is_ppc64le = platform.machine() == "ppc64le"
Expand Down
Loading
Loading