Debian Codegraph @

hypothesis-python/src/_hypothesis_ftz_detector.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 """
12 This is a toolkit for determining which module set the "flush to zero" flag.
13
14 For details, see the docstring and comments in `identify_ftz_culprit()`. This module
15 is defined outside the main Hypothesis namespace so that we can avoid triggering
16 import of Hypothesis itself from each subprocess which must import the worker function.
17 """
18
19 import importlib
20 import sys
21 from collections.abc import Callable
22 from typing import TYPE_CHECKING, TypeAlias
23
24 if TYPE_CHECKING:
25 from multiprocessing import Queue
26
27 FTZCulprits: TypeAlias = tuple[bool | None, set[str]]
28
29
30 KNOWN_EVER_CULPRITS = (
31 # https://moyix.blogspot.com/2022/09/someones-been-messing-with-my-subnormals.html
32 # fmt: off
33 "archive-pdf-tools", "bgfx-python", "bicleaner-ai-glove", "BTrees", "cadbiom",
34 "ctranslate2", "dyNET", "dyNET38", "gevent", "glove-python-binary", "higra",
35 "hybridq", "ikomia", "ioh", "jij-cimod", "lavavu", "lavavu-osmesa", "MulticoreTSNE",
36 "neural-compressor", "nwhy", "openjij", "openturns", "perfmetrics", "pHashPy",
37 "pyace-lite", "pyapr", "pycompadre", "pycompadre-serial", "PyKEP", "pykep",
38 "pylimer-tools", "pyqubo", "pyscf", "PyTAT", "python-prtree", "qiskit-aer",
39 "qiskit-aer-gpu", "RelStorage", "sail-ml", "segmentation", "sente", "sinr",
40 "snapml", "superman", "symengine", "systran-align", "texture-tool", "tsne-mp",
41 "xcsf",
42 # fmt: on
43 )
44
45
46 def flush_to_zero() -> bool:
47 # If this subnormal number compares equal to zero we have a problem
48 return 2.0**-1073 == 0
49
50
51 def run_in_process(fn: Callable[..., FTZCulprits], *args: object) -> FTZCulprits:
52 import multiprocessing as mp
53
54 mp.set_start_method("spawn", force=True)
55 q: Queue[FTZCulprits] = mp.Queue()
56 p = mp.Process(target=target, args=(q, fn, *args))
57 p.start()
58 retval = q.get()
59 p.join()
60 return retval
61
62
63 def target(
64 q: "Queue[FTZCulprits]", fn: Callable[..., FTZCulprits], *args: object
65 ) -> None:
66 q.put(fn(*args))
67
68
69 def always_imported_modules() -> FTZCulprits:
70 return flush_to_zero(), set(sys.modules)
71
72
73 def modules_imported_by(mod: str) -> FTZCulprits:
74 """Return the set of modules imported transitively by mod."""
75 before = set(sys.modules)
76 try:
77 importlib.import_module(mod)
78 except Exception:
79 return None, set()
80 imports = set(sys.modules) - before
81 return flush_to_zero(), imports
82
83
84 # We don't want to redo all the expensive process-spawning checks when we've already
85 # done them, so we cache known-good packages and a known-FTZ result if we have one.
86 KNOWN_FTZ = None
87 CHECKED_CACHE = set()
88
89
90 def identify_ftz_culprits() -> str:
91 """Find the modules in sys.modules which cause "mod" to be imported."""
92 # If we've run this function before, return the same result.
93 global KNOWN_FTZ
94 if KNOWN_FTZ:
95 return KNOWN_FTZ
96 # Start by determining our baseline: the FTZ and sys.modules state in a fresh
97 # process which has only imported this module and nothing else.
98 always_enables_ftz, always_imports = run_in_process(always_imported_modules)
99 if always_enables_ftz:
100 raise RuntimeError("Python is always in FTZ mode, even without imports!")
101 CHECKED_CACHE.update(always_imports)
102
103 # Next, we'll search through sys.modules looking for a package (or packages) such
104 # that importing them in a new process sets the FTZ state. As a heuristic, we'll
105 # start with packages known to have ever enabled FTZ, then top-level packages as
106 # a way to eliminate large fractions of the search space relatively quickly.
107 def key(name: str) -> tuple[bool, int, str]:
108 """Prefer known-FTZ modules, then top-level packages, then alphabetical."""
109 return (name not in KNOWN_EVER_CULPRITS, name.count("."), name)
110
111 # We'll track the set of modules to be checked, and those which do trigger FTZ.
112 candidates = set(sys.modules) - CHECKED_CACHE
113 triggering_modules = {}
114 while candidates:
115 mod = min(candidates, key=key)
116 candidates.discard(mod)
117 enables_ftz, imports = run_in_process(modules_imported_by, mod)
118 imports -= CHECKED_CACHE
119 if enables_ftz:
120 triggering_modules[mod] = imports
121 candidates &= imports
122 else:
123 candidates -= imports
124 CHECKED_CACHE.update(imports)
125
126 # We only want to report the 'top level' packages which enable FTZ - for example,
127 # if the enabling code is in `a.b`, and `a` in turn imports `a.b`, we prefer to
128 # report `a`. On the other hand, if `a` does _not_ import `a.b`, as is the case
129 # for `hypothesis.extra.*` modules, then `a` will not be in `triggering_modules`
130 # and we'll report `a.b` here instead.
131 prefixes = tuple(n + "." for n in triggering_modules)
132 result = {k for k in triggering_modules if not k.startswith(prefixes)}
133
134 # Suppose that `bar` enables FTZ, and `foo` imports `bar`. At this point we're
135 # tracking both, but only want to report the latter.
136 for a in sorted(result):
137 for b in sorted(result):
138 if a in triggering_modules[b] and b not in triggering_modules[a]:
139 result.discard(b)
140
141 # There may be a cyclic dependency which that didn't handle, or simply two
142 # separate modules which both enable FTZ. We already gave up comprehensive
143 # reporting for speed above (`candidates &= imports`), so we'll also buy
144 # simpler reporting by arbitrarily selecting the alphabetically first package.
145 KNOWN_FTZ = min(result) # Cache the result - it's likely this will trigger again!
146 return KNOWN_FTZ
147
148
149 if __name__ == "__main__":
150 # This would be really really annoying to write automated tests for, so I've
151 # done some manual exploratory testing: `pip install grequests gevent==21.12.0`,
152 # and call print() as desired to observe behavior.
153 import grequests # noqa
154
155 # To test without skipping to a known answer, uncomment the following line and
156 # change the last element of key from `name` to `-len(name)` so that we check
157 # grequests before gevent.
158 # KNOWN_EVER_CULPRITS = [c for c in KNOWN_EVER_CULPRITS if c != "gevent"]
159 print(identify_ftz_culprits())