From 5f6e6a62992b3f91d8e736a5ef583ca10c1a8e76 Mon Sep 17 00:00:00 2001 From: Joshua Cartu Date: Mon, 30 Nov 2026 14:27:51 +0000 Subject: [PATCH] ignition(preparation): skip unreferenced epilogue candidates in relocate_inductor Tensor-parallel preparation aborts with `KeyError` on relocating ranks when a compiled forward's Triton bundle holds a static autotuner that the generated Python module never defines. During multi-rank preparation (`ForwardCache._prepare_ranks` in `ignition/preparation/aot.py`), `self._load` deserializes compiled forwards through `aot._load_inductor` with `frozen` false (the artifact's `_tuning_frozen` before `InductorSelections.freeze`), which invokes `relocate_inductor` (`ignition/preparation/device_binding.py`) before `InductorSelections.freeze` prunes `bundle.static_autotuners`. On the compiler rank (`target == original`) with `freeze_tuning=False`, `relocate_inductor` returns early without inspecting `static_autotuners`, and `InductorSelections.register` (`ignition/preparation/inductor_tuning.py`) ignores unreferenced `static_autotuners` entries left behind by PyTorch Inductor epilogue-fusion benchmarking (`entry.kernel_name` absent from the generated Python module). On peer tensor-parallel ranks (`target != original`) during the unfrozen load, `relocate_inductor` previously assigned `graph.source_code`, `graph.cache_key`, and `graph.device_idxs` before its loop and indexed `kernel_keys[entry_kernel.cache_key]` across every entry in `bundle.static_autotuners`. Because `_device_source` populates `kernel_keys` only from `async_compile.triton` calls present in `graph.source_code`, on an unfrozen peer load a bundled candidate whose cache key was absent from `kernel_keys` raised `KeyError`. Compiler-rank registration accepted the candidate in the TP4 reproduction, but its substring check could reject unused candidates with prefix-colliding names. When `freeze_tuning=True` (`ForwardCache._load` sets it from the `triton.autotune_at_compile_time` option), `_freeze_tuning_winners` also ran before checking bindings on both compiler and peer ranks, so an unresolved unreferenced candidate or referenced unbound kernel could fail winner freezing before missing bindings were diagnosed. In addition, `InductorSelections.register` previously mutated `self.instances` and called `_install` before checking unbound entries, collapsed duplicate unbound `cache_key` snapshots before checking names, and checked `entry.kernel_name in graph.source_code` by substring rather than exact identifier, which false-matches a prefix candidate such as `triton_tem_fused_1` when `triton_tem_fused_10` is bound (reproduced in CPU unit tests). Dropping unreferenced `static_autotuners` entries during relocation and winner freezing is sound because any entry whose cache key has no `async_compile.triton` definition cannot be launched by the generated module, every launch in generated Inductor code names its kernel via a module-global identifier or `async_compile.triton` call string, and `InductorSelections.freeze` discards unreferenced entries on every rank anyway. This commit aligns unreferenced-candidate handling and pre-mutation validation across `ignition/preparation/device_binding.py` and `ignition/preparation/inductor_tuning.py`: - Adds `_referenced_kernel_names(source)` (collecting AST `Name` identifiers and `async_compile.triton` string kernel names), `_source_kernel_keys(source)`, and `_filter_static_autotuners(bundle, source, bound_keys)` (deferring AST name collection until an unbound key is encountered) in `device_binding.py`, and uses `_filter_static_autotuners` in both `InductorSelections.register` and `relocate_inductor`. - Updates `relocate_inductor` so that both `target == original` (when `freeze_tuning=True`) and `target != original` validate and filter `bundle.static_autotuners` before `_freeze_tuning_winners` and before writing `graph` or mutating any `CachingAutotuner`. Entries with `cache_key` in `bound_keys` are retained; entries absent from `bound_keys` raise `ValueError("compiled forward has unbound static Inductor kernels")` when `entry_kernel.kernel_name` is in `_referenced_kernel_names(source)`, and are removed from the bundle without mutating their device metadata or failing winner freezing when unreferenced (matching what `InductorSelections.freeze` produces on every rank). - Updates `InductorSelections.register` to collect discovered `(identity, tuner)` pairs during AST traversal, validate every `bundle.static_autotuners` entry through `_filter_static_autotuners` before mutating state, and only then register each distinct tuner instance (including multiple globals sharing one `cache_key`), install an existing winner on each newly registered instance, and record `self.forwards`. - Adds CPU regression tests in `tests/preparation/test_inductor_prepared_winners.py` covering serialized peer-rank unreferenced-candidate pruning, exact-identifier prefix-collision handling across compiler (`target == original, freeze_tuning=True`) and peer (`target != original, freeze_tuning in [False, True]`) ranks, pre-mutation `ValueError` rejection in `relocate_inductor` (across both compiler and peer ranks) and `InductorSelections.register`, aliased `async_compile.triton` literal kernel names with a trailing same-key unused snapshot, and multi-global shared-key tuner preservation. On `0a8c20f4` CPU fixtures, `relocate_inductor` removes unreferenced epilogue candidates (including unresolved candidates under `freeze_tuning=True` on both compiler and peer ranks), `InductorSelections.register` ignores unreferenced candidates while preserving distinct tuners sharing a source key, and both fail closed with `ValueError` on referenced unbound kernels (including when shadowed by a later unused snapshot with the same key) without mutating `graph`, `self.instances`, or sibling autotuners. Separately, on 4x RTX PRO 6000 Blackwell (`sm_120`, TP4) using a locally patched checkout of `Flare v0.4.4` (`99339606`), skipping unreferenced `static_autotuners` entries in `relocate_inductor` unblocked `qwen38` TP4 preparation through native core export and `flare run` health startup across all four ranks; with both production files restored to `0a8c20f4` and the new tests retained, the serialized peer-load test raised `KeyError`. This changes Python preparation orchestration and its CPU tests only: `InductorSelections.register` on every rank and in single-device `ForwardCache._warm`, and `relocate_inductor` on every compiled-forward load that relocates (`target != original`) or freezes winners (a frozen artifact or `triton.autotune_at_compile_time`). It does not modify CUDA, PTX, CuTe DSL, Triton kernels, fusion, stream overlap, prepared core formats, or runtime ABIs. Validation and limitations: - Targeted CPU unit tests (`Python 3.12`, `torch==2.14.1+cu132`, `triton==3.8.0` on `0a8c20f4`): `CUDA_VISIBLE_DEVICES="" .venv/bin/python -m pytest -q tests/preparation/test_inductor_prepared_winners.py tests/preparation/test_aot_guards.py tests/preparation/test_inductor_workspace_lifetimes.py` passed (`32 passed` in `4.63s`; `27 passed` in `test_inductor_prepared_winners.py`, adding 9 test cases across 5 functions: `test_load_inductor_relocation_drops_unreferenced_epilogue_candidates`, `test_relocate_inductor_skips_prefix_colliding_unreferenced_candidate_in_memory[(0, True), (1, False), (1, True)]`, `test_relocate_inductor_rejects_referenced_unbound_kernel_without_partial_mutation[(0, True), (2, False), (2, True)]`, `test_register_and_relocate_reject_aliased_triton_literal_without_partial_mutation`, and `test_register_preserves_distinct_tuners_sharing_source_key`). - Full `tests/preparation` CPU suite (`CUDA_VISIBLE_DEVICES="" .venv/bin/python -m pytest -q tests/preparation` in the same `0a8c20f4` environment): unmodified `0a8c20f4` reported `1,148 passed, 74 skipped, 2 failed`, and this change reported `1,157 passed, 74 skipped, 2 failed` (`+9` added cases). Both runs hit the same two unrelated failures (`test_inductor_template_mutations.py::test_external_bmm_replacement_retains_input_mutation_dependency[clean]` did not raise `InductorError`, and `test_runtime_triton.py::test_replaces_clean_architecture_probe_and_preserves_patched_key` saw `platform.architecture()` omit `'ELF'` under `uv`-managed Python); neither test touches `device_binding.py` or `inductor_tuning.py`. - Revert check: reverting `ignition/preparation/device_binding.py` and `ignition/preparation/inductor_tuning.py` causes all 8 behavior-change test cases in `test_inductor_prepared_winners.py` to fail (`8 failed, 19 passed` in `2.69s`: `KeyError` on the serialized drop test, false-positive `ValueError` in `register` on all three prefix-collision cases, `KeyError` on peer `freeze_tuning=False` rejection, premature `pending coordinate-descent tuning` failure before binding validation on both `(0, True)` and `(2, True)` rejection cases, and `DID NOT RAISE ValueError` on `register` when the trailing unused same-key snapshot shadowed `'kernel_x'`; `test_register_preserves_distinct_tuners_sharing_source_key` passes with and without the source change, confirming preservation of existing multi-global registration). All `27` tests in `test_inductor_prepared_winners.py` pass with the change. - Hardware reproduction provenance (`4x RTX PRO 6000 Blackwell`, `sm_120`, TP4, `Flare v0.4.4` `99339606`, `local-inference-lab/Qwen3.8-Flash-Next-NVFP4-MXFP8-CSF-QAD` `dc5b8ab2` with the `qwen38` recipe): on unmodified `99339606`, `qwen38` TP4 preparation failed during `Load and warm compiled forwards` with no error on rank `0` and `KeyError` inside `relocate_inductor` on ranks `1..3` for the forward named `speculative16x5`. On a locally patched checkout of `99339606` with an uncommitted guard in `relocate_inductor` that skipped `static_autotuners` entries absent from `kernel_keys` when `entry.kernel_name` was not a substring of `graph.source_code`, `qwen38` TP4 preparation completed `Load and warm compiled forwards`, CUDA graph capture, native core export, and `flare run` health startup across all four ranks. The TP4 run exercised the substring guard. CPU tests exercised the submitted AST matcher against prefix collisions and aliased kernel names, aligned `InductorSelections.register`, and validated before freezing or mutation on `0a8c20f4`. - Limitations: no GPU preparation was run on `0a8c20f4` with this exact submitted diff, and standalone CUDA unit tests (`tests/preparation/*_cuda.py`) were not run, including on the 4x RTX PRO 6000 host. Design-Signed-Off-By: Gemini 4 Neon; design-review=2e5b Signed-off-by: Joshua Cartu --- ignition/preparation/device_binding.py | 63 +++- ignition/preparation/inductor_tuning.py | 11 +- .../test_inductor_prepared_winners.py | 350 ++++++++++++++++++ 3 files changed, 414 insertions(+), 10 deletions(-) diff --git a/ignition/preparation/device_binding.py b/ignition/preparation/device_binding.py index 6b2b88e94..18cc3e214 100644 --- a/ignition/preparation/device_binding.py +++ b/ignition/preparation/device_binding.py @@ -89,6 +89,47 @@ def replace(node, value): return b"".join(parts).decode() +def _referenced_kernel_names(source): + """Collect module identifiers and async_compile.triton kernel names in generated Inductor code.""" + names = set() + for node in ast.walk(ast.parse(source)): + if isinstance(node, ast.Name): + names.add(node.id) + elif (isinstance(node, ast.Call) and ast.unparse(node.func) == "async_compile.triton" + and node.args and isinstance(node.args[0], ast.Constant) + and isinstance(node.args[0].value, str)): + names.add(node.args[0].value) + return names + + +def _source_kernel_keys(source): + from torch._inductor.async_compile import CompiledTritonKernels + + keys = set() + for node in ast.walk(ast.parse(source)): + if (isinstance(node, ast.Call) and ast.unparse(node.func) == "async_compile.triton" + and len(node.args) > 1 and isinstance(node.args[1], ast.Constant) + and isinstance(node.args[1].value, str)): + keys.add(CompiledTritonKernels.key(node.args[1].value)) + return keys + + +def _filter_static_autotuners(bundle, source, bound_keys): + # Epilogue-fusion benchmarking bundles template candidates that final code never names; + # only static autotuners still named in the generated module require an async_compile binding. + referenced_names = None + retained = [] + for entry_kernel in bundle.static_autotuners: + if entry_kernel.cache_key in bound_keys: + retained.append(entry_kernel) + continue + if referenced_names is None: + referenced_names = _referenced_kernel_names(source) + if entry_kernel.kernel_name in referenced_names: + raise ValueError("compiled forward has unbound static Inductor kernels") + return retained + + def _freeze_tuning_winners(bundle): """Preserve completed compile-time selections while rebuilding launchers. @@ -138,17 +179,27 @@ def relocate_inductor(entry, original, *, freeze_tuning=False): raise ValueError("device binding requires a compiled inference forward") if graph.device_idxs != OrderedSet((original.index,)): raise ValueError("compiled forward must use one CUDA device") - if freeze_tuning and graph._triton_bundle is not None: - _freeze_tuning_winners(graph._triton_bundle) if not relocate: + if bundle := graph._triton_bundle: + retained = _filter_static_autotuners(bundle, graph.source_code, _source_kernel_keys(graph.source_code)) + retained_bundle = replace(bundle, static_autotuners=retained) + _freeze_tuning_winners(retained_bundle) + graph._triton_bundle = retained_bundle return kernel_keys = {} - graph.source_code = _device_source(graph.source_code, original.index, target.index, kernel_keys) - graph.cache_key = code_hash(graph.source_code) - graph.device_idxs = OrderedSet((target.index,)) + rebound_source = _device_source(graph.source_code, original.index, target.index, kernel_keys) if bundle := graph._triton_bundle: + retained = _filter_static_autotuners(bundle, rebound_source, kernel_keys) + if freeze_tuning: + retained_bundle = replace(bundle, static_autotuners=retained) + _freeze_tuning_winners(retained_bundle) + retained = retained_bundle.static_autotuners + graph.source_code = rebound_source + graph.cache_key = code_hash(rebound_source) + graph.device_idxs = OrderedSet((target.index,)) + if bundle: autotuners = [] - for entry_kernel in bundle.static_autotuners: + for entry_kernel in retained: kernel = entry_kernel.kernel kernel.device_props = kernel.device_props._replace(index=target.index) kernel.triton_meta["device"] = target.index diff --git a/ignition/preparation/inductor_tuning.py b/ignition/preparation/inductor_tuning.py index fb062daeb..a431b8c5f 100644 --- a/ignition/preparation/inductor_tuning.py +++ b/ignition/preparation/inductor_tuning.py @@ -15,7 +15,7 @@ import torch -from .device_binding import _device_source, _freeze_tuning_winners +from .device_binding import _device_source, _filter_static_autotuners, _freeze_tuning_winners def _selected(tuner): @@ -143,6 +143,7 @@ def register(self, bound): {entry.cache_key: entry for entry in graph._triton_bundle.static_autotuners}) module = _kernel_globals(graph) if entries else {} bindings = {} + discovered = [] for node in ast.walk(ast.parse(graph.source_code)): if not (isinstance(node, ast.Assign) and isinstance(node.value, ast.Call) and ast.unparse(node.value.func) == 'async_compile.triton'): @@ -161,14 +162,16 @@ def register(self, bound): f'bundled={cache_key in entries}, static_entries={len(entries)}') identity = CompiledTritonKernels.key(_device_source(source, original, 0)) bindings[cache_key] = identity, entries[cache_key], tuner + discovered.append((identity, tuner)) + # Epilogue-fusion benchmarking bundles template candidates that final code never names. + if graph._triton_bundle is not None: + _filter_static_autotuners(graph._triton_bundle, graph.source_code, bindings) + for identity, tuner in discovered: instances = self.instances.setdefault(identity, {}) if id(tuner) not in instances: instances[id(tuner)] = tuner if identity in self.winners: _install(tuner, self.winners[identity]) - # Epilogue-fusion benchmarking bundles template candidates that final code never names. - if any(entries[key].kernel_name in graph.source_code for key in set(entries) - set(bindings)): - raise ValueError("compiled forward has unbound static Inductor kernels") self.forwards[id(bound)] = backend, graph, bindings @contextmanager diff --git a/tests/preparation/test_inductor_prepared_winners.py b/tests/preparation/test_inductor_prepared_winners.py index aedc4484b..23f1c1dd3 100644 --- a/tests/preparation/test_inductor_prepared_winners.py +++ b/tests/preparation/test_inductor_prepared_winners.py @@ -312,3 +312,353 @@ def test_effective_last_snapshot_preserves_the_tuned_winner(monkeypatch): assert len(initial.compile_results) == 2 with pytest.raises(ValueError, match="unresolved"): _freeze_tuning_winners(SimpleNamespace(static_autotuners=snapshots[::-1])) + + +def test_load_inductor_relocation_drops_unreferenced_epilogue_candidates(monkeypatch): + import importlib + import zlib + from torch._inductor.output_code import CompiledFxGraph + from torch.utils._ordered_set import OrderedSet + from torch._inductor.async_compile import CompiledTritonKernels + from torch._inductor.codecache import code_hash + from torch._functorch._aot_autograd import aot_autograd_result + from torch._functorch._aot_autograd.runtime_wrappers import SerializableCompiledFunction + from torch._functorch._aot_autograd.utils import simple_wraps + from ignition.preparation import aot + standalone_compile = importlib.import_module("torch._inductor.standalone_compile") + + tuner, selected = restored_reduction(monkeypatch) + bound_tuner = StoredTuner() + bound_tuner.compile_results = tuner.compile_results + bound_tuner.compile_results[0].compile_meta["device"] = 0 + bound_tuner.inductor_meta = tuner.inductor_meta + bound_tuner.triton_meta = {"device": 0} + bound_tuner.device_props = DeviceProperties(0) + + unreferenced_cand, _ = restored_reduction(monkeypatch) + epilogue_tuner = StoredTuner() + epilogue_tuner.compile_results = unreferenced_cand.compile_results * 2 + for res in epilogue_tuner.compile_results: + res.compile_meta["device"] = 0 + epilogue_tuner.inductor_meta = {"kernel_name": "triton_tem_fused_epilogue_0"} + epilogue_tuner.triton_meta = {"device": 0} + epilogue_tuner.device_props = DeviceProperties(0) + + kernel_source = "device = DeviceProperties(index=0)\n# triton_red_fused_0\n" + graph = CompiledFxGraph.__new__(CompiledFxGraph) + graph.compiled_fn_runner = None + graph.device_idxs = OrderedSet((0,)) + graph.source_code = ( + "torch.cuda.set_device(0)\n" + "stream = get_raw_stream(0)\n" + "triton_red_fused_0 = async_compile.triton('triton_red_fused_0', " + repr(kernel_source) + ")\n" + ) + graph.cache_key = code_hash(graph.source_code) + orig_key = CompiledTritonKernels.key(kernel_source) + graph._triton_bundle = StoredBundle( + static_autotuners=[ + StoredEntry(orig_key, bound_tuner, "triton_red_fused_0"), + StoredEntry( + "unreferenced-epilogue-candidate-key", + epilogue_tuner, + "triton_tem_fused_epilogue_0", + ), + ], + kernel_artifacts=[StoredArtifact(0)], + ) + entry = SimpleNamespace(compiled_fw=SimpleNamespace(result=graph), compiled_bw=None) + data = pickle.dumps((entry, {}, {})) + + def deserialize(copied): + owner = SerializableCompiledFunction(lambda args: None, lambda: copied) + @simple_wraps(owner) + def compiled(*args): + return owner(list(args)) + compiled.serialize = owner.serialize + return compiled + + monkeypatch.setattr(aot_autograd_result, "deserialize_bundled_cache_entry", deserialize) + monkeypatch.setattr(standalone_compile, "AOTCompiledArtifact", lambda compiled: compiled) + with bind_device("cuda:1", freeze_tuning=False): + _, compressed = aot._load_inductor(data, torch.device("cuda", 0), frozen=False) + + portable = pickle.loads(zlib.decompress(compressed))[0].compiled_fw.result + assert portable.device_idxs == OrderedSet((1,)) + assert "torch.cuda.set_device(1)" in portable.source_code + assert portable._triton_bundle.kernel_artifacts[0].device == 1 + assert len(portable._triton_bundle.static_autotuners) == 1 + relocated = portable._triton_bundle.static_autotuners[0] + assert relocated.kernel_name == "triton_red_fused_0" + assert relocated.cache_key != orig_key + assert relocated.kernel.device_props.index == 1 + assert relocated.kernel.triton_meta["device"] == 1 + assert relocated.kernel.compile_results[0].compile_meta["device"] == 1 + assert relocated.kernel.compile_results[0].config.kwargs == selected.kwargs + + +@pytest.mark.parametrize("target,freeze_tuning", [(0, True), (1, False), (1, True)]) +def test_relocate_inductor_skips_prefix_colliding_unreferenced_candidate_in_memory(monkeypatch, target, freeze_tuning): + from torch._inductor.output_code import CompiledFxGraph + from torch.utils._ordered_set import OrderedSet + from torch._inductor.async_compile import CompiledTritonKernels + from torch._inductor.codecache import code_hash + from ignition.preparation.inductor_tuning import InductorSelections + + tuner, _ = restored_reduction(monkeypatch) + bound_tuner = copy.copy(tuner) + bound_tuner.compile_results = [copy.copy(tuner.compile_results[0])] + bound_tuner.compile_results[0].compile_meta = {"device": 0} + bound_tuner.inductor_meta = dict(tuner.inductor_meta) + bound_tuner.triton_meta = {"device": 0} + bound_tuner.device_props = DeviceProperties(0) + + cand, _ = restored_reduction(monkeypatch) + epilogue_tuner = StoredTuner() + epilogue_tuner.compile_results = [copy.copy(cand.compile_results[0]), copy.copy(cand.compile_results[0])] + for res in epilogue_tuner.compile_results: + res.compile_meta = {"device": 0} + epilogue_tuner.inductor_meta = {"dynamic_scale_rblock": True, "coordinate_descent_tuning": True} + epilogue_tuner.triton_meta = {"device": 0} + epilogue_tuner.device_props = DeviceProperties(0) + + kernel_source = "device = DeviceProperties(index=0)\n" + orig_source = ( + "torch.cuda.set_device(0)\n" + "triton_tem_fused_10 = async_compile.triton('triton_tem_fused_10', " + repr(kernel_source) + ")\n" + ) + orig_key = CompiledTritonKernels.key(kernel_source) + graph = CompiledFxGraph.__new__(CompiledFxGraph) + graph.compiled_fn_runner = None + graph.device_idxs = OrderedSet((0,)) + graph.source_code = orig_source + graph.cache_key = code_hash(orig_source) + graph._triton_bundle = StoredBundle( + static_autotuners=[ + StoredEntry(orig_key, bound_tuner, "triton_tem_fused_10"), + StoredEntry("prefix-colliding-unused-key", epilogue_tuner, "triton_tem_fused_1"), + ], + kernel_artifacts=[StoredArtifact(0)], + ) + entry = SimpleNamespace(compiled_fw=SimpleNamespace(result=graph), compiled_bw=None) + + def runner(): + pass + + runner.__code__ = compile("pass", f"/tmp/{graph.cache_key}.py", "exec") + fn = type(runner)(runner.__code__, {"triton_tem_fused_10": bound_tuner}) + graph.current_callable = fn + selections = InductorSelections("cuda:0") + bound = SimpleNamespace(backend=SimpleNamespace(artifact=SimpleNamespace(_flare_graph=graph))) + selections.register(bound) + + with bind_device(f"cuda:{target}", freeze_tuning=freeze_tuning): + relocate_inductor(entry, torch.device("cuda", 0), freeze_tuning=freeze_tuning) + + assert len(graph._triton_bundle.static_autotuners) == 1 + assert graph._triton_bundle.static_autotuners[0].kernel_name == "triton_tem_fused_10" + assert bound_tuner.device_props.index == target + assert bound_tuner.triton_meta["device"] == target + assert bound_tuner.compile_results[0].compile_meta["device"] == target + if freeze_tuning: + assert bound_tuner.inductor_meta["dynamic_scale_rblock"] is False + assert bound_tuner.inductor_meta["coordinate_descent_tuning"] is False + assert epilogue_tuner.device_props.index == 0 + assert epilogue_tuner.triton_meta["device"] == 0 + assert all(res.compile_meta["device"] == 0 for res in epilogue_tuner.compile_results) + assert epilogue_tuner.inductor_meta == {"dynamic_scale_rblock": True, "coordinate_descent_tuning": True} + + +@pytest.mark.parametrize("target,freeze_tuning", [(0, True), (2, False), (2, True)]) +def test_relocate_inductor_rejects_referenced_unbound_kernel_without_partial_mutation(monkeypatch, target, freeze_tuning): + from torch._inductor.output_code import CompiledFxGraph + from torch.utils._ordered_set import OrderedSet + from torch._inductor.async_compile import CompiledTritonKernels + from torch._inductor.codecache import code_hash + + tuner, _ = restored_reduction(monkeypatch) + first_tuner = copy.copy(tuner) + first_tuner.compile_results = [copy.copy(tuner.compile_results[0])] + first_tuner.compile_results[0].compile_meta = {"device": 0} + orig_inductor_meta = {**tuner.inductor_meta, "dynamic_scale_rblock": True, "coordinate_descent_tuning": True} + first_tuner.inductor_meta = dict(orig_inductor_meta) + first_tuner.triton_meta = {"device": 0} + first_tuner.device_props = DeviceProperties(0) + + unbound_tuner = StoredTuner() + unbound_tuner.compile_results = [] + unbound_tuner.triton_meta = {"device": 0} + unbound_tuner.device_props = DeviceProperties(0) + + kernel_source = "device = DeviceProperties(index=0)\n" + orig_source = ( + "torch.cuda.set_device(0)\n" + "triton_red_fused_0 = async_compile.triton('triton_red_fused_0', " + repr(kernel_source) + ")\n" + "triton_poi_missing_1.run(stream=get_raw_stream(0))\n" + ) + orig_cache_key = code_hash(orig_source) + orig_bundle = StoredBundle( + static_autotuners=[ + StoredEntry(CompiledTritonKernels.key(kernel_source), first_tuner, "triton_red_fused_0"), + StoredEntry("missing-source-binding-key", unbound_tuner, "triton_poi_missing_1"), + ], + kernel_artifacts=[StoredArtifact(0)], + ) + graph = CompiledFxGraph.__new__(CompiledFxGraph) + graph.compiled_fn_runner = None + graph.device_idxs = OrderedSet((0,)) + graph.source_code = orig_source + graph.cache_key = orig_cache_key + graph._triton_bundle = orig_bundle + entry = SimpleNamespace(compiled_fw=SimpleNamespace(result=graph), compiled_bw=None) + + with bind_device(f"cuda:{target}", freeze_tuning=freeze_tuning): + with pytest.raises(ValueError, match="unbound static Inductor kernels"): + relocate_inductor(entry, torch.device("cuda", 0), freeze_tuning=freeze_tuning) + + assert graph.source_code == orig_source + assert graph.cache_key == orig_cache_key + assert graph.device_idxs == OrderedSet((0,)) + assert graph._triton_bundle is orig_bundle + assert orig_bundle.kernel_artifacts[0].device == 0 + assert first_tuner.device_props.index == 0 + assert first_tuner.triton_meta["device"] == 0 + assert first_tuner.compile_results[0].compile_meta["device"] == 0 + assert first_tuner.inductor_meta == orig_inductor_meta + + +def test_register_and_relocate_reject_aliased_triton_literal_without_partial_mutation(monkeypatch): + from torch._inductor.output_code import CompiledFxGraph + from torch.utils._ordered_set import OrderedSet + from torch._inductor.async_compile import CompiledTritonKernels + from torch._inductor.codecache import code_hash + from ignition.preparation import inductor_tuning + from ignition.preparation.inductor_tuning import InductorSelections + + tuner, selected = restored_reduction(monkeypatch) + bound_tuner = copy.copy(tuner) + orig_result = copy.copy(tuner.compile_results[0]) + orig_result.compile_meta = {"device": 0} + bound_tuner.compile_results = [orig_result] + bound_tuner.inductor_meta = dict(tuner.inductor_meta) + bound_tuner.triton_meta = {"device": 0} + bound_tuner.device_props = DeviceProperties(0) + + other_tuner, other_selected = restored_reduction(monkeypatch) + other_result = copy.copy(other_tuner.compile_results[0]) + other_result.config = copy.copy(other_selected) + other_result.config.num_warps = selected.num_warps + 4 + other_result._flare_config_state = dict(other_result.config.__dict__) + monkeypatch.setattr(inductor_tuning, "_materialize_selected_cubin", lambda result: None) + + unbound_tuner = StoredTuner() + unbound_tuner.compile_results = [] + unbound_tuner.triton_meta = {"device": 0} + unbound_tuner.device_props = DeviceProperties(0) + + kernel_source = "device = DeviceProperties(index=0)\n" + orig_source = ( + "torch.cuda.set_device(0)\n" + "alias = async_compile.triton('kernel_x', " + repr(kernel_source) + ")\n" + ) + orig_key = CompiledTritonKernels.key(kernel_source) + graph = CompiledFxGraph.__new__(CompiledFxGraph) + graph.compiled_fn_runner = None + graph.device_idxs = OrderedSet((0,)) + graph.source_code = orig_source + graph.cache_key = code_hash(orig_source) + graph._triton_bundle = StoredBundle( + static_autotuners=[ + StoredEntry(orig_key, bound_tuner, "kernel_x"), + StoredEntry("aliased-unbound-key", unbound_tuner, "kernel_x"), + StoredEntry("aliased-unbound-key", unbound_tuner, "triton_unused_shadow"), + ], + kernel_artifacts=[StoredArtifact(0)], + ) + + def runner(): + pass + + runner.__code__ = compile("pass", f"/tmp/{graph.cache_key}.py", "exec") + graph.current_callable = type(runner)(runner.__code__, {"alias": bound_tuner}) + + selections = InductorSelections("cuda:0") + identity = CompiledTritonKernels.key(kernel_source) + selections.winners[identity] = pickle.dumps(other_result) + bound = SimpleNamespace(backend=SimpleNamespace(artifact=SimpleNamespace(_flare_graph=graph))) + + with pytest.raises(ValueError, match="unbound static Inductor kernels"): + selections.register(bound) + + assert selections.instances == {} + assert selections.forwards == {} + assert bound_tuner.compile_results == [orig_result] + + entry = SimpleNamespace(compiled_fw=SimpleNamespace(result=graph), compiled_bw=None) + with bind_device("cuda:1"): + with pytest.raises(ValueError, match="unbound static Inductor kernels"): + relocate_inductor(entry, torch.device("cuda", 0)) + + assert graph.device_idxs == OrderedSet((0,)) + assert bound_tuner.device_props.index == 0 + assert bound_tuner.triton_meta["device"] == 0 + + +def test_register_preserves_distinct_tuners_sharing_source_key(monkeypatch): + from torch._inductor.output_code import CompiledFxGraph + from torch.utils._ordered_set import OrderedSet + from torch._inductor.async_compile import CompiledTritonKernels + from torch._inductor.codecache import code_hash + from ignition.preparation import inductor_tuning + from ignition.preparation.inductor_tuning import InductorSelections + + tuner_a, selected = restored_reduction(monkeypatch) + tuner_a = copy.copy(tuner_a) + tuner_a.compile_results = [copy.copy(tuner_a.compile_results[0])] + tuner_a.inductor_meta = dict(tuner_a.inductor_meta) + tuner_a.triton_meta = {"device": 0} + + tuner_b, _ = restored_reduction(monkeypatch) + tuner_b = copy.copy(tuner_b) + tuner_b.compile_results = [copy.copy(tuner_b.compile_results[0])] + tuner_b.inductor_meta = dict(tuner_b.inductor_meta) + tuner_b.triton_meta = {"device": 0} + + winner_tuner, winner_selected = restored_reduction(monkeypatch) + winner_result = copy.copy(winner_tuner.compile_results[0]) + winner_result.config = copy.copy(winner_selected) + winner_result.config.num_warps = selected.num_warps + 4 + winner_result._flare_config_state = dict(winner_result.config.__dict__) + monkeypatch.setattr(inductor_tuning, "_materialize_selected_cubin", lambda result: None) + + kernel_source = "device = DeviceProperties(index=0)\n" + orig_source = ( + "torch.cuda.set_device(0)\n" + "kernel_a = async_compile.triton('kernel_a', " + repr(kernel_source) + ")\n" + "kernel_b = async_compile.triton('kernel_b', " + repr(kernel_source) + ")\n" + ) + orig_key = CompiledTritonKernels.key(kernel_source) + graph = CompiledFxGraph.__new__(CompiledFxGraph) + graph.compiled_fn_runner = None + graph.device_idxs = OrderedSet((0,)) + graph.source_code = orig_source + graph.cache_key = code_hash(orig_source) + graph._triton_bundle = StoredBundle( + static_autotuners=[StoredEntry(orig_key, tuner_a, "kernel_a")], + kernel_artifacts=[StoredArtifact(0)], + ) + + def runner(): + pass + + runner.__code__ = compile("pass", f"/tmp/{graph.cache_key}.py", "exec") + graph.current_callable = type(runner)(runner.__code__, {"kernel_a": tuner_a, "kernel_b": tuner_b}) + + selections = InductorSelections("cuda:0") + identity = CompiledTritonKernels.key(kernel_source) + selections.winners[identity] = pickle.dumps(winner_result) + bound = SimpleNamespace(backend=SimpleNamespace(artifact=SimpleNamespace(_flare_graph=graph))) + selections.register(bound) + + assert set(selections.instances[identity]) == {id(tuner_a), id(tuner_b)} + assert tuner_a.compile_results[0].config.num_warps == selected.num_warps + 4 + assert tuner_b.compile_results[0].config.num_warps == selected.num_warps + 4