diff --git a/src/qldpc/_compilation.py b/src/qldpc/_compilation.py index 9efefdb5d..0eea90eee 100644 --- a/src/qldpc/_compilation.py +++ b/src/qldpc/_compilation.py @@ -5,7 +5,7 @@ qLDPC, for example in its distance and counting searches, runs two kinds of functions that numba compiles. They are written in the subset of Python and NumPy that numba supports. -Always-compiled functions, such as bit packing, row reduction and the scan of a chunk of +Always-compiled functions, such as bit packing, row reduction, and the scan of a chunk of combinations, are compiled by numba the first time that they are used. Compiled-on-request functions are compiled on first use after :func:`~qldpc.codes.distance.compile_search_setup` requests their compilation (see below). The compiled code of both kinds is cached on disk. Numba @@ -20,18 +20,9 @@ hold code of other versions of its own package directory's source files, or of package directories that it cannot find, such as deleted checkouts (see :func:`_delete_outdated_cache_directories`). -Several processes can compile the same function at the same time, such as parallel test workers -after a change to the source. Numba saves each compiled version of a function in a data file, and -keeps an index that maps the key of each compiled version, which includes its argument types, to its -data file. It names the data file of a new compiled version by the lowest number that the index it -read does not use, and nothing stops another process from writing the index between its read and its -write. Two processes that compile a function for different argument types at once can thus write -the same data file, and leave the index pointing at code compiled for other argument types (`numba -issue #10862 `_). Numba checks little more than the -size of the items of array arguments before it runs such code, which can then raise an error or -silently return wrong results. This module therefore saves numba's version and the key of each -compiled version with its code, and loads the code only if both match. Otherwise numba compiles the -function again for that key, and saves the new code in place of the code that did not match. +Numba's disk cache can serve code compiled for other argument types, such as when several processes +compile a function at once, or code saved by another version of numba, so this module checks what it +loads (see ``_KeyCheckedCacheFile``). Compiled-on-request functions, such as the building of overlapping basis families, are registered with :func:`compiled_on_request`. They run as plain Python until @@ -49,8 +40,8 @@ orchestrate a search, which select and bound its information sets, build its basis families, and drive its scan. Compiling them takes long, and if they were always compiled, the first program that makes a search after each change to the source files of qLDPC would compile them, even for one -search. Define them only in :mod:`qldpc.codes.distance`, whose tests CI runs with them compiled. A -function that is neither runs as plain Python. A small always-compiled helper that hot loops call +search. Define them only in :mod:`qldpc.codes.distance`, whose tests CI runs with them compiled. +A function that is neither runs as plain Python. A small always-compiled helper that hot loops call can be marked ``inline=True`` (see :func:`always_compiled`). A compiled-on-request function may call always-compiled and compiled-on-request functions. An always-compiled function may call only always-compiled functions, since it is compiled and cached by itself. The tests of these rules find @@ -286,11 +277,10 @@ def is_compilation_disabled() -> bool: def _work_around_numba_name_clashes() -> bool: """Work around a numba bug by starting numba's count of compiled functions at random. - Numba names compiled code by function name, argument types, and this count, which starts at one - in each process. Functions that numba generates from one template, such as the sorts behind - ``np.sort`` and ``np.argsort``, can thus get the same name for different code in different - processes, and a process that loads both from the disk cache runs one in place of the other. - Code that numba compiled before qLDPC was imported keeps its names. + TEMPORARY until numba fixes numba/numba#11016: see numba_workarounds.md, + "Clashing names of code compiled in different processes". + + Code that numba compiled before qLDPC was imported keeps the names that numba's count gave it. Returns: Whether the count, which is internal to numba, was where this function expects. @@ -303,7 +293,8 @@ def _work_around_numba_name_clashes() -> bool: return True -# WORKAROUND FOR A NUMBA BUG, in each process and forked child. Without it, qLDPC caches nothing. +# TEMPORARY until numba fixes numba/numba#11016: see numba_workarounds.md, +# "Clashing names of code compiled in different processes". _NUMBA_NAME_CLASHES_AVOIDED = _work_around_numba_name_clashes() if hasattr(os, "register_at_fork"): os.register_at_fork(after_in_child=_work_around_numba_name_clashes) @@ -339,7 +330,9 @@ def _compile_with_cache_in( setting, the report, and the object are internal to numba, so this function checks the report and the class of the object. """ - # Cache nothing without the workaround for numba's clashing names. + # TEMPORARY until numba fixes numba/numba#11016: see numba_workarounds.md, + # "Clashing names of code compiled in different processes". + # Cache nothing without the workaround. if not _NUMBA_NAME_CLASHES_AVOIDED: _warn_not_cached( f"its workaround for a numba bug does not work with numba {numba.__version__}", @@ -363,6 +356,9 @@ def _compile_with_cache_in( _warn_not_cached(f"numba does not use {directory}") return None + # TEMPORARY until numba loads a data file only if its own version saved it for the key that it + # loads (numba/numba#10862): see numba_workarounds.md, + # "Data files that hold code for another key". # Make numba's cache-file object check what it loads, if it has exactly the class that qLDPC # extends. Changing the class of an object of a subclass would drop the overrides of the # subclass. The class is changed, rather than the object replaced, to keep the paths and source @@ -382,13 +378,15 @@ def _compile_with_cache_in( class _KeyCheckedCacheFile(caching.IndexDataCacheFile): """Numba's cache-file object of a function, which loads only code saved for the same key. + TEMPORARY until numba loads a data file only if its own version saved it for the key that it + loads (numba/numba#10862): see numba_workarounds.md, + "Data files that hold code for another key". + Each data file holds numba's version, and a pickle of the key of its compiled version with the code. A load unpickles the pickle only if numba's version matches, since another version of numba may not be able to unpickle it. It returns the code only if the key matches too. Otherwise numba compiles the function again for that key, and saves the new code in the same - data file. Environments with different versions of numba can share the directory: each reads - only an index that its own version wrote, but any of them can write a data file. The module - docstring explains how a data file can hold code for another key. + data file. """ def save(self, key: object, data: object) -> None: diff --git a/src/qldpc/_compilation_test.py b/src/qldpc/_compilation_test.py index e79443368..f629100f6 100644 --- a/src/qldpc/_compilation_test.py +++ b/src/qldpc/_compilation_test.py @@ -333,11 +333,13 @@ def test_versions_compiled_at_the_same_time_are_loaded_only_for_their_argument_t ) -> None: """A version compiled for some argument types is never loaded for others. - The docstring of ``_compilation`` explains how processes that compile a function at once can - leave numba's index pointing at code compiled for other argument types. Without the check of - keys, a later process here would run code compiled for F-ordered arrays on a C-ordered array and - return a wrong entry. Each new dispatcher stands for a process, and replacing the index file - stages the order of the writes. + TEMPORARY until numba loads a data file only if its own version saved it for the key that it + loads (numba/numba#10862): see numba_workarounds.md, + "Data files that hold code for another key". + + Without the check of keys, a later process here would run code compiled for F-ordered arrays on + a C-ordered array and return a wrong entry. Each new dispatcher stands for a process, and + replacing the index file stages the order of the writes. """ monkeypatch.setattr(_compilation, "_get_cache_directory", lambda package: tmp_path / "cache") matrix = np.array([[0, 1], [2, 3]], dtype=np.uint8) @@ -368,10 +370,12 @@ def test_code_saved_by_another_version_of_numba_is_compiled_again( ) -> None: """Code that another version of numba saved for the same key is compiled again, not loaded. - ``_KeyCheckedCacheFile`` explains how the index of this version can name a data file that - another version of numba wrote, and why its code is not unpickled. In one case, this version - can unpickle that code. In the other, the code refers to a module that this version lacks, as - code that numba 0.61.2 saved does for numba 0.67.0. + TEMPORARY until numba loads a data file only if its own version saved it for the key that it + loads (numba/numba#10862): see numba_workarounds.md, + "Data files that hold code for another key". + + In one case, this version can unpickle the code. In the other, the code refers to a module that + this version lacks, as code that numba 0.61.2 saved does for numba 0.67.0. """ monkeypatch.setattr(_compilation, "_get_cache_directory", lambda package: tmp_path / "cache") @@ -400,6 +404,10 @@ def test_a_function_is_not_cached_if_numba_reads_its_files_through_another_class ) -> None: """qLDPC caches only through a cache-file object exactly of the class that qLDPC extends. + TEMPORARY until numba loads a data file only if its own version saved it for the key that it + loads (numba/numba#10862): see numba_workarounds.md, + "Data files that hold code for another key". + Here ``object`` stands for the class that qLDPC extends, so numba's cache-file object is of a subclass of it. """ @@ -416,13 +424,19 @@ def test_a_function_is_not_cached_if_numba_reads_its_files_through_another_class [False, pytest.param(True, marks=pytest.mark.skipif(not hasattr(os, "fork"), reason=""))], ) def test_code_compiled_in_different_processes_has_distinct_names(fork: bool) -> None: - """Check the workaround for a numba bug that gives different code the same name.""" + """Check the workaround for a numba bug that gives different code the same name. + + TEMPORARY until numba fixes numba/numba#11016: see numba_workarounds.md, + "Clashing names of code compiled in different processes". + """ code = _PRINT_SYMBOL_NAMES + (_IN_PARENT_AND_FORKED_CHILD if fork else "print_names()\n") outputs = run_python(code).splitlines() if fork else [run_python(code), run_python(code)] first, second = (set(output.split()) for output in outputs) assert first and second and not first & second +# TEMPORARY until numba fixes numba/numba#11016: see numba_workarounds.md, +# "Clashing names of code compiled in different processes". def test_compiled_code_is_not_cached_without_the_workaround_for_a_numba_bug( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -669,6 +683,8 @@ def add_to(value): return increment(value) """ +# TEMPORARY until numba fixes numba/numba#11016: see numba_workarounds.md, +# "Clashing names of code compiled in different processes". # A program whose ``print_names`` compiles a function that sorts, and prints the names in its code # that hold numba's count of compiled functions, in tags such as ``B5v5006``. _PRINT_SYMBOL_NAMES = """ @@ -685,6 +701,8 @@ def print_names(): print(*{name for name in names if re.search("B[0-9]+v[0-9]+", name)}, flush=True) """ +# TEMPORARY until numba fixes numba/numba#11016: see numba_workarounds.md, +# "Clashing names of code compiled in different processes". _IN_PARENT_AND_FORKED_CHILD = """ if os.fork() == 0: print_names() @@ -705,6 +723,8 @@ def _add_one(value: int) -> int: return value + 1 +# TEMPORARY until numba loads a data file only if its own version saved it for the key that it loads +# (numba/numba#10862): see numba_workarounds.md, "Data files that hold code for another key". def _get_top_right_entry(matrix: npt.NDArray[np.uint8]) -> int: return matrix[0, -1] diff --git a/src/qldpc/numba_workarounds.md b/src/qldpc/numba_workarounds.md new file mode 100644 index 000000000..6632c1d79 --- /dev/null +++ b/src/qldpc/numba_workarounds.md @@ -0,0 +1,43 @@ +# Workarounds for bugs of numba + +This guide lists the code in qLDPC that exists only because of a bug of [numba](https://github.com/numba/numba), with one section for each bug, and says how to remove the code once numba is fixed. + +Each site carries a marker that names its section, so `git grep "TEMPORARY until"` lists every site, apart from passages of docstrings that describe a workaround, which the section's steps name. +A function or class with a docstring that the migration deletes has the marker right after its docstring's summary line. +Anything else that the migration deletes has the marker as a comment above it: + +```python +# TEMPORARY until : see numba_workarounds.md, "
". +``` + +A trigger holds once qLDPC's `pyproject.toml` requires a numba release that does what it says. +To migrate, follow the section's steps, delete the imports that become unused, and delete the section. + +## Clashing names of code compiled in different processes + +Numba names compiled code by function name, argument types, and a count that starts at one in each process ([numba/numba#11016](https://github.com/numba/numba/issues/11016)). +Functions that numba generates from one template, such as the sorts behind `np.sort` and `np.argsort`, can thus get the same name for different code in different processes, and a process that loads both from the disk cache runs one in place of the other. +So `_compilation` starts the count at a random number in each process. + +**Trigger:** numba fixes numba/numba#11016. + +**Migration:** + +1. In `_compilation`, delete `_work_around_numba_name_clashes`, `_NUMBA_NAME_CLASHES_AVOIDED`, the `if` statement that calls `os.register_at_fork`, and the check that opens `_compile_with_cache_in`. +2. In `_compilation_test`, delete `test_code_compiled_in_different_processes_has_distinct_names`, `test_compiled_code_is_not_cached_without_the_workaround_for_a_numba_bug`, `_PRINT_SYMBOL_NAMES`, and `_IN_PARENT_AND_FORKED_CHILD`. + +## Data files that hold code for another key + +Numba saves the code that it compiles for each key, which includes the argument types, in a data file, and keeps an index that maps each key to its data file. +It names the data file of new code by the lowest number that the index it read does not use, and nothing stops another process from writing the index between its read and its write ([numba/numba#10862](https://github.com/numba/numba/issues/10862)). +Two processes that compile a function for different argument types at once can thus write the same data file, and leave the index pointing at code compiled for the other argument types, which can raise an error or silently return wrong results. +Environments with different versions of numba that share a cache directory also write each other's data files, since each reads only an index that its own version wrote. +So `_KeyCheckedCacheFile` saves numba's version and the key with the code, and loads the code only if both match. + +**Trigger:** numba loads a data file only if its own version saved it for the key that it loads (numba/numba#10862). + +**Migration:** + +1. In `_compilation`, delete `_KeyCheckedCacheFile`, and the paragraph of `_compile_with_cache_in` that changes the class of numba's cache-file object, except its `return dispatcher`. +2. Delete what the docstrings of `always_compiled` and `_compile_with_cache_in` say about that object, so that `always_compiled` says "If the directory cannot be used, qLDPC warns once, and every process compiles the function again.", and delete the paragraph of the module docstring that points to `_KeyCheckedCacheFile`. +3. In `_compilation_test`, delete `test_versions_compiled_at_the_same_time_are_loaded_only_for_their_argument_types`, `test_code_saved_by_another_version_of_numba_is_compiled_again`, `test_a_function_is_not_cached_if_numba_reads_its_files_through_another_class`, and `_get_top_right_entry`.