From 801909bcc058fb08891f7cf872d511afa98fc0a9 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Wed, 2 Dec 2026 00:15:07 -0700 Subject: [PATCH] Set the macOS OpenMP defaults when litkit is imported On macOS, torch, faiss-cpu and scikit-learn each bundle libomp. Two OpenMP runtimes in one process abort with "OMP: Error #15" unless KMP_DUPLICATE_LIB_OK is set, and then segfault or hang unless OpenMP runs one thread. litkit survived only because importing sentence-transformers imports scikit-learn, which sets KMP_DUPLICATE_LIB_OK. The thread defaults lived in cli.py and __main__.py, so importing litkit.index got none of them. The package __init__ now sets KMP_DUPLICATE_LIB_OK=TRUE, OMP_NUM_THREADS=1 and MKL_NUM_THREADS=1 on macOS, as defaults only (torch reads both thread variables). A value already set wins, with a RuntimeWarning when it allows more than one thread, since a CPU build then segfaults without a message. FAISS_NUM_THREADS has no effect: faiss reads OMP_NUM_THREADS. The docs no longer claim otherwise. Fixes #16 --- CHANGELOG.md | 1 + LITKIT_MAC_GUIDE.md | 15 ++-- src/litkit/__init__.py | 36 ++++++++++ src/litkit/__main__.py | 19 +---- src/litkit/cli.py | 18 +---- src/litkit/embeddings/devices.py | 11 +-- test_build.sh | 4 +- tests/conftest.py | 15 ++-- tests/test_macos_openmp.py | 120 +++++++++++++++++++++++++++++++ 9 files changed, 186 insertions(+), 53 deletions(-) create mode 100644 tests/test_macos_openmp.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 30437bc..b26d6e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ internal versions are summarized under 0.3.33. - The batch scripts and the cluster guide remove the writer guard litkit creates, `workspace/sqlite/faiss_writer.guard`, instead of `workspace/.writer_guard`. (#15) - Builds commit articles in batches instead of one at a time. A producer commits a tar's articles only at the tar boundary, just before it finalizes the tar's segments, so after a failed flush or a job killed mid-tar, a restart without `--rebuild` processes them again instead of skipping them with no vectors. A writer commits at each flush, once the batch is embedded, at each checkpoint and at each tar boundary, so a failed embedding rolls back only the articles since the last of those; earlier rows of the batch still wait for the backfill. Without `--strict-ingest`, an error after which SQLite has rolled back the batch, such as a full disk, now stops the build instead of skipping the article. (#13) - Removing vectors from a FAISS index before re-adding them (`--update`, backfill, segment ingestion) takes time proportional to the index size instead of index size times IDs removed. Removing 20,000 IDs from 1M vectors took 10.3 s and now takes 0.03 s. (#14) +- On macOS, importing litkit sets `KMP_DUPLICATE_LIB_OK=TRUE`, `OMP_NUM_THREADS=1` and `MKL_NUM_THREADS=1` unless they're already set, and warns when either thread variable allows more than one thread. torch and faiss-cpu each bundle libomp, and with both loaded a process aborted (`OMP: Error #15`), segfaulted or hung unless scikit-learn had happened to set `KMP_DUPLICATE_LIB_OK`. The setting also limits numpy's OpenBLAS and child processes to one thread. (#16) ## [0.3.36] - 2026-11-30 diff --git a/LITKIT_MAC_GUIDE.md b/LITKIT_MAC_GUIDE.md index d3b6fcd..edc07f3 100644 --- a/LITKIT_MAC_GUIDE.md +++ b/LITKIT_MAC_GUIDE.md @@ -460,7 +460,7 @@ REFERENCES | `LITKIT_WORKSPACE` | Override workspace directory | | `HF_HOME` | HuggingFace cache location | | `HF_HUB_OFFLINE=1` | Force offline mode (no model downloads) | -| `FAISS_NUM_THREADS=1` | Force single-threaded FAISS (fixes hangs) | +| `OMP_NUM_THREADS=1`, `MKL_NUM_THREADS=1` | One thread, which torch and FAISS need to share a process on macOS (torch reads both); litkit sets them unless they're already set | | `LITKIT_DEBUG=1` | Enable verbose debug output | --- @@ -540,16 +540,21 @@ rm -rf .venv uv sync ``` -### FAISS Hangs During Build +### FAISS Hangs or the Build Crashes -FAISS can hang on some systems. Set single-threaded mode: +torch and FAISS each load their own OpenMP runtime on macOS, and with more than +one thread a build can hang or crash with no message. litkit sets +`OMP_NUM_THREADS=1` and `MKL_NUM_THREADS=1` when it's imported (torch reads +both), but a value already in your environment wins, and litkit warns about it. +Unset them or set them to 1: ```bash -export FAISS_NUM_THREADS=1 +export OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 litkit --build-only --faiss-writer ... ``` -The `test_build.sh` script sets this automatically. +The `test_build.sh` script sets `OMP_NUM_THREADS=1` unless you set it. +`FAISS_NUM_THREADS` has no effect: FAISS reads `OMP_NUM_THREADS`. ### Verifying MPS Setup diff --git a/src/litkit/__init__.py b/src/litkit/__init__.py index 395276b..18c65e0 100644 --- a/src/litkit/__init__.py +++ b/src/litkit/__init__.py @@ -3,6 +3,42 @@ from __future__ import annotations +import os as _os +import sys as _sys + +# macOS: torch, faiss-cpu and scikit-learn each bundle their own libomp. A process +# that initializes two copies aborts with "OMP: Error #15" unless +# KMP_DUPLICATE_LIB_OK is set, and with two copies running more than one thread, +# torch segfaults or FAISS hangs. Both are loaded for every build and query, so set +# these before anything imports torch or faiss. The package __init__ runs first +# for the litkit command, python -m litkit and library imports alike (#16). +# Defaults only: a value set in the environment wins, with a warning, since a CPU +# build then segfaults without a message. FAISS reads OMP_NUM_THREADS, not +# FAISS_NUM_THREADS. +if _sys.platform == "darwin": + + def _one_thread(value: str) -> bool: + # libomp reads ASCII digits only; the first entry is the outermost level, so + # "1,4" and "01" run one thread. "", "0", "auto" and "+1" do not. + first = value.split(",")[0].strip(" \t\n\r\f\v") + return first.isascii() and first.isdigit() and int(first) == 1 + + _os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE") + # torch takes its thread count from OMP_NUM_THREADS, then MKL_NUM_THREADS. + for _var in ("OMP_NUM_THREADS", "MKL_NUM_THREADS"): + _threads = _os.environ.setdefault(_var, "1") + if not _one_thread(_threads): + import warnings as _warnings + + _warnings.warn( + f"{_var}={_threads}: on macOS, torch and faiss-cpu each load their own " + "OpenMP runtime, and with more than one thread a process that runs " + "both on the CPU segfaults or hangs (litkit #16). " + f"Set {_var}=1 or unset it.", + RuntimeWarning, + stacklevel=2, + ) + import logging from importlib.metadata import PackageNotFoundError, version diff --git a/src/litkit/__main__.py b/src/litkit/__main__.py index 55d0b0a..ecc66a9 100644 --- a/src/litkit/__main__.py +++ b/src/litkit/__main__.py @@ -1,24 +1,9 @@ # src/litkit/__main__.py """LitKit entry point. -CRITICAL: Thread limits are set BEFORE any imports that could pull in FAISS -or other OpenMP-using C extensions. On macOS, FAISS + MPS threading causes -segfaults unless FAISS_NUM_THREADS=1 and OMP_NUM_THREADS=1. - -These env vars MUST be set before the C extensions are loaded - setting them -after import has no effect because OpenMP initializes its thread pool at -library load time. +The macOS OpenMP settings (KMP_DUPLICATE_LIB_OK, OMP_NUM_THREADS) are set in +litkit/__init__.py, which runs before this module. """ -import os -import sys - -# Set thread limits BEFORE any heavy imports (faiss, numpy, torch, etc.) -# macOS: FAISS + MPS threading causes segfaults -if sys.platform == "darwin": - os.environ.setdefault("FAISS_NUM_THREADS", "1") - os.environ.setdefault("OMP_NUM_THREADS", "1") - -# Now safe to import cli (which eventually imports faiss) from .cli import main if __name__ == "__main__": diff --git a/src/litkit/cli.py b/src/litkit/cli.py index ef76eac..b42293b 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1,19 +1,7 @@ # src/litkit/cli.py -# ═══════════════════════════════════════════════════════════════════════════════ -# CRITICAL: macOS FAISS threading fix MUST come BEFORE any other imports -# ═══════════════════════════════════════════════════════════════════════════════ -# On macOS, FAISS + MPS threading causes segfaults. The env vars must be set -# BEFORE any C extension (faiss, numpy, torch) is loaded because OpenMP -# initializes its thread pool at library load time. -# -# This block must stay at the absolute top of this file. -# ═══════════════════════════════════════════════════════════════════════════════ -import os as _os -import sys as _sys -if _sys.platform == "darwin": - _os.environ.setdefault("FAISS_NUM_THREADS", "1") - _os.environ.setdefault("OMP_NUM_THREADS", "1") -# ═══════════════════════════════════════════════════════════════════════════════ +# The macOS OpenMP settings (KMP_DUPLICATE_LIB_OK, OMP_NUM_THREADS) are set in +# litkit/__init__.py, which runs before this module and before anything imports +# faiss or torch (#16). """Litkit CLI entrypoint. diff --git a/src/litkit/embeddings/devices.py b/src/litkit/embeddings/devices.py index 22b4dab..1171a04 100644 --- a/src/litkit/embeddings/devices.py +++ b/src/litkit/embeddings/devices.py @@ -65,8 +65,10 @@ def configure_threads(default: str | None = None) -> dict[str, str]: NB: This function must be called before importing faiss. Platform-specific behavior: - - macOS: Forces FAISS_NUM_THREADS=1 and OMP_NUM_THREADS=1 by default - to prevent segfaults from FAISS + MPS threading conflicts. + - macOS: Sets OMP_NUM_THREADS=1 and MKL_NUM_THREADS=1 by default, as + importing litkit does: torch and faiss-cpu each load their own OpenMP + runtime, and with more than one thread a process running both segfaults or + hangs (#16). FAISS reads OMP_NUM_THREADS; FAISS_NUM_THREADS has no effect. - Linux/HPC: Uses CPU-count based heuristics for reasonable parallelism. Users can override with LITKIT_THREADS env var. @@ -84,14 +86,13 @@ def configure_threads(default: str | None = None) -> dict[str, str]: ): os.environ.setdefault(k, val) elif sys.platform == "darwin": - # macOS: FAISS + MPS threading causes segfaults - # Force single-threaded operation by default + # macOS: two OpenMP runtimes (torch, faiss-cpu) need one thread (#16) os.environ.setdefault("FAISS_NUM_THREADS", "1") os.environ.setdefault("OMP_NUM_THREADS", "1") + os.environ.setdefault("MKL_NUM_THREADS", "1") # torch reads it too # Other thread vars can remain at reasonable defaults for k in ( "OPENBLAS_NUM_THREADS", - "MKL_NUM_THREADS", "BLIS_NUM_THREADS", "VECLIB_MAXIMUM_THREADS", ): diff --git a/test_build.sh b/test_build.sh index 6c588fe..736823b 100755 --- a/test_build.sh +++ b/test_build.sh @@ -134,8 +134,8 @@ if [[ "$MISSING" -gt 0 ]]; then fi # --- Set environment for Mac --- -# FAISS hangs on macOS with multi-threading + MPS -export FAISS_NUM_THREADS="${FAISS_NUM_THREADS:-1}" +# torch and faiss-cpu each load an OpenMP runtime on macOS; with more than one +# OpenMP thread a build segfaults or hangs (#16). FAISS reads OMP_NUM_THREADS. export OMP_NUM_THREADS="${OMP_NUM_THREADS:-1}" # litkit reads LITKIT_WORKSPACE for output location diff --git a/tests/conftest.py b/tests/conftest.py index e3e220a..c7b6b12 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -13,18 +13,15 @@ import tarfile import tempfile -# macOS: torch, faiss-cpu and scikit-learn each ship libomp, and a process that -# initializes two of them aborts (#16). litkit survives only because importing -# sentence-transformers sets KMP_DUPLICATE_LIB_OK as a side effect. With two -# runtimes loaded, torch then segfaults in multi-threaded CPU kernels unless -# OpenMP runs one thread, which is what litkit's __main__ and cli.py set. -# The slow tier runs torch after FAISS in one process, so it needs both, set -# before faiss or torch is imported. -# Forced, not defaulted: OMP_NUM_THREADS=8 in the user's shell segfaults the slow tier. +# macOS: torch, faiss-cpu and scikit-learn each ship libomp. A process that +# initializes two of them aborts unless KMP_DUPLICATE_LIB_OK is set, and then +# torch segfaults or FAISS hangs unless OpenMP runs one thread (#16). Importing +# litkit sets both as defaults. The slow tier runs torch after FAISS in one +# process, so they're forced here, before faiss or torch is imported: +# OMP_NUM_THREADS=8 in the user's shell would segfault it. if sys.platform == "darwin": os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" os.environ["OMP_NUM_THREADS"] = "1" - os.environ["FAISS_NUM_THREADS"] = "1" import numpy as np # noqa: E402 import pytest # noqa: E402 diff --git a/tests/test_macos_openmp.py b/tests/test_macos_openmp.py new file mode 100644 index 0000000..b8e6b1e --- /dev/null +++ b/tests/test_macos_openmp.py @@ -0,0 +1,120 @@ +"""macOS OpenMP runtimes: torch, faiss-cpu and scikit-learn each bundle libomp (#16). + +litkit loads torch and faiss in one process for every build and query. Two OpenMP +runtimes in one process abort it ("OMP: Error #15") unless KMP_DUPLICATE_LIB_OK is +set, and then segfault or hang unless OpenMP runs one thread. litkit used to survive +only because importing sentence-transformers imports scikit-learn, which sets +KMP_DUPLICATE_LIB_OK. +""" + +import importlib.util +import os +import subprocess +import sys + +import pytest + +OPENMP_VARS = ("KMP_DUPLICATE_LIB_OK", "OMP_NUM_THREADS", "MKL_NUM_THREADS") + +# Imports an entry module with scikit-learn blocked, then runs torch and faiss in +# the given order and again. +PROBE = """\ +import importlib, sys + +class NoSklearn: + def find_spec(self, name, path=None, target=None): + if name == "sklearn" or name.startswith("sklearn."): + raise ImportError("scikit-learn is blocked in this test") + +sys.meta_path.insert(0, NoSklearn()) +importlib.import_module(sys.argv[1]) +import numpy as np + +def run_torch(): + import torch + x = torch.randn(512, 512) + for _ in range(20): + x = torch.tanh(x @ x / 512) + +def run_faiss(): + import faiss + index = faiss.IndexFlatIP(64) + index.add(np.random.rand(2000, 64).astype("float32")) + index.search(np.random.rand(200, 64).astype("float32"), 5) + +first = (run_torch, run_faiss) if sys.argv[2] == "torch-first" else (run_faiss, run_torch) +for step in first + first: + step() +assert "sklearn" not in sys.modules +print("ok") +""" + + +def _env(**extra): + # PYTHONWARNINGS from the developer's shell could hide or raise the warning. + env = {k: v for k, v in os.environ.items() if k not in OPENMP_VARS + ("PYTHONWARNINGS",)} + env.update(extra) + return env + + +@pytest.mark.skipif(sys.platform != "darwin", reason="the Linux wheels share GNU libgomp") +@pytest.mark.skipif(importlib.util.find_spec("torch") is None, reason="needs torch") +@pytest.mark.parametrize("order", ["torch-first", "faiss-first"]) +# The litkit command imports litkit.cli (as python -m litkit does); a library user +# might import litkit.index alone. +@pytest.mark.parametrize("entry", ["litkit.cli", "litkit.index"]) +def test_torch_and_faiss_run_in_one_process_without_scikit_learn(entry, order): + """#16: on main, each case segfaults or aborts with OMP Error #15. litkit.cli set + OMP_NUM_THREADS but not KMP_DUPLICATE_LIB_OK; litkit.index set neither.""" + try: + proc = subprocess.run( + [sys.executable, "-c", PROBE, entry, order], + env=_env(), + capture_output=True, + text=True, + timeout=120, + ) + except subprocess.TimeoutExpired as e: + raise RuntimeError(f"torch and faiss hung after importing {entry}") from e + assert (proc.returncode, proc.stdout.strip()) == (0, "ok"), proc.stderr[-2000:] + + +@pytest.mark.parametrize("preset", [{}, dict(zip(OPENMP_VARS, ("keep", "4", "2"), strict=True))]) +def test_openmp_defaults_are_set_on_macos_only_and_never_override(preset): + code = f"import os, litkit; print(*(os.environ.get(v) for v in {OPENMP_VARS!r}))" + proc = subprocess.run( + [sys.executable, "-c", code], + env=_env(**preset), + capture_output=True, + text=True, + timeout=60, + check=True, + ) + defaults = ("TRUE", "1", "1") if sys.platform == "darwin" else (None, None, None) + expected = [preset.get(v, d) for v, d in zip(OPENMP_VARS, defaults, strict=True)] + assert proc.stdout.split() == [str(e) for e in expected] + + +ONE_THREAD = [None, "1", "01", " 1", "1,4"] +# torch runs every core for "", "0" and "auto"; libomp rejects "+1" and runs every core. +MORE_THREADS = ["8", "4,2", "", "0", "auto", "+1"] + + +# torch takes its thread count from OMP_NUM_THREADS, then MKL_NUM_THREADS. +@pytest.mark.parametrize("var", ["OMP_NUM_THREADS", "MKL_NUM_THREADS"]) +@pytest.mark.parametrize("threads", ONE_THREAD + MORE_THREADS) +def test_macos_warns_when_openmp_threads_are_set_above_one(var, threads): + """#16: with more than one thread set in the environment, which litkit leaves alone, + a CPU build on macOS segfaults with no message. Values that run one thread are + controls.""" + env = _env() if threads is None else _env(**{var: threads}) + proc = subprocess.run( + [sys.executable, "-c", "import litkit"], + env=env, + capture_output=True, + text=True, + timeout=60, + check=True, + ) + warned = f"RuntimeWarning: {var}=" in proc.stderr + assert warned == (sys.platform == "darwin" and threads in MORE_THREADS), proc.stderr