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