From 3c807f1cc58dcf929a3484c7b90590cfc3d546f1 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:46:53 +0400 Subject: [PATCH 01/10] Set OpenMP and BLAS thread counts in the US base and local-area commands The base and local-area commands now set OMP_NUM_THREADS, OPENBLAS_NUM_THREADS, MKL_NUM_THREADS, BLIS_NUM_THREADS, VECLIB_MAXIMUM_THREADS and NUMEXPR_NUM_THREADS before numpy loads. Each gets the count its library already uses, so a host's output bytes do not change. Values already set are kept, and importing the tools changes nothing. On Linux the OpenBLAS thread count changes output bytes, so the base command now records real counts and refuses a resume with different ones. Co-Authored-By: Claude Opus 5.5 --- .../us-build-thread-environment.changed.md | 3 + docs/us-modal-stage-runbook.md | 97 +++- .../us/test_us_build_tool_thread_defaults.py | 453 ++++++++++++++++++ pyproject.toml | 5 + tools/_legacy/build_us_acs_multispine_base.py | 15 +- tools/build_us_acs_multispine_base.py | 9 + tools/build_us_puf_support_base.py | 15 +- tools/us_build_thread_environment.py | 86 ++++ 8 files changed, 678 insertions(+), 5 deletions(-) create mode 100644 changelog.d/us-build-thread-environment.changed.md create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py create mode 100644 tools/us_build_thread_environment.py diff --git a/changelog.d/us-build-thread-environment.changed.md b/changelog.d/us-build-thread-environment.changed.md new file mode 100644 index 0000000000..03957dc843 --- /dev/null +++ b/changelog.d/us-build-thread-environment.changed.md @@ -0,0 +1,3 @@ +The US base and local-area build commands now set their OpenMP, BLAS and numexpr thread variables before numpy loads, each to the count its library already uses: `OMP_NUM_THREADS` if it names a count, otherwise `os.process_cpu_count()`, with no upper limit. numexpr keeps its own rule. Values already set are kept, and importing the tools changes nothing. + +On Linux the OpenBLAS thread count changes output bytes, so a build's output already depends on the host's count. This change keeps each count, so it keeps a host's output, but the base command now records real counts in `thread_environment` and refuses a resume on a host with a different count. On hosts with more logical CPUs than physical cores, scikit-learn's sign classifier now uses all logical CPUs. OpenMP and BLAS still do not follow a CPU quota outside Modal. diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index f247120d71..9cc4772328 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -395,6 +395,94 @@ that release's current build. Modal, 3 November 2026: the telemetry token"); it did not cover a container reaching the collector. +## Thread variables + +The base command (`tools/build_us_puf_support_base.py`) and the local-area +command (`tools/build_us_acs_multispine_base.py`, and +`tools/_legacy/build_us_acs_multispine_base.py` when that file is run directly) +set their OpenMP, BLAS and numexpr thread variables before numpy loads +(`tools/us_build_thread_environment.py`). They do this only when started as +commands, not when imported. A value already in the environment, from an +operator, a plan or Modal, is kept. The commits pinned by the base and +local-area plans in this runbook predate this step, so the tools at those +commits leave the variables as they find them. + +| Variable | Value when unset | +| --- | --- | +| `OMP_NUM_THREADS` | `os.process_cpu_count()` | +| `MKL_NUM_THREADS`, `BLIS_NUM_THREADS`, `VECLIB_MAXIMUM_THREADS` | `OMP_NUM_THREADS` if it names a count, otherwise `os.process_cpu_count()` | +| `OPENBLAS_NUM_THREADS` | `GOTO_NUM_THREADS` if it names a count, otherwise as above | +| `NUMEXPR_NUM_THREADS` | `OMP_NUM_THREADS` if it names a count, otherwise `NUMEXPR_MAX_THREADS` if that does, otherwise the online CPUs up to 16 | + +If `os.process_cpu_count()` returns nothing and `OMP_NUM_THREADS` names no +count, the commands set none of them. + +**These are the counts the libraries already use.** The step records the counts +and fixes them before the libraries load; it does not limit them. OpenMP and +BLAS have no upper limit here, unlike the release tool's limit of 16. They +follow CPU affinity but not a CPU quota, so outside Modal, where nothing sets +them from the quota, a container held to 2 CPUs by a quota can still start one +BLAS thread per visible CPU. The commands do not set `LOKY_MAX_CPU_COUNT`, +`POPULACE_FIT_N_JOBS` or `POPULACE_FIT_PREDICT_WORKERS`. With those unset, QRF +fitting and drawing use `joblib.cpu_count()`, which does follow a quota. The +release tool keeps its own settings: `min(os.cpu_count(), 16)` for +`OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `MKL_NUM_THREADS`, +`NUMEXPR_NUM_THREADS`, `VECLIB_MAXIMUM_THREADS` and `LOKY_MAX_CPU_COUNT`. + +**On Linux the BLAS thread count changes output bytes.** numpy's Linux wheels use +OpenBLAS, which splits a large dot product between its threads, so the order of +the additions, and with it the last bits of the sum, depends on the count. +Setting only `OMP_NUM_THREADS` has the same effect, because OpenBLAS follows it. +In Linux containers (x86-64 under emulation and arm64, 10 CPUs visible, numpy +2.4.6), `np.dot` and `@` on vectors of 20,000 to 500,000 rows gave different +results at 1, 2, 4, 8 and 10 threads, and `_project_weighted_sum_to_bounds` on +150,000 rows wrote different bytes at 1, 2 and 4 threads than at 10. These were +small synthetic checks, not full builds. The same checks on macOS, where numpy +uses Accelerate, showed no difference. The affected operations reach: + +- the ESI premium stage (`esi_premiums.py`), which scales a person column by a + weighted total; +- the PUF aggregate-record and source-AGI projections + (`_project_weighted_sum_to_bounds`), which write the projected amounts; +- cross-fitted calibration of the QRF sign classifier (`microcosm.fit.qrf`), + which uses `w @ ...` on row-length vectors. + +So a Linux build's output already depends on the host's thread count, and it +still does: two hosts with different counts can write different bytes. Keeping +each count as it was keeps a given host's output as it was. + +**The sign classifier can use more threads.** With `OMP_NUM_THREADS` unset, +scikit-learn uses physical cores; with it set, it uses that count. So on a host +with more logical CPUs than physical cores, `HistGradientBoostingClassifier` now +runs on all logical CPUs. Its probabilities were byte-identical at 1, 2 and 4 +OpenMP threads in the tests, which does not prove it for every input, and its +run time may change. + +**When a change takes effect.** + +- *Base, OpenMP and BLAS variables and `NUMEXPR_NUM_THREADS`:* recorded in + `stage_run_context.json` under `thread_environment` and compared on resume. A + different value, including one that comes from a host with a different CPU + count, is refused, so a new value needs a new checkpoint directory. +- *Base, `PYTHONHASHSEED`:* recorded and compared in the same way. +- *Base, `POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS`:* recorded and + not compared. A new value applies from the next outer stage of a resumed run. +- *Base runs started before this step:* they cannot resume after it. The run + configuration holds a digest that covers the tool's own file + (`builder_code_identity`), and the file changed. +- *Local-area command:* it keeps no run configuration, so the values apply to the + process that was started. + +**On Modal.** A plan may set `OMP_NUM_THREADS`, `MKL_NUM_THREADS`, +`OPENBLAS_NUM_THREADS`, `NUMEXPR_NUM_THREADS` and `BLIS_NUM_THREADS`. It may not +set `VECLIB_MAXIMUM_THREADS`, `GOTO_NUM_THREADS` or `NUMEXPR_MAX_THREADS`. In the +check-class container Modal set `OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, +`MKL_NUM_THREADS` and `BLIS_NUM_THREADS` to the class's CPU request; the commands +then give `VECLIB_MAXIMUM_THREADS` and `NUMEXPR_NUM_THREADS` the same count. No +record shows whether Modal does this in the `base` or `acs-staging` class. If it +does not, the count is `os.process_cpu_count()` in that container, and a resumed +base attempt on a host with a different count is refused. + ## Resources and cost The heavy and light classes are sized from the #974 measured peaks @@ -1163,7 +1251,8 @@ digests, settings, its code identity and the thread variables it sees) and refuses a resume whose config differs. Code newer than the pinned `4b57d15a2` that contains the QRF thread-count change records `POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS` without comparing -them. Every path in the config is the same in +them, and code that sets the OpenMP and BLAS variables itself compares the +counts it set (see "Thread variables"). Every path in the config is the same in every attempt of the run, and so are the image, the plan's environment and the class, so a relaunch of the same plan should resume. If Modal gave the new container different compared thread variables, the tool would refuse, @@ -1324,8 +1413,10 @@ python3 tools/modal_us_stage_plan.py compare-lineage "$RECEIPT" \ Two things are reported and never refused: the interpreter string (`python`) and every other `thread_environment` variable whose value differs (`thread_environment_differences`). The tool reads those variables -from its environment, Modal sets some of them itself (see "Resources"), and -whether they change the numbers has not been shown. The report says +from its environment, and Modal sets some of them itself (see "Resources"). A +difference in the BLAS or OpenMP counts can change output bytes on Linux (see +"Thread variables"), so a reported difference is not evidence that the outputs +agree. Only the checkpoint comparison below is. The report says `compared_outputs_match`, with `stages_compared` 2 of `stages_total` 24 and the 22 stages it did not compare (`stages_not_compared`). diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py b/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py new file mode 100644 index 0000000000..f1b0127dc0 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py @@ -0,0 +1,453 @@ +"""The thread settings the US base and local-area commands give themselves. + +The commands name the thread count each numerical library already uses, so +that it is recorded and is in place before the libraries load. On Linux the +OpenBLAS thread count changes the bytes of large dot products, so these tests +compare real library behaviour with and without the settings. + +Each process-level case starts a fresh interpreter: the settings depend on what +the process has loaded and must not reach the process that runs the tests. +""" + +from __future__ import annotations + +import functools +import importlib.util +import json +import os +import subprocess +import sys +from collections.abc import Mapping +from types import ModuleType + +import pytest + +from test_support.paths import paths_for + +REPOSITORY = paths_for("microcosm-build").repository +HELPER_PATH = REPOSITORY / "tools" / "us_build_thread_environment.py" +RELEASE_TOOL = "tools/build_us_fiscal_refresh_release.py" +BASE_TOOL = "tools/build_us_puf_support_base.py" +LOCAL_AREA_COMMAND = "tools/build_us_acs_multispine_base.py" +LOCAL_AREA_IMPLEMENTATION = "tools/_legacy/build_us_acs_multispine_base.py" +BUILD_COMMANDS = (BASE_TOOL, LOCAL_AREA_COMMAND, LOCAL_AREA_IMPLEMENTATION) + +OPENMP = "OMP_NUM_THREADS" +OPENBLAS = "OPENBLAS_NUM_THREADS" +OPENBLAS_FALLBACK = "GOTO_NUM_THREADS" +MKL = "MKL_NUM_THREADS" +BLIS = "BLIS_NUM_THREADS" +VECLIB = "VECLIB_MAXIMUM_THREADS" +NUMEXPR = "NUMEXPR_NUM_THREADS" +NUMEXPR_MAXIMUM = "NUMEXPR_MAX_THREADS" +JOBLIB_LIMIT = "LOKY_MAX_CPU_COUNT" +QRF_VARIABLES = ("POPULACE_FIT_N_JOBS", "POPULACE_FIT_PREDICT_WORKERS") +SET_BY_COMMANDS = (OPENMP, OPENBLAS, MKL, BLIS, VECLIB, NUMEXPR) +#: Every variable a process-level case clears before applying its own. +THREAD_VARIABLES = ( + *SET_BY_COMMANDS, + OPENBLAS_FALLBACK, + NUMEXPR_MAXIMUM, + JOBLIB_LIMIT, + *QRF_VARIABLES, +) + + +def _clean_environment(settings: Mapping[str, str] = {}) -> dict[str, str]: + environment = { + name: value + for name, value in os.environ.items() + if name not in THREAD_VARIABLES + } + environment.update(settings) + return environment + + +def _last_json_line(command: list[str], environment: dict[str, str]) -> dict: + completed = subprocess.run( + command, + cwd=REPOSITORY, + env=environment, + capture_output=True, + text=True, + check=False, + ) + assert completed.returncode == 0, completed.stderr[-4000:] + return json.loads(completed.stdout.strip().splitlines()[-1]) + + +# --------------------------------------------------------------------------- +# The values chosen +# --------------------------------------------------------------------------- + + +@pytest.fixture +def helper() -> ModuleType: + specification = importlib.util.spec_from_file_location( + "us_build_thread_environment_under_test", HELPER_PATH + ) + assert specification is not None and specification.loader is not None + module = importlib.util.module_from_spec(specification) + specification.loader.exec_module(module) + return module + + +def _defaults_for( + helper: ModuleType, + monkeypatch: pytest.MonkeyPatch, + settings: Mapping[str, str] = {}, + *, + usable_cpus: int | None = 6, + online_cpus: int | None = 6, +) -> dict[str, str]: + monkeypatch.setattr(helper.os, "process_cpu_count", lambda: usable_cpus) + monkeypatch.setattr(helper.os, "cpu_count", lambda: online_cpus) + environment = dict(settings) + helper.set_build_thread_environment(environment) + return environment + + +def _every_variable(count: str, **replacements: str) -> dict[str, str]: + return {**dict.fromkeys(SET_BY_COMMANDS, count), **replacements} + + +def test_unset_variables_take_the_usable_cpu_count( + helper: ModuleType, monkeypatch: pytest.MonkeyPatch +) -> None: + assert _defaults_for(helper, monkeypatch) == _every_variable("6") + + +def test_openmp_and_blas_counts_have_no_upper_limit( + helper: ModuleType, monkeypatch: pytest.MonkeyPatch +) -> None: + """numexpr alone limits itself to 16 threads when nothing configures it.""" + + environment = _defaults_for(helper, monkeypatch, usable_cpus=32, online_cpus=32) + + assert environment == _every_variable("32", **{NUMEXPR: "16"}) + + +def test_cpu_affinity_sets_the_count_and_numexpr_counts_online_cpus( + helper: ModuleType, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _defaults_for(helper, monkeypatch, usable_cpus=4, online_cpus=10) + + assert environment == _every_variable("4", **{NUMEXPR: "10"}) + + +@pytest.mark.parametrize( + ("configured", "expected"), + (("2", "2"), ("4,2", "4"), (" 3 ", "3"), ("007", "7")), +) +def test_an_openmp_count_already_set_is_used_for_the_others( + helper: ModuleType, + monkeypatch: pytest.MonkeyPatch, + configured: str, + expected: str, +) -> None: + environment = _defaults_for(helper, monkeypatch, {OPENMP: configured}) + + assert environment == _every_variable(expected, **{OPENMP: configured}) + + +@pytest.mark.parametrize("configured", ("", "0", "-1", "many", "٣")) +def test_an_openmp_value_without_a_count_is_kept_and_not_copied( + helper: ModuleType, monkeypatch: pytest.MonkeyPatch, configured: str +) -> None: + environment = _defaults_for(helper, monkeypatch, {OPENMP: configured}) + + assert environment == _every_variable("6", **{OPENMP: configured}) + + +def test_values_already_set_are_kept( + helper: ModuleType, monkeypatch: pytest.MonkeyPatch +) -> None: + settings = {name: str(index + 1) for index, name in enumerate(SET_BY_COMMANDS)} + + assert _defaults_for(helper, monkeypatch, settings) == settings + + +def test_openblas_follows_its_own_fallback_variable( + helper: ModuleType, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _defaults_for( + helper, monkeypatch, {OPENMP: "2", OPENBLAS_FALLBACK: "3"} + ) + + assert environment == { + **_every_variable("2", **{OPENBLAS: "3"}), + OPENBLAS_FALLBACK: "3", + } + + +@pytest.mark.parametrize( + ("settings", "expected"), + ( + ({NUMEXPR_MAXIMUM: "3"}, "3"), + ({NUMEXPR_MAXIMUM: "3", OPENMP: "2"}, "2"), + ), +) +def test_numexpr_follows_openmp_and_then_its_maximum( + helper: ModuleType, + monkeypatch: pytest.MonkeyPatch, + settings: dict[str, str], + expected: str, +) -> None: + environment = _defaults_for(helper, monkeypatch, settings) + + assert environment[NUMEXPR] == expected + + +def test_nothing_is_set_when_the_usable_cpus_are_unknown( + helper: ModuleType, monkeypatch: pytest.MonkeyPatch +) -> None: + assert _defaults_for(helper, monkeypatch, usable_cpus=None) == {} + + +def test_numexpr_uses_the_usable_count_when_online_cpus_are_unknown( + helper: ModuleType, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _defaults_for(helper, monkeypatch, usable_cpus=20, online_cpus=None) + + assert environment == _every_variable("20", **{NUMEXPR: "16"}) + + +def test_a_second_call_changes_nothing( + helper: ModuleType, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _defaults_for(helper, monkeypatch, usable_cpus=32, online_cpus=32) + first_result = dict(environment) + + helper.set_build_thread_environment(environment) + + assert environment == first_result + + +# --------------------------------------------------------------------------- +# When the commands apply them +# --------------------------------------------------------------------------- + +#: Starts one tool under ``runpy`` and stops it at its first import of a +#: numerical library, printing the environment at that moment. The tool's +#: imports never finish, so a case costs no more than the code before them. +_START_PROBE = """ +import json +import os +import runpy +import sys +from pathlib import Path + + +class ReachedNumericalLibrary(BaseException): + pass + + +class StopAtNumericalLibrary: + watched = {"joblib", "numexpr", "numpy", "pandas", "scipy", "sklearn", "torch"} + + def find_spec(self, name, path=None, target=None): + if name.partition(".")[0] in self.watched: + raise ReachedNumericalLibrary(name) + return None + + +tool = Path(sys.argv[1]).resolve() +run_name = sys.argv[2] +cpu_count = int(sys.argv[3]) +os.cpu_count = lambda: cpu_count +os.process_cpu_count = lambda: cpu_count +sys.path.insert(0, str(tool.parent)) +sys.argv = [str(tool), "--help"] +sys.meta_path.insert(0, StopAtNumericalLibrary()) +library = None +try: + runpy.run_path(str(tool), run_name=run_name) +except ReachedNumericalLibrary as reached: + library = str(reached) +print() +print(json.dumps({"library": library, "environment": dict(os.environ)})) +""" + + +def _state_at_first_numerical_import( + tool: str, + *, + run_name: str = "__main__", + cpu_count: int = 3, + settings: Mapping[str, str] = {}, +) -> dict: + state = _last_json_line( + [sys.executable, "-c", _START_PROBE, tool, run_name, str(cpu_count)], + _clean_environment(settings), + ) + assert state["library"] is not None + return state + + +@pytest.mark.parametrize("tool", BUILD_COMMANDS) +def test_a_started_command_sets_every_variable_before_numerical_imports( + tool: str, +) -> None: + environment = _state_at_first_numerical_import(tool)["environment"] + + assert {name: environment.get(name) for name in SET_BY_COMMANDS} == ( + _every_variable("3", **{NUMEXPR: "3"}) + ) + + +@pytest.mark.parametrize("tool", BUILD_COMMANDS) +def test_a_started_command_keeps_the_values_it_was_given(tool: str) -> None: + settings = {OPENMP: "2", OPENBLAS: "5"} + + environment = _state_at_first_numerical_import(tool, settings=settings)[ + "environment" + ] + + assert {name: environment.get(name) for name in SET_BY_COMMANDS} == ( + _every_variable("2", **{OPENBLAS: "5"}) + ) + + +@pytest.mark.parametrize("tool", BUILD_COMMANDS) +def test_importing_a_command_changes_no_thread_variable(tool: str) -> None: + """Tests and other tools import these files, often after numpy has loaded.""" + + environment = _state_at_first_numerical_import(tool, run_name="imported_tool")[ + "environment" + ] + + assert not set(THREAD_VARIABLES) & set(environment) + + +@pytest.mark.parametrize("tool", (*BUILD_COMMANDS, RELEASE_TOOL)) +def test_no_command_sets_the_qrf_or_joblib_limits_of_the_base_build( + tool: str, +) -> None: + environment = _state_at_first_numerical_import(tool)["environment"] + + assert not set(QRF_VARIABLES) & set(environment) + if tool != RELEASE_TOOL: + assert JOBLIB_LIMIT not in environment + + +@pytest.mark.parametrize(("cpu_count", "expected"), ((3, "3"), (32, "16"))) +def test_release_tool_keeps_its_existing_thread_values( + cpu_count: int, expected: str +) -> None: + environment = _state_at_first_numerical_import(RELEASE_TOOL, cpu_count=cpu_count)[ + "environment" + ] + + for name in (OPENMP, OPENBLAS, MKL, NUMEXPR, VECLIB, JOBLIB_LIMIT): + assert environment[name] == expected, name + assert BLIS not in environment + + +# --------------------------------------------------------------------------- +# What the libraries do with them +# --------------------------------------------------------------------------- + +#: Loads the libraries, with or without the commands' settings, and prints the +#: thread counts they chose and results of the BLAS operations whose bytes +#: depend on the OpenBLAS thread count on Linux. +_LIBRARY_PROBE = """ +import hashlib +import json +import sys + +sys.path.insert(0, "tools") +if sys.argv[1] == "with_settings": + from us_build_thread_environment import set_build_thread_environment + + set_build_thread_environment() + +import numexpr +import numpy as np +import sklearn.utils._openmp_helpers +import threadpoolctl + +generator = np.random.default_rng(0) +weights = generator.lognormal(7.0, 1.0, 150_000) +values = generator.lognormal(8.0, 1.5, 150_000) +probabilities = generator.dirichlet(np.ones(3), 150_000) +scaled_column = values * (9.6e11 / float(weights @ values)) +print() +print( + json.dumps( + { + "pools": sorted( + [pool["user_api"], pool["internal_api"], pool["num_threads"]] + for pool in threadpoolctl.threadpool_info() + ), + "numexpr_threads": numexpr.utils.get_num_threads(), + "dot_product": float(np.dot(weights, values)).hex(), + "scaled_column": hashlib.sha256(scaled_column.tobytes()).hexdigest(), + "weighted_probabilities": hashlib.sha256( + (weights @ probabilities).tobytes() + ).hexdigest(), + } + ) +) +""" + +_SIGN_CLASSIFIER_PROBE = """ +import hashlib +import json + +import numpy as np + +from microcosm.fit.qrf import _make_gate + +generator = np.random.default_rng(0) +features = generator.lognormal(0.0, 1.5, size=(30_000, 6)) +latent = features[:, 0] * generator.lognormal(0.0, 1.0, 30_000) - features[:, 1] +labels = np.sign(np.where(np.abs(latent) < 0.3, 0.0, latent)).astype(int) +weights = generator.lognormal(0.0, 2.0, 30_000) +classifier = _make_gate(1).fit(features, labels, sample_weight=weights) +probabilities = classifier.predict_proba(features[:10_000]) +print() +print(json.dumps({"digest": hashlib.sha256(probabilities.tobytes()).hexdigest()})) +""" + + +@functools.cache +def _library_results( + mode: str, settings: tuple[tuple[str, str], ...] +) -> dict[str, object]: + return _last_json_line( + [sys.executable, "-c", _LIBRARY_PROBE, mode], + _clean_environment(dict(settings)), + ) + + +@pytest.mark.parametrize( + "settings", + ( + (), + ((OPENMP, "2"),), + ((OPENBLAS_FALLBACK, "2"),), + ((NUMEXPR_MAXIMUM, "3"),), + ((NUMEXPR_MAXIMUM, "3"), (OPENMP, "2")), + ), + ids=("nothing", "openmp", "openblas_fallback", "numexpr_maximum", "both"), +) +def test_the_settings_keep_thread_counts_and_result_bytes( + settings: tuple[tuple[str, str], ...], +) -> None: + assert _library_results("with_settings", settings) == _library_results( + "without_settings", settings + ) + + +def test_sign_classifier_probabilities_do_not_depend_on_the_openmp_count() -> None: + """scikit-learn may move from physical to logical CPUs under the settings.""" + + digests = { + thread_count: _last_json_line( + [sys.executable, "-c", _SIGN_CLASSIFIER_PROBE], + _clean_environment({OPENMP: thread_count, OPENBLAS: "1"}), + )["digest"] + for thread_count in ("1", "2", "4") + } + + assert len(set(digests.values())) == 1, digests diff --git a/pyproject.toml b/pyproject.toml index d6dcdd8aa6..b600104d3a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,6 +43,11 @@ ignore = ["E501"] # defaults before numpy/torch load, which requires statements above the # import block. "tools/build_us_fiscal_refresh_release.py" = ["E402"] +# The base and local-area commands set their thread variables before numpy +# loads (tools/us_build_thread_environment.py), for the same reason. +"tools/build_us_puf_support_base.py" = ["E402"] +"tools/build_us_acs_multispine_base.py" = ["E402"] +"tools/_legacy/build_us_acs_multispine_base.py" = ["E402"] # Evidence scripts are frozen receipts of one-off measurements: formatted and # import-sorted, but their logic stays exactly as it produced the committed # outputs, so style rules that would edit that logic are waived. diff --git a/tools/_legacy/build_us_acs_multispine_base.py b/tools/_legacy/build_us_acs_multispine_base.py index fd5e394855..6818bcaed2 100644 --- a/tools/_legacy/build_us_acs_multispine_base.py +++ b/tools/_legacy/build_us_acs_multispine_base.py @@ -28,6 +28,20 @@ from __future__ import annotations +import sys +from pathlib import Path + +if __name__ == "__main__": + # The same start-up step as tools/build_us_acs_multispine_base.py, for a + # direct run of this file: it comes before numpy loads and does not run on + # import. The helper is in tools/, which a direct run does not have on its + # path. E402 is ignored for this file in pyproject for this block. + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + from us_build_thread_environment import set_build_thread_environment + + del sys.path[0] + set_build_thread_environment() + import argparse import gc import hashlib @@ -35,7 +49,6 @@ import os from collections.abc import Mapping from dataclasses import replace -from pathlib import Path from typing import Any import numpy as np diff --git a/tools/build_us_acs_multispine_base.py b/tools/build_us_acs_multispine_base.py index 3f206e8966..3394c755d1 100644 --- a/tools/build_us_acs_multispine_base.py +++ b/tools/build_us_acs_multispine_base.py @@ -8,6 +8,15 @@ from __future__ import annotations +if __name__ == "__main__": + # OpenBLAS and OpenMP read these variables when they load, and the imports + # below load numpy before the implementation file does. This runs only for + # the command: tests and other tools import this file. E402 is ignored for + # this file in pyproject for this block. + from us_build_thread_environment import set_build_thread_environment + + set_build_thread_environment() + import importlib.util import sys import warnings diff --git a/tools/build_us_puf_support_base.py b/tools/build_us_puf_support_base.py index 19eea90a22..e158ade410 100644 --- a/tools/build_us_puf_support_base.py +++ b/tools/build_us_puf_support_base.py @@ -18,6 +18,16 @@ from __future__ import annotations +if __name__ == "__main__": + # OpenBLAS and OpenMP read these variables when they load, so this comes + # before numpy. It runs only for the command: tests and other tools import + # this file. Stage subprocesses inherit the values, and the run + # configuration records them (``_stage_run_config``). E402 is ignored for + # this file in pyproject for this block. + from us_build_thread_environment import set_build_thread_environment + + set_build_thread_environment() + import argparse import hashlib import json @@ -1262,7 +1272,10 @@ def _pooled_income_years(args: argparse.Namespace) -> tuple[int, ...]: #: QRF thread counts the first run records and a resume does not compare: they #: change no imputed value. The BLAS and OpenMP thread counts and -#: PYTHONHASHSEED in ``thread_environment`` stay compared. +#: PYTHONHASHSEED in ``thread_environment`` stay compared: on Linux the OpenBLAS +#: count changes output bytes, and the command fills those variables in from +#: the host (``us_build_thread_environment``), so a resume on a host with a +#: different CPU count is refused. _RESUME_IGNORED_RUN_CONFIG_PATHS = ( ("thread_environment", "POPULACE_FIT_N_JOBS"), ("thread_environment", "POPULACE_FIT_PREDICT_WORKERS"), diff --git a/tools/us_build_thread_environment.py b/tools/us_build_thread_environment.py new file mode 100644 index 0000000000..109eeecedf --- /dev/null +++ b/tools/us_build_thread_environment.py @@ -0,0 +1,86 @@ +"""Name the thread counts of the US base and local-area build commands. + +The commands call :func:`set_build_thread_environment` before numpy loads, so +this module uses only the standard library. Each variable gets the count its +library already uses when the variable is unset, for two reasons: + +- On Linux the OpenBLAS thread count changes output bytes. OpenBLAS splits a + large dot product between its threads, and the order of the additions moves + the last bits of the sum. Keeping the count keeps the bytes. +- The base command records these variables in its run configuration and refuses + a resume with different values, which it can only do once they have values. + +So this limits nothing. OpenMP and BLAS counts have no upper limit, and they +follow CPU affinity but not a CPU quota. The one thread count that can change +is scikit-learn's: with ``OMP_NUM_THREADS`` unset it uses physical cores, and +with it set it uses that count. +""" + +from __future__ import annotations + +import os +from collections.abc import MutableMapping + +#: The most threads numexpr starts when nothing configures it. +NUMEXPR_UNCONFIGURED_THREAD_LIMIT = 16 + +__all__ = ["NUMEXPR_UNCONFIGURED_THREAD_LIMIT", "set_build_thread_environment"] + + +def _configured_count(value: str | None) -> str | None: + """The thread count a setting names, or None when it names none. + + OpenMP allows a comma-separated list, one count per nesting level, and + OpenBLAS reads the leading number. A value without a positive count leaves + these libraries on their own default. + """ + + if value is None: + return None + first = value.split(",", 1)[0].strip() + if not (first.isascii() and first.isdigit()) or int(first) < 1: + return None + return str(int(first)) + + +def set_build_thread_environment( + environment: MutableMapping[str, str] = os.environ, +) -> None: + """Give each unset OpenMP, BLAS and numexpr variable its current count. + + The count is ``OMP_NUM_THREADS`` when that names one, otherwise the CPUs + this process may use. Two variables have other sources, because their + libraries do: + + - OpenBLAS reads ``GOTO_NUM_THREADS`` before ``OMP_NUM_THREADS``. + - numexpr uses ``OMP_NUM_THREADS``, then ``NUMEXPR_MAX_THREADS``, and with + neither it counts the online CPUs, up to 16. It needs its own value here + because the ``OMP_NUM_THREADS`` set below would otherwise replace the + last two. + + A value already present is kept. When the usable CPUs are unknown nothing + is set, and each library keeps its own default. + """ + + openmp_count = _configured_count(environment.get("OMP_NUM_THREADS")) + usable_cpus = os.process_cpu_count() + if openmp_count is not None: + count = openmp_count + elif usable_cpus is not None: + count = str(usable_cpus) + else: + return + online_cpus = os.cpu_count() or int(count) + defaults = { + "OMP_NUM_THREADS": count, + "OPENBLAS_NUM_THREADS": _configured_count(environment.get("GOTO_NUM_THREADS")) + or count, + "MKL_NUM_THREADS": count, + "BLIS_NUM_THREADS": count, + "VECLIB_MAXIMUM_THREADS": count, + "NUMEXPR_NUM_THREADS": openmp_count + or _configured_count(environment.get("NUMEXPR_MAX_THREADS")) + or str(min(online_cpus, NUMEXPR_UNCONFIGURED_THREAD_LIMIT)), + } + for name, value in defaults.items(): + environment.setdefault(name, value) From d8570b3b4d4f21da8f7b94c7fbc7e657126e1366 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:23:13 +0400 Subject: [PATCH 02/10] Leave unusual thread values to their libraries Copy OMP_NUM_THREADS, GOTO_NUM_THREADS and NUMEXPR_MAX_THREADS only when each is a plain positive integer. OpenBLAS and numexpr read other spellings differently, so a copied value could change their thread counts. Correct the runbook and changelog from review: name the ACS multispine staging command, cite the recorded Modal base environment, and state that setting OMP_NUM_THREADS changes scikit-learn's and torch's thread counts. Co-Authored-By: Claude Opus 5.5 --- .../us-build-thread-environment.changed.md | 4 +- docs/us-modal-stage-runbook.md | 106 ++++++++++-------- .../us/test_us_build_tool_thread_defaults.py | 56 +++++++-- pyproject.toml | 2 +- tools/us_build_thread_environment.py | 85 +++++++------- 5 files changed, 155 insertions(+), 98 deletions(-) diff --git a/changelog.d/us-build-thread-environment.changed.md b/changelog.d/us-build-thread-environment.changed.md index 03957dc843..d0d34613e6 100644 --- a/changelog.d/us-build-thread-environment.changed.md +++ b/changelog.d/us-build-thread-environment.changed.md @@ -1,3 +1,3 @@ -The US base and local-area build commands now set their OpenMP, BLAS and numexpr thread variables before numpy loads, each to the count its library already uses: `OMP_NUM_THREADS` if it names a count, otherwise `os.process_cpu_count()`, with no upper limit. numexpr keeps its own rule. Values already set are kept, and importing the tools changes nothing. +The US base and ACS multispine staging commands now set their OpenMP, BLAS and numexpr thread variables before numpy loads. Each BLAS and numexpr variable gets the count its library already uses: `OMP_NUM_THREADS` if it is a plain count, otherwise `os.process_cpu_count()`, with no upper limit, and numexpr keeps its own rule. Values already set are kept, and importing the tools changes nothing. -On Linux the OpenBLAS thread count changes output bytes, so a build's output already depends on the host's count. This change keeps each count, so it keeps a host's output, but the base command now records real counts in `thread_environment` and refuses a resume on a host with a different count. On hosts with more logical CPUs than physical cores, scikit-learn's sign classifier now uses all logical CPUs. OpenMP and BLAS still do not follow a CPU quota outside Modal. +On Linux the OpenBLAS thread count changes output bytes, so a build's output already depends on the host's count. This change keeps that count, so it keeps a host's output, and the base command now records real counts in `thread_environment` and refuses a resume with different ones. OpenMP and BLAS still do not follow a CPU quota. Because `OMP_NUM_THREADS` is now set, scikit-learn's sign classifier and torch use that count instead of their own defaults, which for scikit-learn means it no longer follows a CPU quota or `LOKY_MAX_CPU_COUNT`. diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index 9cc4772328..9ed1227340 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -397,36 +397,42 @@ that release's current build. ## Thread variables -The base command (`tools/build_us_puf_support_base.py`) and the local-area -command (`tools/build_us_acs_multispine_base.py`, and +The base command (`tools/build_us_puf_support_base.py`) and the ACS multispine +staging command (`tools/build_us_acs_multispine_base.py`, and `tools/_legacy/build_us_acs_multispine_base.py` when that file is run directly) set their OpenMP, BLAS and numexpr thread variables before numpy loads (`tools/us_build_thread_environment.py`). They do this only when started as commands, not when imported. A value already in the environment, from an -operator, a plan or Modal, is kept. The commits pinned by the base and -local-area plans in this runbook predate this step, so the tools at those -commits leave the variables as they find them. +operator, a plan or Modal, is kept. `tools/build_us_acs_local_release.py`, which +builds the local-area release from the staging output, does not run this step. + +The tools at `4b57d15a2` and `74f5e6123`, the commits pinned by the historical +base plan and the ACS staging plan, predate this step and leave the variables as +they find them. A plan made from the default-pool template runs the step once +its commit contains it. | Variable | Value when unset | | --- | --- | | `OMP_NUM_THREADS` | `os.process_cpu_count()` | -| `MKL_NUM_THREADS`, `BLIS_NUM_THREADS`, `VECLIB_MAXIMUM_THREADS` | `OMP_NUM_THREADS` if it names a count, otherwise `os.process_cpu_count()` | -| `OPENBLAS_NUM_THREADS` | `GOTO_NUM_THREADS` if it names a count, otherwise as above | -| `NUMEXPR_NUM_THREADS` | `OMP_NUM_THREADS` if it names a count, otherwise `NUMEXPR_MAX_THREADS` if that does, otherwise the online CPUs up to 16 | - -If `os.process_cpu_count()` returns nothing and `OMP_NUM_THREADS` names no -count, the commands set none of them. - -**These are the counts the libraries already use.** The step records the counts -and fixes them before the libraries load; it does not limit them. OpenMP and -BLAS have no upper limit here, unlike the release tool's limit of 16. They -follow CPU affinity but not a CPU quota, so outside Modal, where nothing sets -them from the quota, a container held to 2 CPUs by a quota can still start one -BLAS thread per visible CPU. The commands do not set `LOKY_MAX_CPU_COUNT`, -`POPULACE_FIT_N_JOBS` or `POPULACE_FIT_PREDICT_WORKERS`. With those unset, QRF -fitting and drawing use `joblib.cpu_count()`, which does follow a quota. The -release tool keeps its own settings: `min(os.cpu_count(), 16)` for -`OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `MKL_NUM_THREADS`, +| `MKL_NUM_THREADS`, `BLIS_NUM_THREADS`, `VECLIB_MAXIMUM_THREADS` | `OMP_NUM_THREADS` if it is a plain count, otherwise `os.process_cpu_count()` | +| `OPENBLAS_NUM_THREADS` | `GOTO_NUM_THREADS` if it is a plain count, otherwise as above | +| `NUMEXPR_NUM_THREADS` | `OMP_NUM_THREADS` if it is a plain count, otherwise `NUMEXPR_MAX_THREADS` if that is, otherwise the online CPUs up to 16 | + +A plain count is a positive decimal integer. Libraries read other spellings, such +as `+4` or `4,2`, in different ways, so the commands do not copy them: the +variables that would copy the value stay unset, and each library reads the +original as it does without this step. `VECLIB_MAXIMUM_THREADS` then takes +`os.process_cpu_count()`. A variable whose count is unknown stays unset. + +**BLAS and numexpr keep their counts.** The step names the counts these libraries +already use and does not limit them. OpenMP and BLAS have no upper limit here, +unlike the release tool's limit of 16. They follow CPU affinity but not a CPU +quota, so outside Modal a container held to 2 CPUs by a quota starts one BLAS +thread per visible CPU, with or without this step. The commands do not set +`LOKY_MAX_CPU_COUNT`, `POPULACE_FIT_N_JOBS` or `POPULACE_FIT_PREDICT_WORKERS`. +With those unset, QRF fitting and drawing use `joblib.cpu_count()`, which does +follow a quota. The release tool keeps its own settings: `min(os.cpu_count(), 16)` +for `OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `MKL_NUM_THREADS`, `NUMEXPR_NUM_THREADS`, `VECLIB_MAXIMUM_THREADS` and `LOKY_MAX_CPU_COUNT`. **On Linux the BLAS thread count changes output bytes.** numpy's Linux wheels use @@ -438,7 +444,8 @@ In Linux containers (x86-64 under emulation and arm64, 10 CPUs visible, numpy results at 1, 2, 4, 8 and 10 threads, and `_project_weighted_sum_to_bounds` on 150,000 rows wrote different bytes at 1, 2 and 4 threads than at 10. These were small synthetic checks, not full builds. The same checks on macOS, where numpy -uses Accelerate, showed no difference. The affected operations reach: +uses Accelerate, showed no difference. The affected operations reach, for +example: - the ESI premium stage (`esi_premiums.py`), which scales a person column by a weighted total; @@ -448,15 +455,22 @@ uses Accelerate, showed no difference. The affected operations reach: which uses `w @ ...` on row-length vectors. So a Linux build's output already depends on the host's thread count, and it -still does: two hosts with different counts can write different bytes. Keeping -each count as it was keeps a given host's output as it was. - -**The sign classifier can use more threads.** With `OMP_NUM_THREADS` unset, -scikit-learn uses physical cores; with it set, it uses that count. So on a host -with more logical CPUs than physical cores, `HistGradientBoostingClassifier` now -runs on all logical CPUs. Its probabilities were byte-identical at 1, 2 and 4 -OpenMP threads in the tests, which does not prove it for every input, and its -run time may change. +still does: two hosts with different counts can write different bytes. With and +without this step, one x86-64 container gave the same OpenBLAS, OpenMP and numexpr +counts and the same result bytes, with no CPU limit, under a 2-CPU quota and +under a 4-CPU affinity limit. + +**Setting `OMP_NUM_THREADS` changes two other counts.** With the variable unset, +scikit-learn uses `joblib.cpu_count(only_physical_cores=True)` at most, which +follows a CPU quota and `LOKY_MAX_CPU_COUNT`. With it set, scikit-learn uses that +value. So when nothing else has set the variable, the QRF sign classifier +(`HistGradientBoostingClassifier`) can run on all logical CPUs where it would +have used physical cores, and under a quota it starts one thread per visible CPU: +2 threads became 10 in a 2-CPU container. Its probabilities were byte-identical +at 1, 2 and 4 OpenMP threads in the tests, which does not prove it for every +input, and its run time may change, particularly under a quota. torch follows the +variable too (`torch.get_num_threads()`); neither command runs a torch +calculation that review found. **When a change takes effect.** @@ -470,18 +484,20 @@ run time may change. - *Base runs started before this step:* they cannot resume after it. The run configuration holds a digest that covers the tool's own file (`builder_code_identity`), and the file changed. -- *Local-area command:* it keeps no run configuration, so the values apply to the - process that was started. +- *ACS multispine staging command:* it keeps no run configuration, so the values + apply to the process that was started. **On Modal.** A plan may set `OMP_NUM_THREADS`, `MKL_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `NUMEXPR_NUM_THREADS` and `BLIS_NUM_THREADS`. It may not -set `VECLIB_MAXIMUM_THREADS`, `GOTO_NUM_THREADS` or `NUMEXPR_MAX_THREADS`. In the -check-class container Modal set `OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, -`MKL_NUM_THREADS` and `BLIS_NUM_THREADS` to the class's CPU request; the commands -then give `VECLIB_MAXIMUM_THREADS` and `NUMEXPR_NUM_THREADS` the same count. No -record shows whether Modal does this in the `base` or `acs-staging` class. If it -does not, the count is `os.process_cpu_count()` in that container, and a resumed -base attempt on a host with a different count is refused. +set `VECLIB_MAXIMUM_THREADS`, `GOTO_NUM_THREADS` or `NUMEXPR_MAX_THREADS`. Modal +set `OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `MKL_NUM_THREADS` and +`BLIS_NUM_THREADS` to the class's CPU request in the check class (2) and in a +`base` run at `4b57d15a2` (4; +`docs/evidence/us-release-reimputation-1191/receipts/build_environment.base_0fb05b67.release_417d23ae.json`). +With those set, the commands give `VECLIB_MAXIMUM_THREADS` and +`NUMEXPR_NUM_THREADS` the same count, so the attempts of a base run record the +same values on any host. No record shows what Modal sets in the `acs-staging` +class. ## Resources and cost @@ -1413,10 +1429,10 @@ python3 tools/modal_us_stage_plan.py compare-lineage "$RECEIPT" \ Two things are reported and never refused: the interpreter string (`python`) and every other `thread_environment` variable whose value differs (`thread_environment_differences`). The tool reads those variables -from its environment, and Modal sets some of them itself (see "Resources"). A -difference in the BLAS or OpenMP counts can change output bytes on Linux (see -"Thread variables"), so a reported difference is not evidence that the outputs -agree. Only the checkpoint comparison below is. The report says +from its environment, and Modal sets some of them itself (see "Resources"). +These differences are reported and not refused, although a different BLAS or +OpenMP count can change output bytes on Linux (see "Thread variables"). Only the +checkpoint digests compared above show that outputs agree. The report says `compared_outputs_match`, with `stages_compared` 2 of `stages_total` 24 and the 22 stages it did not compare (`stages_not_compared`). diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py b/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py index f1b0127dc0..a5c57c2cd2 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py @@ -1,4 +1,4 @@ -"""The thread settings the US base and local-area commands give themselves. +"""The thread settings the US base and ACS staging commands give themselves. The commands name the thread count each numerical library already uses, so that it is recorded and is in place before the libraries load. On Linux the @@ -28,9 +28,9 @@ HELPER_PATH = REPOSITORY / "tools" / "us_build_thread_environment.py" RELEASE_TOOL = "tools/build_us_fiscal_refresh_release.py" BASE_TOOL = "tools/build_us_puf_support_base.py" -LOCAL_AREA_COMMAND = "tools/build_us_acs_multispine_base.py" -LOCAL_AREA_IMPLEMENTATION = "tools/_legacy/build_us_acs_multispine_base.py" -BUILD_COMMANDS = (BASE_TOOL, LOCAL_AREA_COMMAND, LOCAL_AREA_IMPLEMENTATION) +ACS_STAGING_COMMAND = "tools/build_us_acs_multispine_base.py" +ACS_STAGING_IMPLEMENTATION = "tools/_legacy/build_us_acs_multispine_base.py" +BUILD_COMMANDS = (BASE_TOOL, ACS_STAGING_COMMAND, ACS_STAGING_IMPLEMENTATION) OPENMP = "OMP_NUM_THREADS" OPENBLAS = "OPENBLAS_NUM_THREADS" @@ -137,7 +137,7 @@ def test_cpu_affinity_sets_the_count_and_numexpr_counts_online_cpus( @pytest.mark.parametrize( ("configured", "expected"), - (("2", "2"), ("4,2", "4"), (" 3 ", "3"), ("007", "7")), + (("2", "2"), ("007", "7")), ) def test_an_openmp_count_already_set_is_used_for_the_others( helper: ModuleType, @@ -150,13 +150,39 @@ def test_an_openmp_count_already_set_is_used_for_the_others( assert environment == _every_variable(expected, **{OPENMP: configured}) -@pytest.mark.parametrize("configured", ("", "0", "-1", "many", "٣")) -def test_an_openmp_value_without_a_count_is_kept_and_not_copied( +def test_a_blank_openmp_value_counts_as_unset( + helper: ModuleType, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _defaults_for(helper, monkeypatch, {OPENMP: ""}) + + assert environment == _every_variable("6", **{OPENMP: ""}) + + +@pytest.mark.parametrize("configured", ("+4", "4,2", " 3 ", "0", "-1", "many", "٣")) +def test_libraries_read_an_unusual_openmp_value_themselves( helper: ModuleType, monkeypatch: pytest.MonkeyPatch, configured: str ) -> None: + """OpenBLAS and numexpr parse these differently, so neither gets a copy.""" + environment = _defaults_for(helper, monkeypatch, {OPENMP: configured}) - assert environment == _every_variable("6", **{OPENMP: configured}) + assert environment == {OPENMP: configured, VECLIB: "6"} + + +@pytest.mark.parametrize( + ("source", "left_unset"), + ((OPENBLAS_FALLBACK, OPENBLAS), (NUMEXPR_MAXIMUM, NUMEXPR)), +) +def test_libraries_read_their_own_unusual_values_themselves( + helper: ModuleType, + monkeypatch: pytest.MonkeyPatch, + source: str, + left_unset: str, +) -> None: + environment = _defaults_for(helper, monkeypatch, {source: "+3"}) + + assert left_unset not in environment + assert environment[MKL] == "6" def test_values_already_set_are_kept( @@ -201,7 +227,9 @@ def test_numexpr_follows_openmp_and_then_its_maximum( def test_nothing_is_set_when_the_usable_cpus_are_unknown( helper: ModuleType, monkeypatch: pytest.MonkeyPatch ) -> None: - assert _defaults_for(helper, monkeypatch, usable_cpus=None) == {} + environment = _defaults_for(helper, monkeypatch, usable_cpus=None, online_cpus=None) + + assert environment == {} def test_numexpr_uses_the_usable_count_when_online_cpus_are_unknown( @@ -425,11 +453,19 @@ def _library_results( ( (), ((OPENMP, "2"),), + ((OPENMP, "+4"),), ((OPENBLAS_FALLBACK, "2"),), ((NUMEXPR_MAXIMUM, "3"),), ((NUMEXPR_MAXIMUM, "3"), (OPENMP, "2")), ), - ids=("nothing", "openmp", "openblas_fallback", "numexpr_maximum", "both"), + ids=( + "nothing", + "openmp", + "openmp_with_sign", + "openblas_fallback", + "numexpr_maximum", + "both", + ), ) def test_the_settings_keep_thread_counts_and_result_bytes( settings: tuple[tuple[str, str], ...], diff --git a/pyproject.toml b/pyproject.toml index b600104d3a..413c95c6d9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,7 +43,7 @@ ignore = ["E501"] # defaults before numpy/torch load, which requires statements above the # import block. "tools/build_us_fiscal_refresh_release.py" = ["E402"] -# The base and local-area commands set their thread variables before numpy +# The base and ACS staging commands set their thread variables before numpy # loads (tools/us_build_thread_environment.py), for the same reason. "tools/build_us_puf_support_base.py" = ["E402"] "tools/build_us_acs_multispine_base.py" = ["E402"] diff --git a/tools/us_build_thread_environment.py b/tools/us_build_thread_environment.py index 109eeecedf..f205862ede 100644 --- a/tools/us_build_thread_environment.py +++ b/tools/us_build_thread_environment.py @@ -1,19 +1,20 @@ -"""Name the thread counts of the US base and local-area build commands. +"""Name the thread counts of the US base and ACS staging build commands. The commands call :func:`set_build_thread_environment` before numpy loads, so -this module uses only the standard library. Each variable gets the count its -library already uses when the variable is unset, for two reasons: +this module uses only the standard library. Each BLAS and numexpr variable gets +the count its library already uses when the variable is unset: - On Linux the OpenBLAS thread count changes output bytes. OpenBLAS splits a large dot product between its threads, and the order of the additions moves the last bits of the sum. Keeping the count keeps the bytes. -- The base command records these variables in its run configuration and refuses - a resume with different values, which it can only do once they have values. - -So this limits nothing. OpenMP and BLAS counts have no upper limit, and they -follow CPU affinity but not a CPU quota. The one thread count that can change -is scikit-learn's: with ``OMP_NUM_THREADS`` unset it uses physical cores, and -with it set it uses that count. +- The base command records these variables in its run configuration and compares + them on resume. With real counts recorded, it refuses a resume on a host with a + different count, which two unset values could not show. + +This limits nothing: the counts have no upper limit, and OpenMP and BLAS follow +CPU affinity but not a CPU quota. Setting ``OMP_NUM_THREADS`` does change two +other counts. scikit-learn then uses that value instead of its physical-core +count limited by a CPU quota and ``LOKY_MAX_CPU_COUNT``, and torch uses it too. """ from __future__ import annotations @@ -27,20 +28,20 @@ __all__ = ["NUMEXPR_UNCONFIGURED_THREAD_LIMIT", "set_build_thread_environment"] -def _configured_count(value: str | None) -> str | None: - """The thread count a setting names, or None when it names none. +def _count_or_default(setting: str | None, default: str | None) -> str | None: + """The count to copy from ``setting``, or ``default`` if it is unset or blank. - OpenMP allows a comma-separated list, one count per nesting level, and - OpenBLAS reads the leading number. A value without a positive count leaves - these libraries on their own default. + Only a plain positive integer is copied. Libraries read other spellings + differently (OpenBLAS takes ``4`` from ``4,2`` and numexpr refuses it), so + for those this returns None and the variable that would copy the value stays + unset, leaving each library to read ``setting`` as it does today. """ - if value is None: - return None - first = value.split(",", 1)[0].strip() - if not (first.isascii() and first.isdigit()) or int(first) < 1: - return None - return str(int(first)) + if not setting: + return default + if setting.isascii() and setting.isdigit() and int(setting) > 0: + return str(int(setting)) + return None def set_build_thread_environment( @@ -48,8 +49,8 @@ def set_build_thread_environment( ) -> None: """Give each unset OpenMP, BLAS and numexpr variable its current count. - The count is ``OMP_NUM_THREADS`` when that names one, otherwise the CPUs - this process may use. Two variables have other sources, because their + The count is ``OMP_NUM_THREADS`` when that is a plain count, otherwise the + CPUs this process may use. Two variables have other sources, because their libraries do: - OpenBLAS reads ``GOTO_NUM_THREADS`` before ``OMP_NUM_THREADS``. @@ -58,29 +59,33 @@ def set_build_thread_environment( because the ``OMP_NUM_THREADS`` set below would otherwise replace the last two. - A value already present is kept. When the usable CPUs are unknown nothing - is set, and each library keeps its own default. + A value already present is kept. A variable with no known count stays unset, + and its library keeps its own default. """ - openmp_count = _configured_count(environment.get("OMP_NUM_THREADS")) usable_cpus = os.process_cpu_count() - if openmp_count is not None: - count = openmp_count - elif usable_cpus is not None: - count = str(usable_cpus) - else: - return - online_cpus = os.cpu_count() or int(count) + usable_count = None if usable_cpus is None else str(usable_cpus) + openmp_setting = environment.get("OMP_NUM_THREADS") + count = _count_or_default(openmp_setting, usable_count) + online_cpus = os.cpu_count() or usable_cpus + numexpr_default = ( + None + if online_cpus is None + else str(min(online_cpus, NUMEXPR_UNCONFIGURED_THREAD_LIMIT)) + ) defaults = { "OMP_NUM_THREADS": count, - "OPENBLAS_NUM_THREADS": _configured_count(environment.get("GOTO_NUM_THREADS")) - or count, + "OPENBLAS_NUM_THREADS": _count_or_default( + environment.get("GOTO_NUM_THREADS"), count + ), "MKL_NUM_THREADS": count, "BLIS_NUM_THREADS": count, - "VECLIB_MAXIMUM_THREADS": count, - "NUMEXPR_NUM_THREADS": openmp_count - or _configured_count(environment.get("NUMEXPR_MAX_THREADS")) - or str(min(online_cpus, NUMEXPR_UNCONFIGURED_THREAD_LIMIT)), + "VECLIB_MAXIMUM_THREADS": count or usable_count, + "NUMEXPR_NUM_THREADS": _count_or_default( + openmp_setting, + _count_or_default(environment.get("NUMEXPR_MAX_THREADS"), numexpr_default), + ), } for name, value in defaults.items(): - environment.setdefault(name, value) + if value is not None: + environment.setdefault(name, value) From 86b39fec66dd15b4965d02944ea738d3778d80a9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:35:17 +0400 Subject: [PATCH 03/10] Test one thread setting for the US build commands MICROCOSM_THREADS, when set, fills every OpenMP, BLAS, numexpr and joblib thread variable that is unset; without it the base and ACS staging commands set nothing and the release tool keeps min(os.cpu_count(), 16). The base command's resume check compares the setting and the BLAS thread count in use. These tests fail until the change that follows. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_build_tool_thread_defaults.py | 397 ++++++++---------- .../us/test_us_puf_support_base_builder.py | 39 +- 2 files changed, 217 insertions(+), 219 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py b/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py index a5c57c2cd2..70d862be56 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py @@ -1,9 +1,9 @@ -"""The thread settings the US base and ACS staging commands give themselves. +"""The one thread setting of the US build commands, ``MICROCOSM_THREADS``. -The commands name the thread count each numerical library already uses, so -that it is recorded and is in place before the libraries load. On Linux the -OpenBLAS thread count changes the bytes of large dot products, so these tests -compare real library behaviour with and without the settings. +When it is set, the release, base and ACS staging commands copy it into every +library's thread variable before numpy loads. When it is not, the base and ACS +staging commands set nothing, so each library keeps choosing its own count, +and the release tool keeps its default of ``min(os.cpu_count(), 16)``. Each process-level case starts a fresh interpreter: the settings depend on what the process has loaded and must not reach the process that runs the tests. @@ -11,7 +11,6 @@ from __future__ import annotations -import functools import importlib.util import json import os @@ -31,24 +30,24 @@ ACS_STAGING_COMMAND = "tools/build_us_acs_multispine_base.py" ACS_STAGING_IMPLEMENTATION = "tools/_legacy/build_us_acs_multispine_base.py" BUILD_COMMANDS = (BASE_TOOL, ACS_STAGING_COMMAND, ACS_STAGING_IMPLEMENTATION) +EVERY_COMMAND = (*BUILD_COMMANDS, RELEASE_TOOL) +THREAD_SETTING = "MICROCOSM_THREADS" OPENMP = "OMP_NUM_THREADS" OPENBLAS = "OPENBLAS_NUM_THREADS" -OPENBLAS_FALLBACK = "GOTO_NUM_THREADS" MKL = "MKL_NUM_THREADS" BLIS = "BLIS_NUM_THREADS" VECLIB = "VECLIB_MAXIMUM_THREADS" NUMEXPR = "NUMEXPR_NUM_THREADS" -NUMEXPR_MAXIMUM = "NUMEXPR_MAX_THREADS" JOBLIB_LIMIT = "LOKY_MAX_CPU_COUNT" +FILLED_VARIABLES = (OPENMP, OPENBLAS, MKL, BLIS, VECLIB, NUMEXPR, JOBLIB_LIMIT) QRF_VARIABLES = ("POPULACE_FIT_N_JOBS", "POPULACE_FIT_PREDICT_WORKERS") -SET_BY_COMMANDS = (OPENMP, OPENBLAS, MKL, BLIS, VECLIB, NUMEXPR) #: Every variable a process-level case clears before applying its own. THREAD_VARIABLES = ( - *SET_BY_COMMANDS, - OPENBLAS_FALLBACK, - NUMEXPR_MAXIMUM, - JOBLIB_LIMIT, + THREAD_SETTING, + *FILLED_VARIABLES, + "GOTO_NUM_THREADS", + "NUMEXPR_MAX_THREADS", *QRF_VARIABLES, ) @@ -63,8 +62,8 @@ def _clean_environment(settings: Mapping[str, str] = {}) -> dict[str, str]: return environment -def _last_json_line(command: list[str], environment: dict[str, str]) -> dict: - completed = subprocess.run( +def _run(command: list[str], environment: dict[str, str]): + return subprocess.run( command, cwd=REPOSITORY, env=environment, @@ -72,10 +71,18 @@ def _last_json_line(command: list[str], environment: dict[str, str]) -> dict: text=True, check=False, ) + + +def _last_json_line(command: list[str], environment: dict[str, str]) -> dict: + completed = _run(command, environment) assert completed.returncode == 0, completed.stderr[-4000:] return json.loads(completed.stdout.strip().splitlines()[-1]) +def _every_variable(count: str, **replacements: str) -> dict[str, str]: + return {**dict.fromkeys(FILLED_VARIABLES, count), **replacements} + + # --------------------------------------------------------------------------- # The values chosen # --------------------------------------------------------------------------- @@ -92,161 +99,94 @@ def helper() -> ModuleType: return module -def _defaults_for( +def _filled( helper: ModuleType, - monkeypatch: pytest.MonkeyPatch, settings: Mapping[str, str] = {}, *, - usable_cpus: int | None = 6, - online_cpus: int | None = 6, + default_count: int | None = None, ) -> dict[str, str]: - monkeypatch.setattr(helper.os, "process_cpu_count", lambda: usable_cpus) - monkeypatch.setattr(helper.os, "cpu_count", lambda: online_cpus) environment = dict(settings) - helper.set_build_thread_environment(environment) + helper.set_build_thread_environment(environment, default_count=default_count) return environment -def _every_variable(count: str, **replacements: str) -> dict[str, str]: - return {**dict.fromkeys(SET_BY_COMMANDS, count), **replacements} +def test_nothing_is_set_without_the_thread_setting(helper: ModuleType) -> None: + settings = {OPENBLAS: "3", "UNRELATED": "value"} + assert _filled(helper) == {} + assert _filled(helper, settings) == settings -def test_unset_variables_take_the_usable_cpu_count( - helper: ModuleType, monkeypatch: pytest.MonkeyPatch -) -> None: - assert _defaults_for(helper, monkeypatch) == _every_variable("6") +def test_a_blank_thread_setting_counts_as_unset(helper: ModuleType) -> None: + assert _filled(helper, {THREAD_SETTING: ""}) == {THREAD_SETTING: ""} -def test_openmp_and_blas_counts_have_no_upper_limit( - helper: ModuleType, monkeypatch: pytest.MonkeyPatch -) -> None: - """numexpr alone limits itself to 16 threads when nothing configures it.""" - environment = _defaults_for(helper, monkeypatch, usable_cpus=32, online_cpus=32) +def test_the_thread_setting_fills_every_thread_variable(helper: ModuleType) -> None: + environment = _filled(helper, {THREAD_SETTING: "4"}) - assert environment == _every_variable("32", **{NUMEXPR: "16"}) + assert environment == {THREAD_SETTING: "4", **_every_variable("4")} -def test_cpu_affinity_sets_the_count_and_numexpr_counts_online_cpus( - helper: ModuleType, monkeypatch: pytest.MonkeyPatch -) -> None: - environment = _defaults_for(helper, monkeypatch, usable_cpus=4, online_cpus=10) +def test_the_thread_setting_has_no_upper_limit(helper: ModuleType) -> None: + environment = _filled(helper, {THREAD_SETTING: "64"}, default_count=16) - assert environment == _every_variable("4", **{NUMEXPR: "10"}) + assert environment == {THREAD_SETTING: "64", **_every_variable("64")} -@pytest.mark.parametrize( - ("configured", "expected"), - (("2", "2"), ("007", "7")), -) -def test_an_openmp_count_already_set_is_used_for_the_others( - helper: ModuleType, - monkeypatch: pytest.MonkeyPatch, - configured: str, - expected: str, -) -> None: - environment = _defaults_for(helper, monkeypatch, {OPENMP: configured}) +def test_leading_zeros_are_dropped_from_the_copies(helper: ModuleType) -> None: + environment = _filled(helper, {THREAD_SETTING: "007"}) - assert environment == _every_variable(expected, **{OPENMP: configured}) + assert environment == {THREAD_SETTING: "007", **_every_variable("7")} -def test_a_blank_openmp_value_counts_as_unset( - helper: ModuleType, monkeypatch: pytest.MonkeyPatch -) -> None: - environment = _defaults_for(helper, monkeypatch, {OPENMP: ""}) +def test_variables_already_set_are_kept(helper: ModuleType) -> None: + settings = {THREAD_SETTING: "4", OPENMP: "2", OPENBLAS: "5"} - assert environment == _every_variable("6", **{OPENMP: ""}) + assert _filled(helper, settings) == { + THREAD_SETTING: "4", + **_every_variable("4", **{OPENMP: "2", OPENBLAS: "5"}), + } -@pytest.mark.parametrize("configured", ("+4", "4,2", " 3 ", "0", "-1", "many", "٣")) -def test_libraries_read_an_unusual_openmp_value_themselves( - helper: ModuleType, monkeypatch: pytest.MonkeyPatch, configured: str -) -> None: - """OpenBLAS and numexpr parse these differently, so neither gets a copy.""" +def test_a_blank_thread_variable_is_filled(helper: ModuleType) -> None: + """Libraries read a blank thread variable as unset.""" - environment = _defaults_for(helper, monkeypatch, {OPENMP: configured}) + environment = _filled(helper, {THREAD_SETTING: "4", OPENMP: ""}) - assert environment == {OPENMP: configured, VECLIB: "6"} + assert environment == {THREAD_SETTING: "4", **_every_variable("4")} @pytest.mark.parametrize( - ("source", "left_unset"), - ((OPENBLAS_FALLBACK, OPENBLAS), (NUMEXPR_MAXIMUM, NUMEXPR)), + "configured", ("0", "-1", "+4", "4,2", " 3 ", "4.0", "many", "٣") ) -def test_libraries_read_their_own_unusual_values_themselves( - helper: ModuleType, - monkeypatch: pytest.MonkeyPatch, - source: str, - left_unset: str, +def test_a_thread_setting_that_is_not_a_positive_count_is_refused( + helper: ModuleType, configured: str ) -> None: - environment = _defaults_for(helper, monkeypatch, {source: "+3"}) - - assert left_unset not in environment - assert environment[MKL] == "6" + environment = {THREAD_SETTING: configured} + with pytest.raises(ValueError, match=THREAD_SETTING): + helper.set_build_thread_environment(environment, default_count=16) -def test_values_already_set_are_kept( - helper: ModuleType, monkeypatch: pytest.MonkeyPatch -) -> None: - settings = {name: str(index + 1) for index, name in enumerate(SET_BY_COMMANDS)} + assert environment == {THREAD_SETTING: configured} - assert _defaults_for(helper, monkeypatch, settings) == settings - -def test_openblas_follows_its_own_fallback_variable( - helper: ModuleType, monkeypatch: pytest.MonkeyPatch -) -> None: - environment = _defaults_for( - helper, monkeypatch, {OPENMP: "2", OPENBLAS_FALLBACK: "3"} - ) - - assert environment == { - **_every_variable("2", **{OPENBLAS: "3"}), - OPENBLAS_FALLBACK: "3", - } - - -@pytest.mark.parametrize( - ("settings", "expected"), - ( - ({NUMEXPR_MAXIMUM: "3"}, "3"), - ({NUMEXPR_MAXIMUM: "3", OPENMP: "2"}, "2"), - ), -) -def test_numexpr_follows_openmp_and_then_its_maximum( +def test_the_default_count_applies_without_the_thread_setting( helper: ModuleType, - monkeypatch: pytest.MonkeyPatch, - settings: dict[str, str], - expected: str, -) -> None: - environment = _defaults_for(helper, monkeypatch, settings) - - assert environment[NUMEXPR] == expected - - -def test_nothing_is_set_when_the_usable_cpus_are_unknown( - helper: ModuleType, monkeypatch: pytest.MonkeyPatch ) -> None: - environment = _defaults_for(helper, monkeypatch, usable_cpus=None, online_cpus=None) + assert _filled(helper, default_count=16) == _every_variable("16") - assert environment == {} +def test_the_thread_setting_replaces_the_default_count(helper: ModuleType) -> None: + environment = _filled(helper, {THREAD_SETTING: "3"}, default_count=16) -def test_numexpr_uses_the_usable_count_when_online_cpus_are_unknown( - helper: ModuleType, monkeypatch: pytest.MonkeyPatch -) -> None: - environment = _defaults_for(helper, monkeypatch, usable_cpus=20, online_cpus=None) - - assert environment == _every_variable("20", **{NUMEXPR: "16"}) + assert environment == {THREAD_SETTING: "3", **_every_variable("3")} -def test_a_second_call_changes_nothing( - helper: ModuleType, monkeypatch: pytest.MonkeyPatch -) -> None: - environment = _defaults_for(helper, monkeypatch, usable_cpus=32, online_cpus=32) +def test_a_second_call_changes_nothing(helper: ModuleType) -> None: + environment = _filled(helper, {THREAD_SETTING: "4"}) first_result = dict(environment) - helper.set_build_thread_environment(environment) + helper.set_build_thread_environment(environment, default_count=16) assert environment == first_result @@ -256,8 +196,9 @@ def test_a_second_call_changes_nothing( # --------------------------------------------------------------------------- #: Starts one tool under ``runpy`` and stops it at its first import of a -#: numerical library, printing the environment at that moment. The tool's -#: imports never finish, so a case costs no more than the code before them. +#: numerical library, printing the environment and import path at that moment. +#: The tool's imports never finish, so a case costs no more than the code +#: before them. _START_PROBE = """ import json import os @@ -285,6 +226,7 @@ def find_spec(self, name, path=None, target=None): os.cpu_count = lambda: cpu_count os.process_cpu_count = lambda: cpu_count sys.path.insert(0, str(tool.parent)) +path_before = list(sys.path) sys.argv = [str(tool), "--help"] sys.meta_path.insert(0, StopAtNumericalLibrary()) library = None @@ -293,10 +235,22 @@ def find_spec(self, name, path=None, target=None): except ReachedNumericalLibrary as reached: library = str(reached) print() -print(json.dumps({"library": library, "environment": dict(os.environ)})) +print( + json.dumps( + { + "library": library, + "environment": dict(os.environ), + "path_unchanged": sys.path == path_before, + } + ) +) """ +def _probe_command(tool: str, run_name: str, cpu_count: int) -> list[str]: + return [sys.executable, "-c", _START_PROBE, tool, run_name, str(cpu_count)] + + def _state_at_first_numerical_import( tool: str, *, @@ -305,119 +259,163 @@ def _state_at_first_numerical_import( settings: Mapping[str, str] = {}, ) -> dict: state = _last_json_line( - [sys.executable, "-c", _START_PROBE, tool, run_name, str(cpu_count)], - _clean_environment(settings), + _probe_command(tool, run_name, cpu_count), _clean_environment(settings) ) assert state["library"] is not None return state +def _thread_variables_in(environment: Mapping[str, str]) -> dict[str, str]: + return {name: environment[name] for name in THREAD_VARIABLES if name in environment} + + @pytest.mark.parametrize("tool", BUILD_COMMANDS) -def test_a_started_command_sets_every_variable_before_numerical_imports( +def test_a_started_command_sets_nothing_without_the_thread_setting( tool: str, ) -> None: environment = _state_at_first_numerical_import(tool)["environment"] - assert {name: environment.get(name) for name in SET_BY_COMMANDS} == ( - _every_variable("3", **{NUMEXPR: "3"}) - ) + assert _thread_variables_in(environment) == {} -@pytest.mark.parametrize("tool", BUILD_COMMANDS) +@pytest.mark.parametrize("tool", EVERY_COMMAND) +def test_a_started_command_fills_every_variable_before_numerical_imports( + tool: str, +) -> None: + environment = _state_at_first_numerical_import( + tool, cpu_count=32, settings={THREAD_SETTING: "5"} + )["environment"] + + assert _thread_variables_in(environment) == { + THREAD_SETTING: "5", + **_every_variable("5"), + } + + +@pytest.mark.parametrize("tool", EVERY_COMMAND) def test_a_started_command_keeps_the_values_it_was_given(tool: str) -> None: - settings = {OPENMP: "2", OPENBLAS: "5"} + settings = {THREAD_SETTING: "5", OPENMP: "2", OPENBLAS: "7"} environment = _state_at_first_numerical_import(tool, settings=settings)[ "environment" ] - assert {name: environment.get(name) for name in SET_BY_COMMANDS} == ( - _every_variable("2", **{OPENBLAS: "5"}) + assert _thread_variables_in(environment) == { + THREAD_SETTING: "5", + **_every_variable("5", **{OPENMP: "2", OPENBLAS: "7"}), + } + + +@pytest.mark.parametrize("tool", EVERY_COMMAND) +def test_a_started_command_refuses_an_unusable_thread_setting(tool: str) -> None: + completed = _run( + _probe_command(tool, "__main__", 3), + _clean_environment({THREAD_SETTING: "four"}), ) + assert completed.returncode != 0 + assert THREAD_SETTING in completed.stderr + assert "ReachedNumericalLibrary" not in completed.stderr + @pytest.mark.parametrize("tool", BUILD_COMMANDS) def test_importing_a_command_changes_no_thread_variable(tool: str) -> None: """Tests and other tools import these files, often after numpy has loaded.""" - environment = _state_at_first_numerical_import(tool, run_name="imported_tool")[ - "environment" - ] + environment = _state_at_first_numerical_import( + tool, run_name="imported_tool", settings={THREAD_SETTING: "5"} + )["environment"] - assert not set(THREAD_VARIABLES) & set(environment) + assert _thread_variables_in(environment) == {THREAD_SETTING: "5"} -@pytest.mark.parametrize("tool", (*BUILD_COMMANDS, RELEASE_TOOL)) -def test_no_command_sets_the_qrf_or_joblib_limits_of_the_base_build( - tool: str, -) -> None: - environment = _state_at_first_numerical_import(tool)["environment"] +@pytest.mark.parametrize("tool", EVERY_COMMAND) +def test_no_command_sets_the_qrf_variables(tool: str) -> None: + environment = _state_at_first_numerical_import( + tool, settings={THREAD_SETTING: "5"} + )["environment"] assert not set(QRF_VARIABLES) & set(environment) - if tool != RELEASE_TOOL: - assert JOBLIB_LIMIT not in environment @pytest.mark.parametrize(("cpu_count", "expected"), ((3, "3"), (32, "16"))) -def test_release_tool_keeps_its_existing_thread_values( +def test_release_tool_keeps_its_default_without_the_thread_setting( cpu_count: int, expected: str ) -> None: - environment = _state_at_first_numerical_import(RELEASE_TOOL, cpu_count=cpu_count)[ - "environment" - ] + """Its existing six variables keep their values; BLIS has no library here.""" + + state = _state_at_first_numerical_import(RELEASE_TOOL, cpu_count=cpu_count) + + assert _thread_variables_in(state["environment"]) == _every_variable(expected) + assert state["path_unchanged"] - for name in (OPENMP, OPENBLAS, MKL, NUMEXPR, VECLIB, JOBLIB_LIMIT): - assert environment[name] == expected, name - assert BLIS not in environment + +def test_importing_the_release_tool_still_applies_its_default() -> None: + """It always has: its tests import it, and the values only fill unset ones.""" + + state = _state_at_first_numerical_import( + RELEASE_TOOL, run_name="imported_tool", cpu_count=32 + ) + + assert _thread_variables_in(state["environment"]) == _every_variable("16") + assert state["path_unchanged"] # --------------------------------------------------------------------------- # What the libraries do with them # --------------------------------------------------------------------------- -#: Loads the libraries, with or without the commands' settings, and prints the -#: thread counts they chose and results of the BLAS operations whose bytes -#: depend on the OpenBLAS thread count on Linux. -_LIBRARY_PROBE = """ -import hashlib +#: Applies the commands' settings, loads every library whose thread count they +#: choose, and prints the counts each library ended with. +_THREAD_COUNT_PROBE = """ import json import sys sys.path.insert(0, "tools") -if sys.argv[1] == "with_settings": - from us_build_thread_environment import set_build_thread_environment +from us_build_thread_environment import set_build_thread_environment - set_build_thread_environment() +set_build_thread_environment() +import joblib import numexpr -import numpy as np -import sklearn.utils._openmp_helpers +import numpy +import scipy.linalg import threadpoolctl +import torch +from sklearn.utils._openmp_helpers import _openmp_effective_n_threads -generator = np.random.default_rng(0) -weights = generator.lognormal(7.0, 1.0, 150_000) -values = generator.lognormal(8.0, 1.5, 150_000) -probabilities = generator.dirichlet(np.ones(3), 150_000) -scaled_column = values * (9.6e11 / float(weights @ values)) print() print( json.dumps( { - "pools": sorted( - [pool["user_api"], pool["internal_api"], pool["num_threads"]] - for pool in threadpoolctl.threadpool_info() + "thread_pools": sorted( + {pool["num_threads"] for pool in threadpoolctl.threadpool_info()} ), - "numexpr_threads": numexpr.utils.get_num_threads(), - "dot_product": float(np.dot(weights, values)).hex(), - "scaled_column": hashlib.sha256(scaled_column.tobytes()).hexdigest(), - "weighted_probabilities": hashlib.sha256( - (weights @ probabilities).tobytes() - ).hexdigest(), + "numexpr": numexpr.utils.get_num_threads(), + "scikit_learn": _openmp_effective_n_threads(), + "joblib_cpu_count": joblib.cpu_count(), + "torch": torch.get_num_threads(), } ) ) """ + +def test_the_thread_setting_reaches_every_library() -> None: + counts = _last_json_line( + [sys.executable, "-c", _THREAD_COUNT_PROBE], + _clean_environment({THREAD_SETTING: "2"}), + ) + + assert counts == { + "thread_pools": [2], + "numexpr": 2, + "scikit_learn": 2, + "joblib_cpu_count": 2, + "torch": 2, + } + + _SIGN_CLASSIFIER_PROBE = """ import hashlib import json @@ -438,45 +436,8 @@ def test_release_tool_keeps_its_existing_thread_values( """ -@functools.cache -def _library_results( - mode: str, settings: tuple[tuple[str, str], ...] -) -> dict[str, object]: - return _last_json_line( - [sys.executable, "-c", _LIBRARY_PROBE, mode], - _clean_environment(dict(settings)), - ) - - -@pytest.mark.parametrize( - "settings", - ( - (), - ((OPENMP, "2"),), - ((OPENMP, "+4"),), - ((OPENBLAS_FALLBACK, "2"),), - ((NUMEXPR_MAXIMUM, "3"),), - ((NUMEXPR_MAXIMUM, "3"), (OPENMP, "2")), - ), - ids=( - "nothing", - "openmp", - "openmp_with_sign", - "openblas_fallback", - "numexpr_maximum", - "both", - ), -) -def test_the_settings_keep_thread_counts_and_result_bytes( - settings: tuple[tuple[str, str], ...], -) -> None: - assert _library_results("with_settings", settings) == _library_results( - "without_settings", settings - ) - - def test_sign_classifier_probabilities_do_not_depend_on_the_openmp_count() -> None: - """scikit-learn may move from physical to logical CPUs under the settings.""" + """The thread setting changes the classifier's OpenMP count.""" digests = { thread_count: _last_json_line( diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_builder.py index d141097858..b9fad483eb 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_builder.py @@ -1344,7 +1344,11 @@ def test_outer_stage_resume_accepts_a_changed_qrf_thread_count( @pytest.mark.parametrize( ("variable", "first_value", "changed_value"), - (("OMP_NUM_THREADS", "1", "2"), ("PYTHONHASHSEED", "0", "1")), + ( + ("OMP_NUM_THREADS", "1", "2"), + ("PYTHONHASHSEED", "0", "1"), + ("MICROCOSM_THREADS", "2", "3"), + ), ) def test_outer_stage_resume_refuses_other_changed_environment_values( monkeypatch: pytest.MonkeyPatch, @@ -1363,6 +1367,39 @@ def test_outer_stage_resume_refuses_other_changed_environment_values( builder._open_stage_runtime(args) +def test_outer_stage_resume_refuses_a_changed_blas_thread_count( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + """With no thread variable set, OpenBLAS follows the host's CPUs.""" + + builder = _load_support_builder_module() + args = _resumable_builder_args(builder, monkeypatch, tmp_path) + monkeypatch.setattr(builder, "_blas_threads_in_use", lambda: [["openblas", 4]]) + first_config = builder._open_stage_runtime(args).context.run_config + assert first_config["thread_environment"]["blas_threads_in_use"] == [ + ["openblas", 4] + ] + + monkeypatch.setattr(builder, "_blas_threads_in_use", lambda: [["openblas", 8]]) + with pytest.raises(ValueError, match="run_config differs"): + builder._open_stage_runtime(args) + + +def test_blas_threads_in_use_lists_each_loaded_blas_library( + monkeypatch: pytest.MonkeyPatch, +) -> None: + builder = _load_support_builder_module() + loaded_pools = [ + {"user_api": "openmp", "internal_api": "openmp", "num_threads": 10}, + {"user_api": "blas", "internal_api": "openblas", "num_threads": 6}, + {"user_api": "blas", "internal_api": "openblas", "num_threads": 4}, + ] + monkeypatch.setattr(builder, "threadpool_info", lambda: loaded_pools) + + assert builder._blas_threads_in_use() == [["openblas", 4], ["openblas", 6]] + + def test_puf_donor_builder_threads_explicit_source_year_agi( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, From ea9eb078c3d483c7c584fd4dc7f4198c94f3d7bb Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:40:47 +0400 Subject: [PATCH 04/10] Use one thread setting, MICROCOSM_THREADS, in the US build commands The release, base and ACS multispine staging commands copy MICROCOSM_THREADS, before numpy loads, into every unset OpenMP, BLAS, numexpr and joblib thread variable, and refuse a value that is not a positive whole number. Without it the base and ACS staging commands set nothing, so each library keeps choosing its own count, and the release tool keeps its default of min(os.cpu_count(), 16). The base command records MICROCOSM_THREADS and each loaded BLAS library's thread count (threadpoolctl) in thread_environment, so a resume on a host where OpenBLAS would use a different count is refused: on Linux that count changes output bytes. threadpoolctl, already installed through scikit-learn, is now declared by microcosm-build. Co-Authored-By: Claude Opus 5.5 --- .../us-build-thread-environment.changed.md | 4 +- docs/us-modal-stage-runbook.md | 166 ++++++++++-------- packages/microcosm-build/pyproject.toml | 3 + pyproject.toml | 2 +- tools/build_us_acs_multispine_base.py | 10 +- tools/build_us_fiscal_refresh_release.py | 29 ++- tools/build_us_puf_support_base.py | 40 +++-- tools/us_build_thread_environment.py | 157 +++++++++-------- uv.lock | 2 + 9 files changed, 232 insertions(+), 181 deletions(-) diff --git a/changelog.d/us-build-thread-environment.changed.md b/changelog.d/us-build-thread-environment.changed.md index d0d34613e6..b7f1a2a2a6 100644 --- a/changelog.d/us-build-thread-environment.changed.md +++ b/changelog.d/us-build-thread-environment.changed.md @@ -1,3 +1,3 @@ -The US base and ACS multispine staging commands now set their OpenMP, BLAS and numexpr thread variables before numpy loads. Each BLAS and numexpr variable gets the count its library already uses: `OMP_NUM_THREADS` if it is a plain count, otherwise `os.process_cpu_count()`, with no upper limit, and numexpr keeps its own rule. Values already set are kept, and importing the tools changes nothing. +`MICROCOSM_THREADS` is the one thread setting of the US release, base and ACS multispine staging commands. When it is set to a positive whole number, each command copies it, before numpy loads, into every unset OpenMP, BLAS, numexpr and joblib thread variable (`OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `MKL_NUM_THREADS`, `BLIS_NUM_THREADS`, `VECLIB_MAXIMUM_THREADS`, `NUMEXPR_NUM_THREADS` and `LOKY_MAX_CPU_COUNT`). Variables already set keep their values, and a value that is not a positive whole number stops the command. Without it, the base and ACS staging commands set nothing and each library chooses its own count as before, and the release tool keeps its default of `min(os.cpu_count(), 16)`. -On Linux the OpenBLAS thread count changes output bytes, so a build's output already depends on the host's count. This change keeps that count, so it keeps a host's output, and the base command now records real counts in `thread_environment` and refuses a resume with different ones. OpenMP and BLAS still do not follow a CPU quota. Because `OMP_NUM_THREADS` is now set, scikit-learn's sign classifier and torch use that count instead of their own defaults, which for scikit-learn means it no longer follows a CPU quota or `LOKY_MAX_CPU_COUNT`. +On Linux the OpenBLAS thread count changes output bytes, so the base command now records `MICROCOSM_THREADS` and each loaded BLAS library's thread count (`blas_threads_in_use`, from threadpoolctl) in `thread_environment`, and a resume with different values is refused, including one on a host where OpenBLAS would use a different count. diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index 9ed1227340..57383fdd4d 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -397,43 +397,51 @@ that release's current build. ## Thread variables -The base command (`tools/build_us_puf_support_base.py`) and the ACS multispine -staging command (`tools/build_us_acs_multispine_base.py`, and -`tools/_legacy/build_us_acs_multispine_base.py` when that file is run directly) -set their OpenMP, BLAS and numexpr thread variables before numpy loads -(`tools/us_build_thread_environment.py`). They do this only when started as -commands, not when imported. A value already in the environment, from an -operator, a plan or Modal, is kept. `tools/build_us_acs_local_release.py`, which -builds the local-area release from the staging output, does not run this step. - -The tools at `4b57d15a2` and `74f5e6123`, the commits pinned by the historical -base plan and the ACS staging plan, predate this step and leave the variables as -they find them. A plan made from the default-pool template runs the step once -its commit contains it. - -| Variable | Value when unset | -| --- | --- | -| `OMP_NUM_THREADS` | `os.process_cpu_count()` | -| `MKL_NUM_THREADS`, `BLIS_NUM_THREADS`, `VECLIB_MAXIMUM_THREADS` | `OMP_NUM_THREADS` if it is a plain count, otherwise `os.process_cpu_count()` | -| `OPENBLAS_NUM_THREADS` | `GOTO_NUM_THREADS` if it is a plain count, otherwise as above | -| `NUMEXPR_NUM_THREADS` | `OMP_NUM_THREADS` if it is a plain count, otherwise `NUMEXPR_MAX_THREADS` if that is, otherwise the online CPUs up to 16 | - -A plain count is a positive decimal integer. Libraries read other spellings, such -as `+4` or `4,2`, in different ways, so the commands do not copy them: the -variables that would copy the value stay unset, and each library reads the -original as it does without this step. `VECLIB_MAXIMUM_THREADS` then takes -`os.process_cpu_count()`. A variable whose count is unknown stays unset. - -**BLAS and numexpr keep their counts.** The step names the counts these libraries -already use and does not limit them. OpenMP and BLAS have no upper limit here, -unlike the release tool's limit of 16. They follow CPU affinity but not a CPU -quota, so outside Modal a container held to 2 CPUs by a quota starts one BLAS -thread per visible CPU, with or without this step. The commands do not set -`LOKY_MAX_CPU_COUNT`, `POPULACE_FIT_N_JOBS` or `POPULACE_FIT_PREDICT_WORKERS`. -With those unset, QRF fitting and drawing use `joblib.cpu_count()`, which does -follow a quota. The release tool keeps its own settings: `min(os.cpu_count(), 16)` -for `OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `MKL_NUM_THREADS`, -`NUMEXPR_NUM_THREADS`, `VECLIB_MAXIMUM_THREADS` and `LOKY_MAX_CPU_COUNT`. +`MICROCOSM_THREADS` is the one thread setting of three US commands: the release +command (`tools/build_us_fiscal_refresh_release.py`), the base command +(`tools/build_us_puf_support_base.py`) and the ACS multispine staging command +(`tools/build_us_acs_multispine_base.py`, and +`tools/_legacy/build_us_acs_multispine_base.py` when that file is run directly). +Set it to a positive whole number to choose the thread count of every numerical +library these commands use. Before numpy loads, `tools/us_build_thread_environment.py` +copies it into each of these variables that is unset or blank: + +- `OMP_NUM_THREADS`: OpenMP, which scikit-learn's QRF sign classifier and torch + use. OpenBLAS and numexpr read it when their own variable is unset. +- `OPENBLAS_NUM_THREADS`: OpenBLAS, which numpy and scipy bundle on Linux. It + reads this before its older name, `GOTO_NUM_THREADS`. +- `MKL_NUM_THREADS`: Intel MKL, which only torch bundles here. torch also takes + its own thread count from it. +- `BLIS_NUM_THREADS`: BLIS, which nothing installed here uses. +- `VECLIB_MAXIMUM_THREADS`: Apple's Accelerate, which numpy uses on macOS. +- `NUMEXPR_NUM_THREADS`: numexpr, which pandas uses for large element-wise + arithmetic. +- `LOKY_MAX_CPU_COUNT`: the limit on `joblib.cpu_count()`, which sizes the QRF's + tree-building jobs and prediction workers while `POPULACE_FIT_N_JOBS` and + `POPULACE_FIT_PREDICT_WORKERS` are unset. + +A variable that already has a value keeps it, so one library's count can still be +set directly. A setting that is not a positive whole number, such as `0`, `+4` or +`four`, stops the command before numpy loads. The base and ACS staging commands +read the setting only when started as commands, not when imported. +`tools/build_us_acs_local_release.py` does not read it. + +**Without the setting.** The base and ACS staging commands set nothing, and each +library chooses its own count, as before: + +- OpenBLAS and OpenMP use the CPUs the process may run on (its CPU affinity). + They do not follow a CPU quota. +- scikit-learn uses at most the physical cores, a CPU quota allows and + `LOKY_MAX_CPU_COUNT` allows. torch uses the physical cores (on Apple chips, the + performance cores). +- numexpr uses the online CPUs, up to 16. +- `joblib.cpu_count()`, and with it the QRF's pools, follows CPU affinity, a CPU + quota and `LOKY_MAX_CPU_COUNT`. + +The release tool instead fills the same variables with `min(os.cpu_count(), 16)`, +as it did before for all of them but `BLIS_NUM_THREADS`, which has no effect here. +It does this on import too, as it always has. Its calibration's exact weights +depend on torch's thread count, so that default stays. **On Linux the BLAS thread count changes output bytes.** numpy's Linux wheels use OpenBLAS, which splits a large dot product between its threads, so the order of @@ -454,50 +462,60 @@ example: - cross-fitted calibration of the QRF sign classifier (`microcosm.fit.qrf`), which uses `w @ ...` on row-length vectors. -So a Linux build's output already depends on the host's thread count, and it -still does: two hosts with different counts can write different bytes. With and -without this step, one x86-64 container gave the same OpenBLAS, OpenMP and numexpr -counts and the same result bytes, with no CPU limit, under a 2-CPU quota and -under a 4-CPU affinity limit. - -**Setting `OMP_NUM_THREADS` changes two other counts.** With the variable unset, -scikit-learn uses `joblib.cpu_count(only_physical_cores=True)` at most, which -follows a CPU quota and `LOKY_MAX_CPU_COUNT`. With it set, scikit-learn uses that -value. So when nothing else has set the variable, the QRF sign classifier -(`HistGradientBoostingClassifier`) can run on all logical CPUs where it would -have used physical cores, and under a quota it starts one thread per visible CPU: -2 threads became 10 in a 2-CPU container. Its probabilities were byte-identical -at 1, 2 and 4 OpenMP threads in the tests, which does not prove it for every -input, and its run time may change, particularly under a quota. torch follows the -variable too (`torch.get_num_threads()`); neither command runs a torch -calculation that review found. +So a Linux base build's output depends on the OpenBLAS thread count. Without the +setting that count follows the host, so two hosts with different CPU counts can +write different bytes, as before. A build made with `MICROCOSM_THREADS=N` matches +one made without it only where OpenBLAS would otherwise use N threads. + +**Other effects of the setting.** Because it sets `OMP_NUM_THREADS`, scikit-learn +no longer limits itself to physical cores, a CPU quota or `LOKY_MAX_CPU_COUNT`: +the sign classifier uses N threads. Its probabilities were byte-identical at 1, 2 +and 4 OpenMP threads in the tests, which does not prove it for every input. torch +uses N threads too; review found no torch calculation in the base or ACS staging +commands. The QRF's pools use `joblib.cpu_count()`, at most N, and their imputed +values do not depend on those counts. **When a change takes effect.** -- *Base, OpenMP and BLAS variables and `NUMEXPR_NUM_THREADS`:* recorded in - `stage_run_context.json` under `thread_environment` and compared on resume. A - different value, including one that comes from a host with a different CPU - count, is refused, so a new value needs a new checkpoint directory. -- *Base, `PYTHONHASHSEED`:* recorded and compared in the same way. -- *Base, `POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS`:* recorded and - not compared. A new value applies from the next outer stage of a resumed run. -- *Base runs started before this step:* they cannot resume after it. The run +- *Base command.* Its run configuration (`stage_run_context.json`) records, under + `thread_environment`, `MICROCOSM_THREADS`, `OMP_NUM_THREADS`, + `OPENBLAS_NUM_THREADS`, `MKL_NUM_THREADS`, `BLIS_NUM_THREADS`, + `VECLIB_MAXIMUM_THREADS`, `NUMEXPR_NUM_THREADS`, `POPULACE_FIT_N_JOBS`, + `POPULACE_FIT_PREDICT_WORKERS` and `PYTHONHASHSEED`. It also records + `blas_threads_in_use`: each loaded BLAS library with the thread count it uses + once numpy has loaded, as `threadpoolctl` reports it. threadpoolctl does not + report Accelerate, so on macOS the list is empty. +- *A resume of the base command* compares all of these except + `POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS`, and refuses a + difference, so a new thread setting needs a new checkpoint directory. Because + `blas_threads_in_use` is compared, a resume is also refused on a host where + OpenBLAS would use a different count. Before, with the variables unset on both + hosts, the configurations matched. +- *`POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS`:* recorded and not + compared. A new value applies from the next outer stage of a resumed run. + `LOKY_MAX_CPU_COUNT` is not recorded. None of the three changes an imputed value. +- *Base runs started before this change:* they cannot resume after it. The run configuration holds a digest that covers the tool's own file (`builder_code_identity`), and the file changed. - *ACS multispine staging command:* it keeps no run configuration, so the values apply to the process that was started. -**On Modal.** A plan may set `OMP_NUM_THREADS`, `MKL_NUM_THREADS`, -`OPENBLAS_NUM_THREADS`, `NUMEXPR_NUM_THREADS` and `BLIS_NUM_THREADS`. It may not -set `VECLIB_MAXIMUM_THREADS`, `GOTO_NUM_THREADS` or `NUMEXPR_MAX_THREADS`. Modal -set `OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `MKL_NUM_THREADS` and +**On Modal.** A plan may set `MICROCOSM_THREADS`, because its environment +allowlist accepts `MICROCOSM_*` names, and it may set `OMP_NUM_THREADS`, +`MKL_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `NUMEXPR_NUM_THREADS` and +`BLIS_NUM_THREADS` directly. It may not set `VECLIB_MAXIMUM_THREADS`, +`LOKY_MAX_CPU_COUNT`, `GOTO_NUM_THREADS` or `NUMEXPR_MAX_THREADS`. Modal set +`OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `MKL_NUM_THREADS` and `BLIS_NUM_THREADS` to the class's CPU request in the check class (2) and in a `base` run at `4b57d15a2` (4; `docs/evidence/us-release-reimputation-1191/receipts/build_environment.base_0fb05b67.release_417d23ae.json`). -With those set, the commands give `VECLIB_MAXIMUM_THREADS` and -`NUMEXPR_NUM_THREADS` the same count, so the attempts of a base run record the -same values on any host. No record shows what Modal sets in the `acs-staging` -class. +Because a value already set is kept, a plan's `MICROCOSM_THREADS` does not +replace those four. It fills only `VECLIB_MAXIMUM_THREADS`, `NUMEXPR_NUM_THREADS` +and `LOKY_MAX_CPU_COUNT`. To change the BLAS and OpenMP counts on Modal, a plan +sets those variables directly, as before. No record shows what Modal sets in the +`acs-staging` class. The tools at `4b57d15a2` and `74f5e6123`, the commits pinned +by the historical base plan and the ACS staging plan, predate the setting and +ignore it. ## Resources and cost @@ -1267,8 +1285,9 @@ digests, settings, its code identity and the thread variables it sees) and refuses a resume whose config differs. Code newer than the pinned `4b57d15a2` that contains the QRF thread-count change records `POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS` without comparing -them, and code that sets the OpenMP and BLAS variables itself compares the -counts it set (see "Thread variables"). Every path in the config is the same in +them, and code that reads `MICROCOSM_THREADS` also records it and the BLAS +thread counts in use, and compares them (see "Thread variables"). Every path in +the config is the same in every attempt of the run, and so are the image, the plan's environment and the class, so a relaunch of the same plan should resume. If Modal gave the new container different compared thread variables, the tool would refuse, @@ -1431,7 +1450,8 @@ Two things are reported and never refused: the interpreter string differs (`thread_environment_differences`). The tool reads those variables from its environment, and Modal sets some of them itself (see "Resources"). These differences are reported and not refused, although a different BLAS or -OpenMP count can change output bytes on Linux (see "Thread variables"). Only the +OpenMP count can change output bytes on Linux (see "Thread variables"). That +includes `blas_threads_in_use`, which is empty for a macOS run. Only the checkpoint digests compared above show that outputs agree. The report says `compared_outputs_match`, with `stages_compared` 2 of `stages_total` 24 and the 22 stages it did not compare (`stages_not_compared`). diff --git a/packages/microcosm-build/pyproject.toml b/packages/microcosm-build/pyproject.toml index b15a3f6189..fb8df9f66e 100644 --- a/packages/microcosm-build/pyproject.toml +++ b/packages/microcosm-build/pyproject.toml @@ -30,6 +30,9 @@ dependencies = [ # emitter release needs no change here. The socket protocol carries its # own version, and every emitter release accepts the versions in use. "microcosm-emitter-interface>=0.16.0,<1", + # The US base command records each loaded BLAS library's thread count in + # its run configuration. scikit-learn already depends on it. + "threadpoolctl>=3.1", ] [project.optional-dependencies] diff --git a/pyproject.toml b/pyproject.toml index 413c95c6d9..88c518e863 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,7 +43,7 @@ ignore = ["E501"] # defaults before numpy/torch load, which requires statements above the # import block. "tools/build_us_fiscal_refresh_release.py" = ["E402"] -# The base and ACS staging commands set their thread variables before numpy +# The base and ACS staging commands apply the thread setting before numpy # loads (tools/us_build_thread_environment.py), for the same reason. "tools/build_us_puf_support_base.py" = ["E402"] "tools/build_us_acs_multispine_base.py" = ["E402"] diff --git a/tools/build_us_acs_multispine_base.py b/tools/build_us_acs_multispine_base.py index 3394c755d1..c5f2dd9663 100644 --- a/tools/build_us_acs_multispine_base.py +++ b/tools/build_us_acs_multispine_base.py @@ -9,10 +9,12 @@ from __future__ import annotations if __name__ == "__main__": - # OpenBLAS and OpenMP read these variables when they load, and the imports - # below load numpy before the implementation file does. This runs only for - # the command: tests and other tools import this file. E402 is ignored for - # this file in pyproject for this block. + # The one thread setting, MICROCOSM_THREADS, fills the OpenMP, BLAS, + # numexpr and joblib thread variables, and the libraries read those when + # they load. The imports below load numpy before the implementation file + # does, so this comes first. Without the setting nothing is set. This runs + # only for the command: tests and other tools import this file. E402 is + # ignored for this file in pyproject for this block. from us_build_thread_environment import set_build_thread_environment set_build_thread_environment() diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 26a8f0318a..5805d653b5 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -26,24 +26,25 @@ from __future__ import annotations import os +import sys +from pathlib import Path # microcosm#456 (#447 ops note): bound the default BLAS/OpenMP/joblib thread # pools instead of inheriting machine geometry — per-thread scratch buffers # scale the resident set with core count (measured 125 GB anon-RSS at 16 vCPU # vs 249 GB at 32 vCPU for the same build). OpenBLAS and torch read these at -# library load, so this must precede the numpy/torch imports below; operator- -# set values always win (setdefault only). E402 is ignored for this file in -# pyproject for exactly this block. -_THREAD_POOL_DEFAULT = str(min(os.cpu_count() or 1, 16)) -for _thread_pool_variable in ( - "OMP_NUM_THREADS", - "OPENBLAS_NUM_THREADS", - "MKL_NUM_THREADS", - "NUMEXPR_NUM_THREADS", - "VECLIB_MAXIMUM_THREADS", - "LOKY_MAX_CPU_COUNT", -): - os.environ.setdefault(_thread_pool_variable, _THREAD_POOL_DEFAULT) +# library load, so this must precede the numpy/torch imports below. The one +# thread setting of the US build commands, MICROCOSM_THREADS, replaces the +# default of min(os.cpu_count(), 16), and variables already set keep their +# values (tools/us_build_thread_environment.py). This also runs on import, as +# it always has. The helper is loaded from this file's folder, which an import +# does not always have on its path. E402 is ignored for this file in pyproject +# for exactly this block. +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from us_build_thread_environment import set_build_thread_environment + +del sys.path[0] +set_build_thread_environment(default_count=min(os.cpu_count() or 1, 16)) import argparse import dataclasses @@ -57,14 +58,12 @@ import shlex import shutil import subprocess -import sys import time import tomllib import uuid from collections.abc import Callable, Iterable, Mapping, Sequence from contextlib import contextmanager, nullcontext from datetime import UTC, datetime -from pathlib import Path from types import MethodType, SimpleNamespace from typing import Any diff --git a/tools/build_us_puf_support_base.py b/tools/build_us_puf_support_base.py index e158ade410..821aeea0f0 100644 --- a/tools/build_us_puf_support_base.py +++ b/tools/build_us_puf_support_base.py @@ -19,11 +19,13 @@ from __future__ import annotations if __name__ == "__main__": - # OpenBLAS and OpenMP read these variables when they load, so this comes - # before numpy. It runs only for the command: tests and other tools import - # this file. Stage subprocesses inherit the values, and the run - # configuration records them (``_stage_run_config``). E402 is ignored for - # this file in pyproject for this block. + # The one thread setting, MICROCOSM_THREADS, fills the OpenMP, BLAS, + # numexpr and joblib thread variables, and the libraries read those when + # they load, so this comes before numpy. Without the setting nothing is + # set. It runs only for the command: tests and other tools import this + # file. Stage subprocesses inherit the values, and the run configuration + # records them (``_stage_run_config``). E402 is ignored for this file in + # pyproject for this block. from us_build_thread_environment import set_build_thread_environment set_build_thread_environment() @@ -42,6 +44,7 @@ import numpy as np import pandas as pd +from threadpoolctl import threadpool_info from microcosm.build import FitWeightRecord, GateResult, weights_audit_gate from microcosm.build.frame_checkpoint import write_frame_checkpoint @@ -1271,17 +1274,32 @@ def _pooled_income_years(args: argparse.Namespace) -> tuple[int, ...]: #: QRF thread counts the first run records and a resume does not compare: they -#: change no imputed value. The BLAS and OpenMP thread counts and -#: PYTHONHASHSEED in ``thread_environment`` stay compared: on Linux the OpenBLAS -#: count changes output bytes, and the command fills those variables in from -#: the host (``us_build_thread_environment``), so a resume on a host with a -#: different CPU count is refused. +#: change no imputed value. Everything else in ``thread_environment`` stays +#: compared, including ``blas_threads_in_use``: on Linux the OpenBLAS count +#: changes output bytes, and with no thread variable set it follows the host's +#: CPUs, so a resume on a host where OpenBLAS uses a different count is refused. _RESUME_IGNORED_RUN_CONFIG_PATHS = ( ("thread_environment", "POPULACE_FIT_N_JOBS"), ("thread_environment", "POPULACE_FIT_PREDICT_WORKERS"), ) +def _blas_threads_in_use() -> list[list[object]]: + """Each loaded BLAS library, as ``[name, thread count]``, in sorted order. + + threadpoolctl reads the counts from the libraries themselves, so this holds + whatever chose them: a thread variable, ``MICROCOSM_THREADS`` or, with + neither, the CPUs OpenBLAS found on the host. It does not report Apple's + Accelerate, so on macOS the list is empty. + """ + + return sorted( + [pool["internal_api"], pool["num_threads"]] + for pool in threadpool_info() + if pool["user_api"] == "blas" + ) + + def _open_stage_runtime(args: argparse.Namespace) -> StageRuntime: """Open the checkpoint directory, refusing a resume with changed settings.""" @@ -1317,6 +1335,7 @@ def path(value: Path | None) -> str | None: else os.environ.get(name) ) for name in ( + "MICROCOSM_THREADS", "OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", @@ -1328,6 +1347,7 @@ def path(value: Path | None) -> str | None: "PYTHONHASHSEED", ) } + thread_environment["blas_threads_in_use"] = _blas_threads_in_use() config: dict[str, object] = { "allow_geography_ladder_gate_failures": bool( args.allow_geography_ladder_gate_failures diff --git a/tools/us_build_thread_environment.py b/tools/us_build_thread_environment.py index f205862ede..11a95a3835 100644 --- a/tools/us_build_thread_environment.py +++ b/tools/us_build_thread_environment.py @@ -1,91 +1,96 @@ -"""Name the thread counts of the US base and ACS staging build commands. - -The commands call :func:`set_build_thread_environment` before numpy loads, so -this module uses only the standard library. Each BLAS and numexpr variable gets -the count its library already uses when the variable is unset: - -- On Linux the OpenBLAS thread count changes output bytes. OpenBLAS splits a - large dot product between its threads, and the order of the additions moves - the last bits of the sum. Keeping the count keeps the bytes. -- The base command records these variables in its run configuration and compares - them on resume. With real counts recorded, it refuses a resume on a host with a - different count, which two unset values could not show. - -This limits nothing: the counts have no upper limit, and OpenMP and BLAS follow -CPU affinity but not a CPU quota. Setting ``OMP_NUM_THREADS`` does change two -other counts. scikit-learn then uses that value instead of its physical-core -count limited by a CPU quota and ``LOKY_MAX_CPU_COUNT``, and torch uses it too. +"""The one thread setting of the US build commands, ``MICROCOSM_THREADS``. + +An operator who wants to choose the thread count of the US release, base and +ACS staging commands sets ``MICROCOSM_THREADS`` to a positive whole number. +Each command calls :func:`set_build_thread_environment` before numpy loads, +because the libraries read their variables when they load, so this module uses +only the standard library. It copies the count into every variable in +``FILLED_VARIABLES`` that is unset or blank. A variable that already has a +value keeps it. + +Without the setting, the base and ACS staging commands set nothing, and each +library chooses its own count as it always has. The release tool passes its +own default instead, ``min(os.cpu_count(), 16)``. + +On Linux the OpenBLAS thread count changes output bytes: OpenBLAS splits a +large dot product between its threads, and the order of the additions moves +the last bits of the sum. So a build's output matches one made without the +setting only when the count equals the CPUs OpenBLAS would otherwise use. """ from __future__ import annotations import os -from collections.abc import MutableMapping - -#: The most threads numexpr starts when nothing configures it. -NUMEXPR_UNCONFIGURED_THREAD_LIMIT = 16 - -__all__ = ["NUMEXPR_UNCONFIGURED_THREAD_LIMIT", "set_build_thread_environment"] - - -def _count_or_default(setting: str | None, default: str | None) -> str | None: - """The count to copy from ``setting``, or ``default`` if it is unset or blank. - - Only a plain positive integer is copied. Libraries read other spellings - differently (OpenBLAS takes ``4`` from ``4,2`` and numexpr refuses it), so - for those this returns None and the variable that would copy the value stays - unset, leaving each library to read ``setting`` as it does today. +from collections.abc import Mapping, MutableMapping + +#: The variable that holds the one thread count. +THREAD_SETTING = "MICROCOSM_THREADS" + +#: The variables the thread setting fills, with what reads each one. +FILLED_VARIABLES = ( + # OpenMP: scikit-learn's sign classifier and torch. OpenBLAS and numexpr + # read it when their own variable is unset. scikit-learn stops limiting + # itself to physical cores, a CPU quota and LOKY_MAX_CPU_COUNT once it is + # set. + "OMP_NUM_THREADS", + # OpenBLAS, which numpy and scipy bundle on Linux. It reads this before + # its older name, GOTO_NUM_THREADS. + "OPENBLAS_NUM_THREADS", + # Intel MKL, which only torch bundles here. torch also takes its own + # thread count from it. + "MKL_NUM_THREADS", + # BLIS, which nothing installed here uses. + "BLIS_NUM_THREADS", + # Apple's Accelerate, which numpy uses on macOS. + "VECLIB_MAXIMUM_THREADS", + # numexpr, which pandas uses for large element-wise arithmetic. + "NUMEXPR_NUM_THREADS", + # The limit on joblib.cpu_count(), which sizes the QRF's tree-building + # jobs and prediction workers when POPULACE_FIT_* are unset. + "LOKY_MAX_CPU_COUNT", +) + +__all__ = [ + "FILLED_VARIABLES", + "THREAD_SETTING", + "set_build_thread_environment", + "thread_setting", +] + + +def thread_setting(environment: Mapping[str, str] = os.environ) -> int | None: + """The count in ``MICROCOSM_THREADS``, or None if it is unset or blank. + + Only a plain positive whole number is accepted. Anything else is refused + rather than ignored, because the operator asked for a count. """ - if not setting: - return default - if setting.isascii() and setting.isdigit() and int(setting) > 0: - return str(int(setting)) - return None + value = environment.get(THREAD_SETTING, "") + if value == "": + return None + if value.isascii() and value.isdigit() and int(value) > 0: + return int(value) + raise ValueError( + f"{THREAD_SETTING} must be a positive whole number of threads, got {value!r}" + ) def set_build_thread_environment( environment: MutableMapping[str, str] = os.environ, + *, + default_count: int | None = None, ) -> None: - """Give each unset OpenMP, BLAS and numexpr variable its current count. - - The count is ``OMP_NUM_THREADS`` when that is a plain count, otherwise the - CPUs this process may use. Two variables have other sources, because their - libraries do: + """Copy the thread setting, or ``default_count``, into each unset variable. - - OpenBLAS reads ``GOTO_NUM_THREADS`` before ``OMP_NUM_THREADS``. - - numexpr uses ``OMP_NUM_THREADS``, then ``NUMEXPR_MAX_THREADS``, and with - neither it counts the online CPUs, up to 16. It needs its own value here - because the ``OMP_NUM_THREADS`` set below would otherwise replace the - last two. - - A value already present is kept. A variable with no known count stays unset, - and its library keeps its own default. + With neither, nothing changes. A variable in ``FILLED_VARIABLES`` that + already has a non-blank value keeps it. """ - usable_cpus = os.process_cpu_count() - usable_count = None if usable_cpus is None else str(usable_cpus) - openmp_setting = environment.get("OMP_NUM_THREADS") - count = _count_or_default(openmp_setting, usable_count) - online_cpus = os.cpu_count() or usable_cpus - numexpr_default = ( - None - if online_cpus is None - else str(min(online_cpus, NUMEXPR_UNCONFIGURED_THREAD_LIMIT)) - ) - defaults = { - "OMP_NUM_THREADS": count, - "OPENBLAS_NUM_THREADS": _count_or_default( - environment.get("GOTO_NUM_THREADS"), count - ), - "MKL_NUM_THREADS": count, - "BLIS_NUM_THREADS": count, - "VECLIB_MAXIMUM_THREADS": count or usable_count, - "NUMEXPR_NUM_THREADS": _count_or_default( - openmp_setting, - _count_or_default(environment.get("NUMEXPR_MAX_THREADS"), numexpr_default), - ), - } - for name, value in defaults.items(): - if value is not None: - environment.setdefault(name, value) + count = thread_setting(environment) + if count is None: + count = default_count + if count is None: + return + for name in FILLED_VARIABLES: + if not environment.get(name): + environment[name] = str(count) diff --git a/uv.lock b/uv.lock index c123b9bea9..454b694da1 100644 --- a/uv.lock +++ b/uv.lock @@ -788,6 +788,7 @@ dependencies = [ { name = "pyyaml" }, { name = "referencing" }, { name = "scipy" }, + { name = "threadpoolctl" }, ] [package.optional-dependencies] @@ -839,6 +840,7 @@ requires-dist = [ { name = "scipy", specifier = ">=1.13" }, { name = "tables", marker = "extra == 'uk'", specifier = ">=3" }, { name = "tables", marker = "extra == 'us'", specifier = ">=3" }, + { name = "threadpoolctl", specifier = ">=3.1" }, ] provides-extras = ["us", "uk"] From 78699b813f1a79d39ac1f78dd23791daa56b332d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:02:42 +0400 Subject: [PATCH 05/10] Test the thread setting's review round 2 findings The commands must find the helper without their folder on the import path, the ACS local-release command applies the setting at start, a count above 64 raises numexpr's maximum, the release default keeps a blank variable, the library test needs two CPUs, and a Modal plan with an unusable MICROCOSM_THREADS is refused when it is loaded. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_build_tool_thread_defaults.py | 94 ++++++++++++++++--- .../us/test_us_modal_stage_plan_tool.py | 11 +++ 2 files changed, 91 insertions(+), 14 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py b/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py index 70d862be56..567a93e117 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py @@ -1,9 +1,10 @@ """The one thread setting of the US build commands, ``MICROCOSM_THREADS``. -When it is set, the release, base and ACS staging commands copy it into every -library's thread variable before numpy loads. When it is not, the base and ACS -staging commands set nothing, so each library keeps choosing its own count, -and the release tool keeps its default of ``min(os.cpu_count(), 16)``. +When it is set, the release, base, ACS staging and ACS local-release commands +copy it into every library's thread variable before numpy loads. When it is +not, all but the release tool set nothing, so each library keeps choosing its +own count, and the release tool keeps its default of +``min(os.cpu_count(), 16)``. Each process-level case starts a fresh interpreter: the settings depend on what the process has loaded and must not reach the process that runs the tests. @@ -29,7 +30,13 @@ BASE_TOOL = "tools/build_us_puf_support_base.py" ACS_STAGING_COMMAND = "tools/build_us_acs_multispine_base.py" ACS_STAGING_IMPLEMENTATION = "tools/_legacy/build_us_acs_multispine_base.py" -BUILD_COMMANDS = (BASE_TOOL, ACS_STAGING_COMMAND, ACS_STAGING_IMPLEMENTATION) +ACS_LOCAL_RELEASE = "tools/build_us_acs_local_release.py" +BUILD_COMMANDS = ( + BASE_TOOL, + ACS_STAGING_COMMAND, + ACS_STAGING_IMPLEMENTATION, + ACS_LOCAL_RELEASE, +) EVERY_COMMAND = (*BUILD_COMMANDS, RELEASE_TOOL) THREAD_SETTING = "MICROCOSM_THREADS" @@ -39,6 +46,7 @@ BLIS = "BLIS_NUM_THREADS" VECLIB = "VECLIB_MAXIMUM_THREADS" NUMEXPR = "NUMEXPR_NUM_THREADS" +NUMEXPR_MAXIMUM = "NUMEXPR_MAX_THREADS" JOBLIB_LIMIT = "LOKY_MAX_CPU_COUNT" FILLED_VARIABLES = (OPENMP, OPENBLAS, MKL, BLIS, VECLIB, NUMEXPR, JOBLIB_LIMIT) QRF_VARIABLES = ("POPULACE_FIT_N_JOBS", "POPULACE_FIT_PREDICT_WORKERS") @@ -47,7 +55,7 @@ THREAD_SETTING, *FILLED_VARIABLES, "GOTO_NUM_THREADS", - "NUMEXPR_MAX_THREADS", + NUMEXPR_MAXIMUM, *QRF_VARIABLES, ) @@ -133,6 +141,26 @@ def test_the_thread_setting_has_no_upper_limit(helper: ModuleType) -> None: assert environment == {THREAD_SETTING: "64", **_every_variable("64")} +def test_a_count_above_numexpr_s_default_maximum_also_raises_it( + helper: ModuleType, +) -> None: + """numexpr refuses a count above NUMEXPR_MAX_THREADS (64 by default).""" + + environment = _filled(helper, {THREAD_SETTING: "96"}) + + assert environment == { + THREAD_SETTING: "96", + **_every_variable("96"), + NUMEXPR_MAXIMUM: "96", + } + + +def test_a_numexpr_maximum_already_set_is_kept(helper: ModuleType) -> None: + environment = _filled(helper, {THREAD_SETTING: "96", NUMEXPR_MAXIMUM: "100"}) + + assert environment[NUMEXPR_MAXIMUM] == "100" + + def test_leading_zeros_are_dropped_from_the_copies(helper: ModuleType) -> None: environment = _filled(helper, {THREAD_SETTING: "007"}) @@ -176,6 +204,14 @@ def test_the_default_count_applies_without_the_thread_setting( assert _filled(helper, default_count=16) == _every_variable("16") +def test_the_default_count_keeps_a_blank_variable(helper: ModuleType) -> None: + """The release tool's default has always left a blank value as it was.""" + + environment = _filled(helper, {OPENMP: ""}, default_count=16) + + assert environment == _every_variable("16", **{OPENMP: ""}) + + def test_the_thread_setting_replaces_the_default_count(helper: ModuleType) -> None: environment = _filled(helper, {THREAD_SETTING: "3"}, default_count=16) @@ -195,10 +231,11 @@ def test_a_second_call_changes_nothing(helper: ModuleType) -> None: # When the commands apply them # --------------------------------------------------------------------------- -#: Starts one tool under ``runpy`` and stops it at its first import of a -#: numerical library, printing the environment and import path at that moment. -#: The tool's imports never finish, so a case costs no more than the code -#: before them. +#: Starts one tool under ``runpy`` from the repository root, without its folder +#: on the import path (as ``python -P`` or ``PYTHONSAFEPATH`` would), and stops +#: it at its first import of a numerical library, printing the environment and +#: import path at that moment. The tool's imports never finish, so a case costs +#: no more than the code before them. _START_PROBE = """ import json import os @@ -225,7 +262,6 @@ def find_spec(self, name, path=None, target=None): cpu_count = int(sys.argv[3]) os.cpu_count = lambda: cpu_count os.process_cpu_count = lambda: cpu_count -sys.path.insert(0, str(tool.parent)) path_before = list(sys.path) sys.argv = [str(tool), "--help"] sys.meta_path.insert(0, StopAtNumericalLibrary()) @@ -282,14 +318,15 @@ def test_a_started_command_sets_nothing_without_the_thread_setting( def test_a_started_command_fills_every_variable_before_numerical_imports( tool: str, ) -> None: - environment = _state_at_first_numerical_import( + state = _state_at_first_numerical_import( tool, cpu_count=32, settings={THREAD_SETTING: "5"} - )["environment"] + ) - assert _thread_variables_in(environment) == { + assert _thread_variables_in(state["environment"]) == { THREAD_SETTING: "5", **_every_variable("5"), } + assert state["path_unchanged"] @pytest.mark.parametrize("tool", EVERY_COMMAND) @@ -401,6 +438,10 @@ def test_importing_the_release_tool_still_applies_its_default() -> None: """ +@pytest.mark.skipif( + (os.process_cpu_count() or 1) < 2, + reason="OpenBLAS and joblib use no more threads than the CPUs available", +) def test_the_thread_setting_reaches_every_library() -> None: counts = _last_json_line( [sys.executable, "-c", _THREAD_COUNT_PROBE], @@ -416,6 +457,31 @@ def test_the_thread_setting_reaches_every_library() -> None: } +_NUMEXPR_PROBE = """ +import json +import sys + +sys.path.insert(0, "tools") +from us_build_thread_environment import set_build_thread_environment + +set_build_thread_environment() + +import numexpr + +print() +print(json.dumps({"numexpr": numexpr.utils.get_num_threads()})) +""" + + +def test_numexpr_takes_a_count_above_its_default_maximum() -> None: + counts = _last_json_line( + [sys.executable, "-c", _NUMEXPR_PROBE], + _clean_environment({THREAD_SETTING: "96"}), + ) + + assert counts == {"numexpr": 96} + + _SIGN_CLASSIFIER_PROBE = """ import hashlib import json diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py index 944df1ac3d..07ef95620c 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py @@ -2691,6 +2691,17 @@ def test_a_plan_may_set_the_telemetry_requirement_only_to_0(value: str) -> None: assert dict(plan_lib.parse_plan(_plan_data(env=env)).env) == env +@pytest.mark.parametrize("value", ["0", "-1", "+4", " 3 ", "4.0", "four"]) +def test_a_plan_s_thread_setting_must_be_a_positive_whole_number(value: str) -> None: + # The base tool's check step loads it without running its start-up step, + # so a bad value would otherwise stop the run only after the runner had + # staged the inputs. + with pytest.raises(plan_lib.PlanError, match="MICROCOSM_THREADS"): + plan_lib.parse_plan(_plan_data(env={"MICROCOSM_THREADS": value})) + env = {"MICROCOSM_THREADS": "4"} + assert dict(plan_lib.parse_plan(_plan_data(env=env)).env) == env + + def test_the_tool_gets_the_collector_token_only_from_the_runner_s_secret() -> None: assert dict(plan_lib.RUNNER_TOKEN_SECRET_ENV) == dict( zip(RUNNER_TOKEN_SECRET, COLLECTOR_TOKEN_NAMES, strict=True) From d2c0d8f78c35a3eb1044fa0efefa051f08a25cff Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:06:51 +0400 Subject: [PATCH 06/10] Address review round 2 of the thread setting - The base, ACS staging and new ACS local-release start-up steps load the helper from their own folder, so `python -m`, `python -P` and runpy starts work again. - The ACS local-release command applies MICROCOSM_THREADS before numpy loads; before, it read the setting only when it imported the release tool partway through a run. - A count above 64 also fills NUMEXPR_MAX_THREADS, since numexpr runs one thread when asked for more than its maximum. - The release tool's default keeps a blank variable, as it always has. - A Modal plan with an unusable MICROCOSM_THREADS is refused when loaded. - threadpoolctl>=3.6, which reads numpy 2's scipy-openblas library. - The runbook and changelog name every command that reads the setting, correct scikit-learn's, torch's and MKL's rules, and say where the Linux byte measurements came from. Co-Authored-By: Claude Opus 5.5 --- .../us-build-thread-environment.changed.md | 4 +- docs/us-modal-stage-runbook.md | 125 +++++++++++------- packages/microcosm-build/pyproject.toml | 5 +- pyproject.toml | 6 +- tools/build_us_acs_local_release.py | 21 ++- tools/build_us_acs_multispine_base.py | 13 +- tools/build_us_puf_support_base.py | 15 ++- tools/modal_us_stage_plan.py | 27 ++++ tools/us_build_thread_environment.py | 56 +++++--- uv.lock | 2 +- 10 files changed, 188 insertions(+), 86 deletions(-) diff --git a/changelog.d/us-build-thread-environment.changed.md b/changelog.d/us-build-thread-environment.changed.md index b7f1a2a2a6..2a583b9622 100644 --- a/changelog.d/us-build-thread-environment.changed.md +++ b/changelog.d/us-build-thread-environment.changed.md @@ -1,3 +1,3 @@ -`MICROCOSM_THREADS` is the one thread setting of the US release, base and ACS multispine staging commands. When it is set to a positive whole number, each command copies it, before numpy loads, into every unset OpenMP, BLAS, numexpr and joblib thread variable (`OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `MKL_NUM_THREADS`, `BLIS_NUM_THREADS`, `VECLIB_MAXIMUM_THREADS`, `NUMEXPR_NUM_THREADS` and `LOKY_MAX_CPU_COUNT`). Variables already set keep their values, and a value that is not a positive whole number stops the command. Without it, the base and ACS staging commands set nothing and each library chooses its own count as before, and the release tool keeps its default of `min(os.cpu_count(), 16)`. +`MICROCOSM_THREADS` is the one thread setting of the US release, base, ACS multispine staging and ACS local-release commands. When it is set to a positive whole number, each command copies it, before numpy loads, into every unset or blank OpenMP, BLAS, numexpr and joblib thread variable (`OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `MKL_NUM_THREADS`, `BLIS_NUM_THREADS`, `VECLIB_MAXIMUM_THREADS`, `NUMEXPR_NUM_THREADS` and `LOKY_MAX_CPU_COUNT`, and `NUMEXPR_MAX_THREADS` above 64). Variables already set keep their values. A value that is not a positive whole number stops the command, and a Modal plan that sets one is refused when it is loaded. Commands that import the release tool, such as the exact-k ladder, certification and scoring tools, read the setting at that import. Without it, the base, ACS staging and ACS local-release commands set nothing and each library chooses its own count as before, and the release tool keeps its default of `min(os.cpu_count(), 16)`, which still leaves a blank variable as it is. -On Linux the OpenBLAS thread count changes output bytes, so the base command now records `MICROCOSM_THREADS` and each loaded BLAS library's thread count (`blas_threads_in_use`, from threadpoolctl) in `thread_environment`, and a resume with different values is refused, including one on a host where OpenBLAS would use a different count. +On Linux the OpenBLAS thread count can change output bytes, so the base command now records `MICROCOSM_THREADS` and each loaded BLAS library's thread count (`blas_threads_in_use`, from threadpoolctl) in `thread_environment`, and a resume with different values is refused, including one on a host where OpenBLAS would use a different count. diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index 57383fdd4d..c95d7a7b7d 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -397,21 +397,22 @@ that release's current build. ## Thread variables -`MICROCOSM_THREADS` is the one thread setting of three US commands: the release -command (`tools/build_us_fiscal_refresh_release.py`), the base command -(`tools/build_us_puf_support_base.py`) and the ACS multispine staging command +`MICROCOSM_THREADS` is the one thread setting of the US build commands: the +release command (`tools/build_us_fiscal_refresh_release.py`), the base command +(`tools/build_us_puf_support_base.py`), the ACS multispine staging command (`tools/build_us_acs_multispine_base.py`, and -`tools/_legacy/build_us_acs_multispine_base.py` when that file is run directly). -Set it to a positive whole number to choose the thread count of every numerical -library these commands use. Before numpy loads, `tools/us_build_thread_environment.py` +`tools/_legacy/build_us_acs_multispine_base.py` when that file is run directly) +and the ACS local-release command (`tools/build_us_acs_local_release.py`). Set it +to a positive whole number to set the thread count of every numerical library +these commands use. Before numpy loads, `tools/us_build_thread_environment.py` copies it into each of these variables that is unset or blank: - `OMP_NUM_THREADS`: OpenMP, which scikit-learn's QRF sign classifier and torch use. OpenBLAS and numexpr read it when their own variable is unset. - `OPENBLAS_NUM_THREADS`: OpenBLAS, which numpy and scipy bundle on Linux. It reads this before its older name, `GOTO_NUM_THREADS`. -- `MKL_NUM_THREADS`: Intel MKL, which only torch bundles here. torch also takes - its own thread count from it. +- `MKL_NUM_THREADS`: Intel MKL, which torch's Linux x86-64 builds include. torch + also takes its own thread count from it, ahead of `OMP_NUM_THREADS`. - `BLIS_NUM_THREADS`: BLIS, which nothing installed here uses. - `VECLIB_MAXIMUM_THREADS`: Apple's Accelerate, which numpy uses on macOS. - `NUMEXPR_NUM_THREADS`: numexpr, which pandas uses for large element-wise @@ -420,40 +421,57 @@ copies it into each of these variables that is unset or blank: tree-building jobs and prediction workers while `POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS` are unset. +numexpr refuses a count above `NUMEXPR_MAX_THREADS`, 64 by default, and then runs +one thread, so a count above 64 also fills `NUMEXPR_MAX_THREADS`. Some libraries +use fewer threads than they are given: OpenBLAS no more than the CPUs it may run +on, and `joblib.cpu_count()` no more than CPU affinity and a CPU quota allow. + A variable that already has a value keeps it, so one library's count can still be set directly. A setting that is not a positive whole number, such as `0`, `+4` or -`four`, stops the command before numpy loads. The base and ACS staging commands +`four`, stops the command before numpy loads, and a Modal plan that sets one is +refused when it is loaded. The base, ACS staging and ACS local-release commands read the setting only when started as commands, not when imported. -`tools/build_us_acs_local_release.py` does not read it. -**Without the setting.** The base and ACS staging commands set nothing, and each -library chooses its own count, as before: +The release tool's step runs on import too, as it always has, so other commands +that import it read the setting at that import. `build_us_exact_k_ladder_release.py`, +`certify_us_national_build.py`, `score_us_fiscal_targets.py` and +`score_us_release_head_to_head.py` import it before numpy loads. Code that +imports it later, such as the release-gate preflight +(`microcosm.build.us_runtime.release_gate_preflight`), applies it only to the +libraries it loads afterwards and to its child processes, and a setting that is +not a positive whole number stops it at that import. + +**Without the setting.** The base, ACS staging and ACS local-release commands set +nothing, and each library chooses its own count, as before: - OpenBLAS and OpenMP use the CPUs the process may run on (its CPU affinity). They do not follow a CPU quota. -- scikit-learn uses at most the physical cores, a CPU quota allows and - `LOKY_MAX_CPU_COUNT` allows. torch uses the physical cores (on Apple chips, the - performance cores). +- scikit-learn uses the smaller of OpenMP's count and `joblib.cpu_count()`, which + is the smallest of CPU affinity, a CPU quota and `LOKY_MAX_CPU_COUNT`. When none + of those is below the logical CPU count, it uses the physical cores instead. +- torch uses the physical cores (on Apple chips, the performance cores). - numexpr uses the online CPUs, up to 16. - `joblib.cpu_count()`, and with it the QRF's pools, follows CPU affinity, a CPU quota and `LOKY_MAX_CPU_COUNT`. -The release tool instead fills the same variables with `min(os.cpu_count(), 16)`, -as it did before for all of them but `BLIS_NUM_THREADS`, which has no effect here. -It does this on import too, as it always has. Its calibration's exact weights -depend on torch's thread count, so that default stays. +The ACS local-release command later imports the release tool, which then fills +the variables still unset with the release default, as before. The release tool +fills them with `min(os.cpu_count(), 16)`, as it did before for all of them but +`BLIS_NUM_THREADS`, which has no effect here. As before, it keeps a blank value; +only `MICROCOSM_THREADS` replaces a blank. Its calibration's exact weights depend +on torch's thread count, so that default stays. -**On Linux the BLAS thread count changes output bytes.** numpy's Linux wheels use -OpenBLAS, which splits a large dot product between its threads, so the order of -the additions, and with it the last bits of the sum, depends on the count. +**On Linux the BLAS thread count can change output bytes.** numpy's Linux wheels +use OpenBLAS, which splits a large dot product between its threads, so the order +of the additions, and with it the last bits of the sum, depends on the count. Setting only `OMP_NUM_THREADS` has the same effect, because OpenBLAS follows it. -In Linux containers (x86-64 under emulation and arm64, 10 CPUs visible, numpy -2.4.6), `np.dot` and `@` on vectors of 20,000 to 500,000 rows gave different -results at 1, 2, 4, 8 and 10 threads, and `_project_weighted_sum_to_bounds` on -150,000 rows wrote different bytes at 1, 2 and 4 threads than at 10. These were -small synthetic checks, not full builds. The same checks on macOS, where numpy -uses Accelerate, showed no difference. The affected operations reach, for -example: +In container probes on 18 November 2026, whose results are not kept in the +repository (x86-64 under emulation and arm64, 10 CPUs visible, numpy 2.4.6), +`np.dot` and `@` on vectors of 20,000 to 500,000 rows gave different results at +1, 2, 4, 8 and 10 threads, and `_project_weighted_sum_to_bounds` on 150,000 rows +wrote different bytes at 1, 2 and 4 threads than at 10. These were small +synthetic checks, not full builds. The same checks on macOS, where numpy uses +Accelerate, showed no difference. The affected operations reach, for example: - the ESI premium stage (`esi_premiums.py`), which scales a person column by a weighted total; @@ -462,10 +480,10 @@ example: - cross-fitted calibration of the QRF sign classifier (`microcosm.fit.qrf`), which uses `w @ ...` on row-length vectors. -So a Linux base build's output depends on the OpenBLAS thread count. Without the -setting that count follows the host, so two hosts with different CPU counts can -write different bytes, as before. A build made with `MICROCOSM_THREADS=N` matches -one made without it only where OpenBLAS would otherwise use N threads. +So a Linux base build's output can depend on the OpenBLAS thread count. Without +the setting that count follows the host, so two hosts with different CPU counts +can write different bytes, as before. A build made with `MICROCOSM_THREADS=N` can +match one made without it only where OpenBLAS would otherwise use N threads. **Other effects of the setting.** Because it sets `OMP_NUM_THREADS`, scikit-learn no longer limits itself to physical cores, a CPU quota or `LOKY_MAX_CPU_COUNT`: @@ -483,22 +501,29 @@ values do not depend on those counts. `VECLIB_MAXIMUM_THREADS`, `NUMEXPR_NUM_THREADS`, `POPULACE_FIT_N_JOBS`, `POPULACE_FIT_PREDICT_WORKERS` and `PYTHONHASHSEED`. It also records `blas_threads_in_use`: each loaded BLAS library with the thread count it uses - once numpy has loaded, as `threadpoolctl` reports it. threadpoolctl does not - report Accelerate, so on macOS the list is empty. + once numpy has loaded, as `threadpoolctl` reads it from the library. That count + does not come from the environment. threadpoolctl does not report Accelerate, + so where numpy uses Accelerate, as on macOS, the list is empty. - *A resume of the base command* compares all of these except `POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS`, and refuses a difference, so a new thread setting needs a new checkpoint directory. Because `blas_threads_in_use` is compared, a resume is also refused on a host where OpenBLAS would use a different count. Before, with the variables unset on both hosts, the configurations matched. -- *`POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS`:* recorded and not - compared. A new value applies from the next outer stage of a resumed run. - `LOKY_MAX_CPU_COUNT` is not recorded. None of the three changes an imputed value. +- *`POPULACE_FIT_N_JOBS`, `POPULACE_FIT_PREDICT_WORKERS` and + `LOKY_MAX_CPU_COUNT`:* the first two are recorded and not compared, and a new + value applies from the next outer stage of a resumed run. `LOKY_MAX_CPU_COUNT` + is not recorded. The QRF counts these set change no imputed value. While + `OMP_NUM_THREADS` is unset, `LOKY_MAX_CPU_COUNT` also limits the sign + classifier's OpenMP count (see "Without the setting"). +- *The helper's own file* is not in the digest of the tool's code + (`builder_code_identity`), but the values it sets are recorded and compared. - *Base runs started before this change:* they cannot resume after it. The run configuration holds a digest that covers the tool's own file (`builder_code_identity`), and the file changed. -- *ACS multispine staging command:* it keeps no run configuration, so the values - apply to the process that was started. +- *ACS staging and ACS local-release commands:* the staging command keeps no run + configuration, so the values apply to the process that was started. The + local-release command's stage settings check does not record thread variables. **On Modal.** A plan may set `MICROCOSM_THREADS`, because its environment allowlist accepts `MICROCOSM_*` names, and it may set `OMP_NUM_THREADS`, @@ -512,10 +537,11 @@ allowlist accepts `MICROCOSM_*` names, and it may set `OMP_NUM_THREADS`, Because a value already set is kept, a plan's `MICROCOSM_THREADS` does not replace those four. It fills only `VECLIB_MAXIMUM_THREADS`, `NUMEXPR_NUM_THREADS` and `LOKY_MAX_CPU_COUNT`. To change the BLAS and OpenMP counts on Modal, a plan -sets those variables directly, as before. No record shows what Modal sets in the -`acs-staging` class. The tools at `4b57d15a2` and `74f5e6123`, the commits pinned -by the historical base plan and the ACS staging plan, predate the setting and -ignore it. +sets those variables directly, as before; torch follows `MKL_NUM_THREADS` before +`OMP_NUM_THREADS`, so changing only the latter leaves torch at Modal's value. No +record shows what Modal sets in the `acs-staging` class. The tools at `4b57d15a2` +and `74f5e6123`, the commits pinned by the historical base plan and the ACS +staging plan, predate the setting and ignore it. ## Resources and cost @@ -1449,10 +1475,13 @@ Two things are reported and never refused: the interpreter string (`python`) and every other `thread_environment` variable whose value differs (`thread_environment_differences`). The tool reads those variables from its environment, and Modal sets some of them itself (see "Resources"). -These differences are reported and not refused, although a different BLAS or -OpenMP count can change output bytes on Linux (see "Thread variables"). That -includes `blas_threads_in_use`, which is empty for a macOS run. Only the -checkpoint digests compared above show that outputs agree. The report says +Code that records `blas_threads_in_use` reads that one from the loaded BLAS +libraries instead. These differences are reported and not refused, although a +different BLAS or OpenMP count can change output bytes on Linux (see "Thread +variables"). `blas_threads_in_use` is an empty list for a run where numpy uses +Accelerate, as on macOS, and is absent from a reference made with code that does +not record it, such as `4b57d15a2`. Only the checkpoint digests compared above +show that outputs agree. The report says `compared_outputs_match`, with `stages_compared` 2 of `stages_total` 24 and the 22 stages it did not compare (`stages_not_compared`). diff --git a/packages/microcosm-build/pyproject.toml b/packages/microcosm-build/pyproject.toml index fb8df9f66e..66412210a9 100644 --- a/packages/microcosm-build/pyproject.toml +++ b/packages/microcosm-build/pyproject.toml @@ -31,8 +31,9 @@ dependencies = [ # own version, and every emitter release accepts the versions in use. "microcosm-emitter-interface>=0.16.0,<1", # The US base command records each loaded BLAS library's thread count in - # its run configuration. scikit-learn already depends on it. - "threadpoolctl>=3.1", + # its run configuration. scikit-learn already depends on it; 3.6 reads + # the scipy-openblas library that numpy 2 wheels bundle. + "threadpoolctl>=3.6", ] [project.optional-dependencies] diff --git a/pyproject.toml b/pyproject.toml index 88c518e863..82578f7218 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,11 +43,13 @@ ignore = ["E501"] # defaults before numpy/torch load, which requires statements above the # import block. "tools/build_us_fiscal_refresh_release.py" = ["E402"] -# The base and ACS staging commands apply the thread setting before numpy -# loads (tools/us_build_thread_environment.py), for the same reason. +# The base, ACS staging and ACS local-release commands apply the thread +# setting before numpy loads (tools/us_build_thread_environment.py), for the +# same reason. "tools/build_us_puf_support_base.py" = ["E402"] "tools/build_us_acs_multispine_base.py" = ["E402"] "tools/_legacy/build_us_acs_multispine_base.py" = ["E402"] +"tools/build_us_acs_local_release.py" = ["E402"] # Evidence scripts are frozen receipts of one-off measurements: formatted and # import-sorted, but their logic stays exactly as it produced the committed # outputs, so style rules that would edit that logic are waived. diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index a92d124e92..3a136aee18 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -111,6 +111,25 @@ from __future__ import annotations +import sys +from pathlib import Path + +if __name__ == "__main__": + # The one thread setting, MICROCOSM_THREADS, fills the OpenMP, BLAS, + # numexpr and joblib thread variables, and the libraries read those when + # they load, so this comes before numpy + # (tools/us_build_thread_environment.py). Without the setting nothing is + # set here; the release tool, imported later, fills what is still unset + # with its own default, as before. This runs only for the command: tests + # import this file. The helper is loaded from this file's folder, which is + # not on the import path under ``python -m`` or ``python -P``. E402 is + # ignored for this file in pyproject for this block. + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from us_build_thread_environment import set_build_thread_environment + + del sys.path[0] + set_build_thread_environment() + import argparse import gc import hashlib @@ -118,13 +137,11 @@ import resource import shutil import subprocess -import sys import threading import time from collections import defaultdict from contextlib import contextmanager from datetime import UTC, datetime -from pathlib import Path import numpy as np import pandas as pd diff --git a/tools/build_us_acs_multispine_base.py b/tools/build_us_acs_multispine_base.py index c5f2dd9663..3551384df8 100644 --- a/tools/build_us_acs_multispine_base.py +++ b/tools/build_us_acs_multispine_base.py @@ -8,21 +8,26 @@ from __future__ import annotations +import sys +from pathlib import Path + if __name__ == "__main__": # The one thread setting, MICROCOSM_THREADS, fills the OpenMP, BLAS, # numexpr and joblib thread variables, and the libraries read those when # they load. The imports below load numpy before the implementation file # does, so this comes first. Without the setting nothing is set. This runs - # only for the command: tests and other tools import this file. E402 is - # ignored for this file in pyproject for this block. + # only for the command: tests and other tools import this file. The helper + # is loaded from this file's folder, which is not on the import path under + # ``python -m`` or ``python -P``. E402 is ignored for this file in + # pyproject for this block. + sys.path.insert(0, str(Path(__file__).resolve().parent)) from us_build_thread_environment import set_build_thread_environment + del sys.path[0] set_build_thread_environment() import importlib.util -import sys import warnings -from pathlib import Path from types import ModuleType from microcosm.build.us_runtime.h5_io import ( diff --git a/tools/build_us_puf_support_base.py b/tools/build_us_puf_support_base.py index 821aeea0f0..6d667a310f 100644 --- a/tools/build_us_puf_support_base.py +++ b/tools/build_us_puf_support_base.py @@ -18,16 +18,23 @@ from __future__ import annotations +import sys +from pathlib import Path + if __name__ == "__main__": # The one thread setting, MICROCOSM_THREADS, fills the OpenMP, BLAS, # numexpr and joblib thread variables, and the libraries read those when # they load, so this comes before numpy. Without the setting nothing is # set. It runs only for the command: tests and other tools import this - # file. Stage subprocesses inherit the values, and the run configuration - # records them (``_stage_run_config``). E402 is ignored for this file in - # pyproject for this block. + # file. The helper is loaded from this file's folder, which is not on the + # import path under ``python -m`` or ``python -P``. Stage subprocesses + # inherit the values, and the run configuration records them, except + # LOKY_MAX_CPU_COUNT (``_stage_run_config``). E402 is ignored for this + # file in pyproject for this block. + sys.path.insert(0, str(Path(__file__).resolve().parent)) from us_build_thread_environment import set_build_thread_environment + del sys.path[0] set_build_thread_environment() import argparse @@ -36,11 +43,9 @@ import os import shutil import subprocess -import sys from collections.abc import Callable, Iterator, Mapping, MutableMapping, Sequence from contextlib import contextmanager from dataclasses import replace -from pathlib import Path import numpy as np import pandas as pd diff --git a/tools/modal_us_stage_plan.py b/tools/modal_us_stage_plan.py index 3385708954..bf350955b9 100644 --- a/tools/modal_us_stage_plan.py +++ b/tools/modal_us_stage_plan.py @@ -172,6 +172,29 @@ "NUMEXPR_NUM_THREADS", "BLIS_NUM_THREADS", ) +#: The one thread setting of the US build commands, which fills the variables +#: above and a few more (tools/us_build_thread_environment.py; this module +#: imports nothing from the workspace, so its rule is repeated here). A plan's +#: value is checked when the plan is loaded: the base tool's check step loads +#: the tool without running its start-up step, so the tool itself would refuse +#: a bad value only after the runner had staged the inputs. +THREAD_SETTING_ENV = "MICROCOSM_THREADS" + + +def _thread_setting_problem(value: str) -> str | None: + """Why ``value`` is not a usable MICROCOSM_THREADS, or None if it is. + + A blank value means unset, as it does to the tools. + """ + + if value == "" or (value.isascii() and value.isdigit() and int(value) > 0): + return None + return ( + f"env {THREAD_SETTING_ENV!r} must be a positive whole number of threads, " + f"got {value!r}" + ) + + #: PYTHONUNBUFFERED is allowed so a plan can match a local run's environment #: exactly (Route A's base ran with only PYTHONUNBUFFERED=1). It changes when #: log lines reach the runner, not what the tool computes. @@ -1637,6 +1660,10 @@ def parse_plan(data: object) -> Plan: raise PlanError(f"env {key!r} must be a string") if key == TELEMETRY_REQUIRED_ENV and raw_env[key] != "0": raise PlanError(_telemetry_setting_refusal(raw_env[key])) + if key == THREAD_SETTING_ENV: + problem = _thread_setting_problem(raw_env[key]) + if problem is not None: + raise PlanError(problem) env[key] = raw_env[key] max_wall = data.get("max_wall_seconds") diff --git a/tools/us_build_thread_environment.py b/tools/us_build_thread_environment.py index 11a95a3835..a49653a24a 100644 --- a/tools/us_build_thread_environment.py +++ b/tools/us_build_thread_environment.py @@ -1,20 +1,20 @@ """The one thread setting of the US build commands, ``MICROCOSM_THREADS``. -An operator who wants to choose the thread count of the US release, base and -ACS staging commands sets ``MICROCOSM_THREADS`` to a positive whole number. -Each command calls :func:`set_build_thread_environment` before numpy loads, -because the libraries read their variables when they load, so this module uses -only the standard library. It copies the count into every variable in -``FILLED_VARIABLES`` that is unset or blank. A variable that already has a +An operator who wants to set the thread count of the US release, base, ACS +staging and ACS local-release commands sets ``MICROCOSM_THREADS`` to a positive +whole number. Each command calls :func:`set_build_thread_environment` before +numpy loads, because the libraries read their variables when they load, so this +module uses only the standard library. It copies the count into every variable +in ``FILLED_VARIABLES`` that is unset or blank. A variable that already has a value keeps it. -Without the setting, the base and ACS staging commands set nothing, and each -library chooses its own count as it always has. The release tool passes its -own default instead, ``min(os.cpu_count(), 16)``. +Without the setting, the base, ACS staging and ACS local-release commands set +nothing, and each library chooses its own count as it always has. The release +tool passes its own default instead, ``min(os.cpu_count(), 16)``. -On Linux the OpenBLAS thread count changes output bytes: OpenBLAS splits a +On Linux the OpenBLAS thread count can change output bytes: OpenBLAS splits a large dot product between its threads, and the order of the additions moves -the last bits of the sum. So a build's output matches one made without the +the last bits of the sum. So a build's output can match one made without the setting only when the count equals the CPUs OpenBLAS would otherwise use. """ @@ -29,15 +29,16 @@ #: The variables the thread setting fills, with what reads each one. FILLED_VARIABLES = ( # OpenMP: scikit-learn's sign classifier and torch. OpenBLAS and numexpr - # read it when their own variable is unset. scikit-learn stops limiting - # itself to physical cores, a CPU quota and LOKY_MAX_CPU_COUNT once it is - # set. + # read it when their own variable is unset. Once it is set, scikit-learn + # stops limiting itself to physical cores, a CPU quota and + # LOKY_MAX_CPU_COUNT. "OMP_NUM_THREADS", # OpenBLAS, which numpy and scipy bundle on Linux. It reads this before - # its older name, GOTO_NUM_THREADS. + # its older name, GOTO_NUM_THREADS, and uses no more threads than the CPUs + # it may run on. "OPENBLAS_NUM_THREADS", - # Intel MKL, which only torch bundles here. torch also takes its own - # thread count from it. + # Intel MKL, which torch's Linux x86-64 builds include. torch also takes + # its own thread count from it, ahead of OMP_NUM_THREADS. "MKL_NUM_THREADS", # BLIS, which nothing installed here uses. "BLIS_NUM_THREADS", @@ -50,8 +51,16 @@ "LOKY_MAX_CPU_COUNT", ) +#: numexpr's maximum thread count when ``NUMEXPR_MAX_THREADS`` is unset. It +#: refuses a larger count and runs one thread, so a larger count fills that +#: variable too. +NUMEXPR_DEFAULT_MAXIMUM = 64 +NUMEXPR_MAXIMUM_VARIABLE = "NUMEXPR_MAX_THREADS" + __all__ = [ "FILLED_VARIABLES", + "NUMEXPR_DEFAULT_MAXIMUM", + "NUMEXPR_MAXIMUM_VARIABLE", "THREAD_SETTING", "set_build_thread_environment", "thread_setting", @@ -83,14 +92,21 @@ def set_build_thread_environment( """Copy the thread setting, or ``default_count``, into each unset variable. With neither, nothing changes. A variable in ``FILLED_VARIABLES`` that - already has a non-blank value keeps it. + already has a value keeps it. A blank value counts as unset for the thread + setting, which libraries also read as unset. ``default_count`` keeps a blank + value, as the release tool's default always has. """ count = thread_setting(environment) + replaces_blank_values = count is not None if count is None: count = default_count if count is None: return - for name in FILLED_VARIABLES: - if not environment.get(name): + names = list(FILLED_VARIABLES) + if count > NUMEXPR_DEFAULT_MAXIMUM: + names.append(NUMEXPR_MAXIMUM_VARIABLE) + for name in names: + current = environment.get(name) + if current is None or (replaces_blank_values and current == ""): environment[name] = str(count) diff --git a/uv.lock b/uv.lock index 454b694da1..54a92f2487 100644 --- a/uv.lock +++ b/uv.lock @@ -840,7 +840,7 @@ requires-dist = [ { name = "scipy", specifier = ">=1.13" }, { name = "tables", marker = "extra == 'uk'", specifier = ">=3" }, { name = "tables", marker = "extra == 'us'", specifier = ">=3" }, - { name = "threadpoolctl", specifier = ">=3.1" }, + { name = "threadpoolctl", specifier = ">=3.6" }, ] provides-extras = ["us", "uk"] From fd3f0875fca29b23971e97e392fb479ee7316d01 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:29:35 +0400 Subject: [PATCH 07/10] Test the thread setting's review round 3 findings A MICROCOSM_THREADS value longer than int() parses must be refused with an error that names the setting, by the helper and by the Modal plan. The library test skips when joblib.cpu_count(), which also follows a CPU quota, is under two. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_build_tool_thread_defaults.py | 18 +++++++++++++++--- .../us/test_us_modal_stage_plan_tool.py | 13 ++++++++++++- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py b/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py index 567a93e117..44a5a706a5 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py @@ -20,6 +20,7 @@ from collections.abc import Mapping from types import ModuleType +import joblib import pytest from test_support.paths import paths_for @@ -177,7 +178,7 @@ def test_variables_already_set_are_kept(helper: ModuleType) -> None: def test_a_blank_thread_variable_is_filled(helper: ModuleType) -> None: - """Libraries read a blank thread variable as unset.""" + """Most libraries ignore a blank thread variable; joblib fails on one.""" environment = _filled(helper, {THREAD_SETTING: "4", OPENMP: ""}) @@ -185,7 +186,18 @@ def test_a_blank_thread_variable_is_filled(helper: ModuleType) -> None: @pytest.mark.parametrize( - "configured", ("0", "-1", "+4", "4,2", " 3 ", "4.0", "many", "٣") + "configured", + ( + "0", + "-1", + "+4", + "4,2", + " 3 ", + "4.0", + "many", + "٣", + pytest.param("9" * 5000, id="longer_than_int_parses"), + ), ) def test_a_thread_setting_that_is_not_a_positive_count_is_refused( helper: ModuleType, configured: str @@ -439,7 +451,7 @@ def test_importing_the_release_tool_still_applies_its_default() -> None: @pytest.mark.skipif( - (os.process_cpu_count() or 1) < 2, + joblib.cpu_count() < 2, reason="OpenBLAS and joblib use no more threads than the CPUs available", ) def test_the_thread_setting_reaches_every_library() -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py index 07ef95620c..291b29f034 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py @@ -2691,7 +2691,18 @@ def test_a_plan_may_set_the_telemetry_requirement_only_to_0(value: str) -> None: assert dict(plan_lib.parse_plan(_plan_data(env=env)).env) == env -@pytest.mark.parametrize("value", ["0", "-1", "+4", " 3 ", "4.0", "four"]) +@pytest.mark.parametrize( + "value", + [ + "0", + "-1", + "+4", + " 3 ", + "4.0", + "four", + pytest.param("9" * 5000, id="longer_than_int_parses"), + ], +) def test_a_plan_s_thread_setting_must_be_a_positive_whole_number(value: str) -> None: # The base tool's check step loads it without running its start-up step, # so a bad value would otherwise stop the run only after the runner had From cdd0bd478ac889cf1264a56f565d6537cb87421b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:31:57 +0400 Subject: [PATCH 08/10] Address review round 3 of the thread setting - A MICROCOSM_THREADS value longer than int() parses is refused with an error that names the setting, by the helper and by the Modal plan. - The library test skips when joblib.cpu_count() is under two. - Comments, runbook and changelog: joblib fails on a blank LOKY_MAX_CPU_COUNT, the ACS local-release command still takes the release default when it imports the release tool, NUMEXPR_MAX_THREADS is filled above 64 and not recorded, the resume compares values as written, and blas_threads_in_use is empty only where numpy and scipy use Accelerate. Co-Authored-By: Claude Opus 5.5 --- .../us-build-thread-environment.changed.md | 2 +- docs/us-modal-stage-runbook.md | 19 +++++++++++----- tools/build_us_puf_support_base.py | 7 +++--- tools/modal_us_stage_plan.py | 8 ++++++- tools/us_build_thread_environment.py | 22 +++++++++++++------ 5 files changed, 40 insertions(+), 18 deletions(-) diff --git a/changelog.d/us-build-thread-environment.changed.md b/changelog.d/us-build-thread-environment.changed.md index 2a583b9622..128525be24 100644 --- a/changelog.d/us-build-thread-environment.changed.md +++ b/changelog.d/us-build-thread-environment.changed.md @@ -1,3 +1,3 @@ -`MICROCOSM_THREADS` is the one thread setting of the US release, base, ACS multispine staging and ACS local-release commands. When it is set to a positive whole number, each command copies it, before numpy loads, into every unset or blank OpenMP, BLAS, numexpr and joblib thread variable (`OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `MKL_NUM_THREADS`, `BLIS_NUM_THREADS`, `VECLIB_MAXIMUM_THREADS`, `NUMEXPR_NUM_THREADS` and `LOKY_MAX_CPU_COUNT`, and `NUMEXPR_MAX_THREADS` above 64). Variables already set keep their values. A value that is not a positive whole number stops the command, and a Modal plan that sets one is refused when it is loaded. Commands that import the release tool, such as the exact-k ladder, certification and scoring tools, read the setting at that import. Without it, the base, ACS staging and ACS local-release commands set nothing and each library chooses its own count as before, and the release tool keeps its default of `min(os.cpu_count(), 16)`, which still leaves a blank variable as it is. +`MICROCOSM_THREADS` is the one thread setting of the US release, base, ACS multispine staging and ACS local-release commands. When it is set to a positive whole number, each command copies it, before numpy loads, into every unset or blank OpenMP, BLAS, numexpr and joblib thread variable (`OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `MKL_NUM_THREADS`, `BLIS_NUM_THREADS`, `VECLIB_MAXIMUM_THREADS`, `NUMEXPR_NUM_THREADS` and `LOKY_MAX_CPU_COUNT`, and `NUMEXPR_MAX_THREADS` above 64). Variables already set keep their values. A value that is not a positive whole number stops the command, and a Modal plan that sets one is refused when it is loaded. Commands that import the release tool, such as the exact-k ladder, certification and scoring tools, read the setting at that import. Without it, the base, ACS staging and ACS local-release commands set nothing and each library chooses its own count as before (until the ACS local-release command imports the release tool, as before), and the release tool keeps its default of `min(os.cpu_count(), 16)`, which still leaves a blank variable as it is. On Linux the OpenBLAS thread count can change output bytes, so the base command now records `MICROCOSM_THREADS` and each loaded BLAS library's thread count (`blas_threads_in_use`, from threadpoolctl) in `thread_environment`, and a resume with different values is refused, including one on a host where OpenBLAS would use a different count. diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index c95d7a7b7d..6d92a43143 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -503,10 +503,13 @@ values do not depend on those counts. `blas_threads_in_use`: each loaded BLAS library with the thread count it uses once numpy has loaded, as `threadpoolctl` reads it from the library. That count does not come from the environment. threadpoolctl does not report Accelerate, - so where numpy uses Accelerate, as on macOS, the list is empty. + so where numpy and scipy use Accelerate, as on Apple-silicon Macs, the list is + empty. - *A resume of the base command* compares all of these except `POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS`, and refuses a - difference, so a new thread setting needs a new checkpoint directory. Because + difference, so a new thread setting needs a new checkpoint directory. Values + are compared as written: `007` and `7`, or a blank and an unset variable, + differ. Because `blas_threads_in_use` is compared, a resume is also refused on a host where OpenBLAS would use a different count. Before, with the variables unset on both hosts, the configurations matched. @@ -517,7 +520,11 @@ values do not depend on those counts. `OMP_NUM_THREADS` is unset, `LOKY_MAX_CPU_COUNT` also limits the sign classifier's OpenMP count (see "Without the setting"). - *The helper's own file* is not in the digest of the tool's code - (`builder_code_identity`), but the values it sets are recorded and compared. + (`builder_code_identity`), but the values it sets are recorded and compared, + except `LOKY_MAX_CPU_COUNT` and `NUMEXPR_MAX_THREADS`. Those two set only + thread counts: numexpr's maximum, the QRF pools' size, which no imputed value + depends on, and, while `OMP_NUM_THREADS` is unset, the sign classifier's + OpenMP count (see above). - *Base runs started before this change:* they cannot resume after it. The run configuration holds a digest that covers the tool's own file (`builder_code_identity`), and the file changed. @@ -536,7 +543,7 @@ allowlist accepts `MICROCOSM_*` names, and it may set `OMP_NUM_THREADS`, `docs/evidence/us-release-reimputation-1191/receipts/build_environment.base_0fb05b67.release_417d23ae.json`). Because a value already set is kept, a plan's `MICROCOSM_THREADS` does not replace those four. It fills only `VECLIB_MAXIMUM_THREADS`, `NUMEXPR_NUM_THREADS` -and `LOKY_MAX_CPU_COUNT`. To change the BLAS and OpenMP counts on Modal, a plan +and `LOKY_MAX_CPU_COUNT`, and `NUMEXPR_MAX_THREADS` above 64. To change the BLAS and OpenMP counts on Modal, a plan sets those variables directly, as before; torch follows `MKL_NUM_THREADS` before `OMP_NUM_THREADS`, so changing only the latter leaves torch at Modal's value. No record shows what Modal sets in the `acs-staging` class. The tools at `4b57d15a2` @@ -1478,8 +1485,8 @@ from its environment, and Modal sets some of them itself (see "Resources"). Code that records `blas_threads_in_use` reads that one from the loaded BLAS libraries instead. These differences are reported and not refused, although a different BLAS or OpenMP count can change output bytes on Linux (see "Thread -variables"). `blas_threads_in_use` is an empty list for a run where numpy uses -Accelerate, as on macOS, and is absent from a reference made with code that does +variables"). `blas_threads_in_use` is an empty list for a run where numpy and scipy use +Accelerate, as on Apple-silicon Macs, and is absent from a reference made with code that does not record it, such as `4b57d15a2`. Only the checkpoint digests compared above show that outputs agree. The report says `compared_outputs_match`, with `stages_compared` 2 of `stages_total` 24 and diff --git a/tools/build_us_puf_support_base.py b/tools/build_us_puf_support_base.py index 6d667a310f..22f21c0672 100644 --- a/tools/build_us_puf_support_base.py +++ b/tools/build_us_puf_support_base.py @@ -29,8 +29,8 @@ # file. The helper is loaded from this file's folder, which is not on the # import path under ``python -m`` or ``python -P``. Stage subprocesses # inherit the values, and the run configuration records them, except - # LOKY_MAX_CPU_COUNT (``_stage_run_config``). E402 is ignored for this - # file in pyproject for this block. + # LOKY_MAX_CPU_COUNT and NUMEXPR_MAX_THREADS (``_stage_run_config``). E402 + # is ignored for this file in pyproject for this block. sys.path.insert(0, str(Path(__file__).resolve().parent)) from us_build_thread_environment import set_build_thread_environment @@ -1295,7 +1295,8 @@ def _blas_threads_in_use() -> list[list[object]]: threadpoolctl reads the counts from the libraries themselves, so this holds whatever chose them: a thread variable, ``MICROCOSM_THREADS`` or, with neither, the CPUs OpenBLAS found on the host. It does not report Apple's - Accelerate, so on macOS the list is empty. + Accelerate, so where numpy and scipy use Accelerate, as on Apple-silicon + Macs, the list is empty. """ return sorted( diff --git a/tools/modal_us_stage_plan.py b/tools/modal_us_stage_plan.py index bf350955b9..03b3669f7c 100644 --- a/tools/modal_us_stage_plan.py +++ b/tools/modal_us_stage_plan.py @@ -187,8 +187,14 @@ def _thread_setting_problem(value: str) -> str | None: A blank value means unset, as it does to the tools. """ - if value == "" or (value.isascii() and value.isdigit() and int(value) > 0): + if value == "": return None + if value.isascii() and value.isdigit(): + try: + if int(value) > 0: + return None + except ValueError: # longer than int() will parse + pass return ( f"env {THREAD_SETTING_ENV!r} must be a positive whole number of threads, " f"got {value!r}" diff --git a/tools/us_build_thread_environment.py b/tools/us_build_thread_environment.py index a49653a24a..ad4316c964 100644 --- a/tools/us_build_thread_environment.py +++ b/tools/us_build_thread_environment.py @@ -9,8 +9,10 @@ value keeps it. Without the setting, the base, ACS staging and ACS local-release commands set -nothing, and each library chooses its own count as it always has. The release -tool passes its own default instead, ``min(os.cpu_count(), 16)``. +nothing, and each library chooses its own count as it always has, until the +ACS local-release command imports the release tool. The release tool passes +its own default instead, ``min(os.cpu_count(), 16)``, and also applies it when +imported. On Linux the OpenBLAS thread count can change output bytes: OpenBLAS splits a large dot product between its threads, and the order of the additions moves @@ -77,8 +79,13 @@ def thread_setting(environment: Mapping[str, str] = os.environ) -> int | None: value = environment.get(THREAD_SETTING, "") if value == "": return None - if value.isascii() and value.isdigit() and int(value) > 0: - return int(value) + if value.isascii() and value.isdigit(): + try: + count = int(value) + except ValueError: # longer than int() will parse + count = 0 + if count > 0: + return count raise ValueError( f"{THREAD_SETTING} must be a positive whole number of threads, got {value!r}" ) @@ -92,9 +99,10 @@ def set_build_thread_environment( """Copy the thread setting, or ``default_count``, into each unset variable. With neither, nothing changes. A variable in ``FILLED_VARIABLES`` that - already has a value keeps it. A blank value counts as unset for the thread - setting, which libraries also read as unset. ``default_count`` keeps a blank - value, as the release tool's default always has. + already has a value keeps it. The thread setting also replaces a blank + value: most libraries ignore one, and joblib fails on a blank + ``LOKY_MAX_CPU_COUNT``. ``default_count`` keeps a blank value, as the release + tool's default always has. """ count = thread_setting(environment) From 5f436716790d6fa8f55f47c70cd9d197d6f6dd2e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:44:45 +0400 Subject: [PATCH 09/10] Test that the approved uv.lock digest is the repository lock's Adding threadpoolctl to microcosm-build moved uv.lock's digest, and the primary-QRF worker identity refuses a lock other than APPROVED_UV_LOCK_SHA256. This test names the pin to update when the lock changes. Co-Authored-By: Claude Opus 5.5 --- .../tests/engine_free/us/test_us_stacked_spine.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_stacked_spine.py b/packages/microcosm-build/tests/engine_free/us/test_us_stacked_spine.py index 87c859e164..8b9b4be75f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_stacked_spine.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_stacked_spine.py @@ -3308,6 +3308,17 @@ def test_primary_qrf_worker_identity_memo_binds_lock( ) +def test_the_approved_uv_lock_digest_is_the_repository_lock_s() -> None: + """A worker started from this checkout refuses any other lock digest.""" + + repository_lock = Path(__file__).resolve().parents[5] / "uv.lock" + repository_lock_sha256 = hashlib.sha256(repository_lock.read_bytes()).hexdigest() + assert repository_lock_sha256 == worker_identity_module.APPROVED_UV_LOCK_SHA256, ( + "uv.lock changed: set APPROVED_UV_LOCK_SHA256 in " + "microcosm.build.us_runtime.worker_identity to its new digest" + ) + + def test_primary_qrf_worker_execution_binding_isolates_semantic_memo( _worker_identity_memo_inputs, ) -> None: From 288924eeb3808aeb239b09063b464205b324c0ef Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:46:52 +0400 Subject: [PATCH 10/10] Re-pin the approved uv.lock digest for threadpoolctl MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit microcosm-build now declares threadpoolctl, which moves uv.lock's SHA-256 to cc2ece9d…. The primary-QRF worker identity refused that digest, so every test that attests the live worker failed at setup. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/build/us_runtime/worker_identity.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/worker_identity.py b/packages/microcosm-build/src/microcosm/build/us_runtime/worker_identity.py index e2e0b48720..19f7354dd4 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/worker_identity.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/worker_identity.py @@ -38,7 +38,7 @@ PRIMARY_QRF_WORKER_MODULE = "microcosm.build.us_runtime.puf_qrf_worker" PRIMARY_QRF_INTERPRETER_PLACEHOLDER = "{python_interpreter}" APPROVED_UV_LOCK_SHA256 = ( - "b9bac3fc8ebda9e5cd5b97fb5ca62c79c7ce704f8ed3c275e42300aaaf267e3f" + "cc2ece9d97931ede6009491aeb311b728ebea7cb03cf6e2752b06fac412b02eb" ) LEGACY_CAMPAIGN_UV_LOCK_SHA256 = ( "27f47e385cfa35e2644a37410d1804b361ad9aee123577551c8421547bda65ee"