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..128525be24 --- /dev/null +++ b/changelog.d/us-build-thread-environment.changed.md @@ -0,0 +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 (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 9453bf76f2..74f8f961af 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -396,6 +396,161 @@ that release's current build. Modal, 3 November 2026: the telemetry token"); it did not cover a container reaching the collector. +## Thread variables + +`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) +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 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 + 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. + +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, 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. + +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 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 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 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 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; +- 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 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`: +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 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` reads it from the library. That count + does not come from the environment. threadpoolctl does not report Accelerate, + 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. 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. +- *`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, + 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. +- *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`, +`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`). +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`, 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` +and `74f5e6123`, the commits pinned by the historical base plan and the ACS +staging plan, predate the setting and ignore it. + ## Resources and cost The heavy and light classes are sized from the #974 measured peaks @@ -1164,7 +1319,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. 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, @@ -1325,8 +1482,14 @@ 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"). +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 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 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 d8916e4141..044e714147 100644 --- a/packages/microcosm-build/pyproject.toml +++ b/packages/microcosm-build/pyproject.toml @@ -30,6 +30,10 @@ 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; 3.6 reads + # the scipy-openblas library that numpy 2 wheels bundle. + "threadpoolctl>=3.6", ] [project.optional-dependencies] 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" 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..44a5a706a5 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_build_tool_thread_defaults.py @@ -0,0 +1,528 @@ +"""The one thread setting of the US build commands, ``MICROCOSM_THREADS``. + +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. +""" + +from __future__ import annotations + +import importlib.util +import json +import os +import subprocess +import sys +from collections.abc import Mapping +from types import ModuleType + +import joblib +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" +ACS_STAGING_COMMAND = "tools/build_us_acs_multispine_base.py" +ACS_STAGING_IMPLEMENTATION = "tools/_legacy/build_us_acs_multispine_base.py" +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" +OPENMP = "OMP_NUM_THREADS" +OPENBLAS = "OPENBLAS_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") +#: Every variable a process-level case clears before applying its own. +THREAD_VARIABLES = ( + THREAD_SETTING, + *FILLED_VARIABLES, + "GOTO_NUM_THREADS", + NUMEXPR_MAXIMUM, + *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 _run(command: list[str], environment: dict[str, str]): + return subprocess.run( + command, + cwd=REPOSITORY, + env=environment, + capture_output=True, + 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 +# --------------------------------------------------------------------------- + + +@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 _filled( + helper: ModuleType, + settings: Mapping[str, str] = {}, + *, + default_count: int | None = None, +) -> dict[str, str]: + environment = dict(settings) + helper.set_build_thread_environment(environment, default_count=default_count) + return environment + + +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_a_blank_thread_setting_counts_as_unset(helper: ModuleType) -> None: + assert _filled(helper, {THREAD_SETTING: ""}) == {THREAD_SETTING: ""} + + +def test_the_thread_setting_fills_every_thread_variable(helper: ModuleType) -> None: + environment = _filled(helper, {THREAD_SETTING: "4"}) + + assert environment == {THREAD_SETTING: "4", **_every_variable("4")} + + +def test_the_thread_setting_has_no_upper_limit(helper: ModuleType) -> None: + environment = _filled(helper, {THREAD_SETTING: "64"}, default_count=16) + + 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"}) + + assert environment == {THREAD_SETTING: "007", **_every_variable("7")} + + +def test_variables_already_set_are_kept(helper: ModuleType) -> None: + settings = {THREAD_SETTING: "4", OPENMP: "2", OPENBLAS: "5"} + + assert _filled(helper, settings) == { + THREAD_SETTING: "4", + **_every_variable("4", **{OPENMP: "2", OPENBLAS: "5"}), + } + + +def test_a_blank_thread_variable_is_filled(helper: ModuleType) -> None: + """Most libraries ignore a blank thread variable; joblib fails on one.""" + + environment = _filled(helper, {THREAD_SETTING: "4", OPENMP: ""}) + + assert environment == {THREAD_SETTING: "4", **_every_variable("4")} + + +@pytest.mark.parametrize( + "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 +) -> None: + environment = {THREAD_SETTING: configured} + + with pytest.raises(ValueError, match=THREAD_SETTING): + helper.set_build_thread_environment(environment, default_count=16) + + assert environment == {THREAD_SETTING: configured} + + +def test_the_default_count_applies_without_the_thread_setting( + helper: ModuleType, +) -> None: + 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) + + assert environment == {THREAD_SETTING: "3", **_every_variable("3")} + + +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, default_count=16) + + assert environment == first_result + + +# --------------------------------------------------------------------------- +# When the commands apply 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 +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 +path_before = list(sys.path) +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), + "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, + *, + run_name: str = "__main__", + cpu_count: int = 3, + settings: Mapping[str, str] = {}, +) -> dict: + state = _last_json_line( + _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_nothing_without_the_thread_setting( + tool: str, +) -> None: + environment = _state_at_first_numerical_import(tool)["environment"] + + assert _thread_variables_in(environment) == {} + + +@pytest.mark.parametrize("tool", EVERY_COMMAND) +def test_a_started_command_fills_every_variable_before_numerical_imports( + tool: str, +) -> None: + state = _state_at_first_numerical_import( + tool, cpu_count=32, settings={THREAD_SETTING: "5"} + ) + + assert _thread_variables_in(state["environment"]) == { + THREAD_SETTING: "5", + **_every_variable("5"), + } + assert state["path_unchanged"] + + +@pytest.mark.parametrize("tool", EVERY_COMMAND) +def test_a_started_command_keeps_the_values_it_was_given(tool: str) -> None: + settings = {THREAD_SETTING: "5", OPENMP: "2", OPENBLAS: "7"} + + environment = _state_at_first_numerical_import(tool, settings=settings)[ + "environment" + ] + + 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", settings={THREAD_SETTING: "5"} + )["environment"] + + assert _thread_variables_in(environment) == {THREAD_SETTING: "5"} + + +@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) + + +@pytest.mark.parametrize(("cpu_count", "expected"), ((3, "3"), (32, "16"))) +def test_release_tool_keeps_its_default_without_the_thread_setting( + cpu_count: int, expected: str +) -> None: + """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"] + + +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 +# --------------------------------------------------------------------------- + +#: 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") +from us_build_thread_environment import set_build_thread_environment + +set_build_thread_environment() + +import joblib +import numexpr +import numpy +import scipy.linalg +import threadpoolctl +import torch +from sklearn.utils._openmp_helpers import _openmp_effective_n_threads + +print() +print( + json.dumps( + { + "thread_pools": sorted( + {pool["num_threads"] for pool in threadpoolctl.threadpool_info()} + ), + "numexpr": numexpr.utils.get_num_threads(), + "scikit_learn": _openmp_effective_n_threads(), + "joblib_cpu_count": joblib.cpu_count(), + "torch": torch.get_num_threads(), + } + ) +) +""" + + +@pytest.mark.skipif( + 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: + 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, + } + + +_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 + +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()})) +""" + + +def test_sign_classifier_probabilities_do_not_depend_on_the_openmp_count() -> None: + """The thread setting changes the classifier's OpenMP count.""" + + 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/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 cf03cee48e..75036f2587 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,28 @@ 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.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 + # 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) 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, 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: diff --git a/pyproject.toml b/pyproject.toml index d6dcdd8aa6..82578f7218 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,6 +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, 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/_legacy/build_us_acs_multispine_base.py b/tools/_legacy/build_us_acs_multispine_base.py index 4299a2e65f..0d7e04fb3b 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_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 3f206e8966..3551384df8 100644 --- a/tools/build_us_acs_multispine_base.py +++ b/tools/build_us_acs_multispine_base.py @@ -8,10 +8,26 @@ from __future__ import annotations -import importlib.util import sys -import warnings 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. 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 warnings from types import ModuleType from microcosm.build.us_runtime.h5_io import ( diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index f672b84652..9ec0f32f7a 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -30,24 +30,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 @@ -62,7 +63,6 @@ import shlex import shutil import subprocess -import sys import time import tomllib import traceback @@ -71,7 +71,7 @@ from contextlib import contextmanager, nullcontext from datetime import UTC, datetime from importlib.resources import files as package_files -from pathlib import Path, PurePosixPath +from pathlib import PurePosixPath 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 19eea90a22..22f21c0672 100644 --- a/tools/build_us_puf_support_base.py +++ b/tools/build_us_puf_support_base.py @@ -18,20 +18,38 @@ 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. 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 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 + + del sys.path[0] + set_build_thread_environment() + import argparse import hashlib import json 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 +from threadpoolctl import threadpool_info from microcosm.build import FitWeightRecord, GateResult, weights_audit_gate from microcosm.build.frame_checkpoint import write_frame_checkpoint @@ -1261,14 +1279,33 @@ 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. +#: 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 where numpy and scipy use Accelerate, as on Apple-silicon + Macs, 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.""" @@ -1304,6 +1341,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", @@ -1315,6 +1353,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/modal_us_stage_plan.py b/tools/modal_us_stage_plan.py index 3385708954..03b3669f7c 100644 --- a/tools/modal_us_stage_plan.py +++ b/tools/modal_us_stage_plan.py @@ -172,6 +172,35 @@ "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 == "": + 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}" + ) + + #: 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 +1666,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 new file mode 100644 index 0000000000..ad4316c964 --- /dev/null +++ b/tools/us_build_thread_environment.py @@ -0,0 +1,120 @@ +"""The one thread setting of the US build commands, ``MICROCOSM_THREADS``. + +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, ACS staging and ACS local-release commands set +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 +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. +""" + +from __future__ import annotations + +import os +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. 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, and uses no more threads than the CPUs + # it may run on. + "OPENBLAS_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. + "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", +) + +#: 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", +] + + +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. + """ + + value = environment.get(THREAD_SETTING, "") + if value == "": + return None + 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}" + ) + + +def set_build_thread_environment( + environment: MutableMapping[str, str] = os.environ, + *, + default_count: int | None = None, +) -> None: + """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. 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) + replaces_blank_values = count is not None + if count is None: + count = default_count + if count is None: + return + 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 d811dd6896..aee8a744d5 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.6" }, ] provides-extras = ["us", "uk"]