From 7038cd3b18efdcbd8b9c8ce3213605ba645d76c1 Mon Sep 17 00:00:00 2001 From: Nicolas Pereira Ribeiro Date: Fri, 27 Nov 2026 17:52:56 +0100 Subject: [PATCH 1/2] Flag kernels whose temporaries are sized while they run, instead of refusing the program (#121) A temporary sized by a value the kernel reads or computes while it runs (lavamd's neighbor_counts[l]) has no caller that can allocate it, so widen_scratch raised UnsupportedNest and default_scopes stopped the program at stage 3. Only Tactics' own per-kernel checks need that size; the built kernel allocates its temporaries itself. - widen_scratch raises RuntimeSizedScratch, naming every such array; prepare catches it and gives the kernel no NumPy oracle (unspelled), with its arguments minus the scratch. - default_scopes reports the arrays in KernelScope.runtime_sized; the kernel's check is left to the whole program, and default_build gives it its first configuration instead of a sweep (the sweep raised ValueError on any kernel without an oracle). - Placement keeps a flagged kernel on the CPU; run-on-gpu on one is refused with why. - The whole-program run passes a scalar input the program takes as a symbol (ls3df_scf's dvol, warpx_esirkepov_deposition's do_ionization), which raised KeyError at init. Co-Authored-By: Claude Opus 5.5 --- docs/oracle.md | 5 ++- tactics/corpus/translate.py | 31 +++++++++++-- tactics/ir/emit_python.py | 61 +++++++++++++++++-------- tactics/session.py | 10 +++-- tactics/stages/performance.py | 17 ++++++- tactics/stages/placement.py | 19 ++++++-- tactics/stages/scopes.py | 10 ++++- tests/test_program_scalar_symbols.py | 44 +++++++++++++++++++ tests/test_runtime_sized_scratch.py | 66 ++++++++++++++++++++++++++++ 9 files changed, 233 insertions(+), 30 deletions(-) create mode 100644 tests/test_program_scalar_symbols.py create mode 100644 tests/test_runtime_sized_scratch.py diff --git a/docs/oracle.md b/docs/oracle.md index f25d1a3..66541d0 100644 --- a/docs/oracle.md +++ b/docs/oracle.md @@ -32,7 +32,10 @@ is made positive definite (`make_inputs`), so both sides of the comparison facto ## Contract - **Caller allocates.** Inputs, outputs and scratch arrays are buffer parameters written in place; only scalars - are locals. A scratch buffer is sized at its loop's extreme value, as a function of size symbols only. + are locals. A scratch buffer is sized at its loop's extreme value, as a function of size symbols only. One sized + by a value the kernel reads or computes while it runs (`lavamd`'s `neighbor_counts[l]`) has no caller that can + size it: the kernel has no oracle and allocates it itself, stage 3 flags it (`KernelScope.runtime_sized`), the whole + program checks it, and it stays on the CPU. - **Python tasklets only.** A tasklet in another language is refused, never translated. - **Loud refusals.** A construct the emitter does not model raises `UnsupportedNest`; it never emits wrong code. - **One signature.** The function's parameters are the kernel's `extern "C"` arguments, in order. diff --git a/tactics/corpus/translate.py b/tactics/corpus/translate.py index d7d3e57..a64891b 100644 --- a/tactics/corpus/translate.py +++ b/tactics/corpus/translate.py @@ -6,7 +6,14 @@ from dataclasses import dataclass -from tactics.ir.emit_python import UnsupportedNest, kernel_args, kernel_arrays, oracle_sdfg, render +from tactics.ir.emit_python import ( + RuntimeSizedScratch, + UnsupportedNest, + kernel_args, + kernel_arrays, + oracle_sdfg, + render, +) from tactics.ir.extract import Boundary @@ -20,13 +27,31 @@ class Prepared: #: Why the body has no NumPy spelling (a C++ tasklet: a vectorized body), so builds of the kernel go unchecked #: and the whole program checks them; empty when ``numpy_source`` is the oracle. unspelled: str = "" + #: The temporaries the kernel sizes while it runs (:class:`RuntimeSizedScratch`); the kernel allocates them. + runtime_sized: tuple[str, ...] = () def prepare(boundary: Boundary, name: str) -> Prepared: - """The NumPy oracle of one extracted kernel; one whose body NumPy cannot spell keeps its arguments, no source.""" - sdfg = oracle_sdfg(boundary) + """The NumPy oracle of one extracted kernel; one whose body NumPy cannot spell, or whose temporaries are sized + while it runs, keeps its arguments, no source.""" + try: + sdfg = oracle_sdfg(boundary) + except RuntimeSizedScratch as err: + args = kernel_args(boundary, kernel_arrays(boundary, boundary.standalone_sdfg, scratch=False)) + why = f"the kernel sizes {', '.join(err.arrays)} while it runs, so it has no NumPy oracle: {err}" + return Prepared(name, "", tuple(args), unspelled=why, runtime_sized=err.arrays) args = kernel_args(boundary, kernel_arrays(boundary, sdfg)) try: return Prepared(name, render(name, args, sdfg), tuple(args)) except UnsupportedNest as err: return Prepared(name, "", tuple(args), unspelled=f"the kernel has no NumPy oracle: {err}") + + +def runtime_sized_scratch(boundary: Boundary) -> tuple[str, ...]: + """The temporaries of the kernel ``boundary`` bounds that it sizes while it runs; empty when a caller can size + every one.""" + try: + oracle_sdfg(boundary) + except RuntimeSizedScratch as err: + return err.arrays + return () diff --git a/tactics/ir/emit_python.py b/tactics/ir/emit_python.py index 904dacc..9637ab8 100644 --- a/tactics/ir/emit_python.py +++ b/tactics/ir/emit_python.py @@ -64,6 +64,17 @@ class UnsupportedNest(Exception): __slots__ = () +class RuntimeSizedScratch(UnsupportedNest): + """A kernel temporary is sized by a value the kernel reads or computes while it runs (``lavamd``'s + ``neighbor_counts[l]``), so no caller can allocate it: the kernel has no NumPy oracle and allocates it itself.""" + + __slots__ = ("arrays",) + + def __init__(self, message: str, arrays: tuple[str, ...]) -> None: + super().__init__(message) + self.arrays = arrays + + #: Math intrinsic in tasklet code -> its NumPy spelling. NP_FUNCTIONS = { **{fn: fn for fn in ("sqrt", "cbrt", "exp", "exp2", "expm1", "log", "log2", "log10", "log1p", "sin", "cos")}, @@ -530,35 +541,48 @@ def positive_as_sizes(expr: sympy.Expr) -> bool: return expr.xreplace(sizes).is_positive is True -def widen_scratch(sdfg: dace.SDFG, symbols: Iterable[str]) -> None: - """Size each transient shaped by a loop variable at that variable's extreme value, so the caller can allocate it; - refuse one whose extent the caller cannot evaluate.""" - known = set(symbols) +def loop_ranges(sdfg: dace.SDFG) -> dict[str, tuple[Any, Any]]: + """``(start, end)`` of every loop variable of ``sdfg`` whose bounds loop analysis finds.""" ranges: dict[str, tuple[Any, Any]] = {} for region in sdfg.all_control_flow_regions(): if isinstance(region, LoopRegion) and region.loop_variable: start, end = loop_analysis.get_init_assignment(region), loop_analysis.get_loop_end(region) if start is not None and end is not None: ranges[region.loop_variable] = (start, end) + return ranges + + +def widest(dim: Any, ranges: dict[str, tuple[Any, Any]]) -> sympy.Expr: + """``dim`` with each loop variable at its extreme value.""" + extent = sympy.sympify(dim) + for _ in range(len(ranges) + 1): # a bound may itself name an outer loop's variable + loop_vars = [s for s in extent.free_symbols if str(s) in ranges] + if not loop_vars: + break + for var in loop_vars: + lo, hi = ranges[str(var)] + extent = sympy.Max(extent.subs(var, lo), extent.subs(var, hi)) # monotone in var + return simplify_as_sizes(extent) + + +def widen_scratch(sdfg: dace.SDFG, symbols: Iterable[str]) -> None: + """Size each transient shaped by a loop variable at that variable's extreme value, so the caller can allocate it; + refuse, naming every one, the transients whose extent the caller cannot evaluate (:class:`RuntimeSizedScratch`).""" + known, ranges = set(symbols), loop_ranges(sdfg) + refused: dict[str, str] = {} for name in scratch_arrays(sdfg): desc = sdfg.arrays[name] shape = [] for dim in desc.shape: - extent = sympy.sympify(dim) - for level in range(len(ranges) + 1): # a bound may itself name an outer loop's variable - loop_vars = [s for s in extent.free_symbols if str(s) in ranges] - if not loop_vars: - break - for var in loop_vars: - lo, hi = ranges[str(var)] - extent = sympy.Max(extent.subs(var, lo), extent.subs(var, hi)) # monotone in var - extent = simplify_as_sizes(extent) + extent = widest(dim, ranges) unknown = sorted(str(s) for s in extent.free_symbols if str(s) not in known) if unknown: - raise UnsupportedNest(f"scratch buffer {name!r} has extent {dim}, which depends on {unknown}") + refused.setdefault(name, f"scratch buffer {name!r} has extent {dim}, which depends on {unknown}") shape.append(extent) - if shape != list(desc.shape): + if name not in refused and shape != list(desc.shape): sdfg.arrays[name] = dt.Array(desc.dtype, shape, transient=True, storage=desc.storage) + if refused: + raise RuntimeSizedScratch("; ".join(refused.values()), tuple(refused)) # emission of a lowered SDFG @@ -1251,10 +1275,11 @@ def hoist_nested_scratch(sdfg: dace.SDFG) -> None: sdfg.arrays[fresh] = copy.deepcopy(nested.arrays[fresh]) -def kernel_arrays(boundary: Boundary, sdfg: dace.SDFG) -> list[str]: - """Array arguments in signature order: inputs, further outputs, then scratch, since a kernel allocates nothing.""" +def kernel_arrays(boundary: Boundary, sdfg: dace.SDFG, scratch: bool = True) -> list[str]: + """Array arguments in signature order: inputs, further outputs, then scratch, since a kernel allocates nothing; + without ``scratch`` for a kernel that allocates its own (:class:`RuntimeSizedScratch`).""" names = list(boundary.inputs) + [o for o in boundary.outputs if o not in boundary.inputs] - return names + [s for s in scratch_arrays(sdfg) if s not in names] + return names + [s for s in scratch_arrays(sdfg) if s not in names] if scratch else names def kernel_args(boundary: Boundary, arrays: list[str]) -> list[str]: diff --git a/tactics/session.py b/tactics/session.py index 4c1774a..9d09794 100644 --- a/tactics/session.py +++ b/tactics/session.py @@ -58,7 +58,7 @@ ) from tactics.build.sdfg import PERSISTENT_MIN_BYTES, force_register_arrays, make_persistent from tactics.build.toolchain import SymbolValue, parse_params, raw_signature -from tactics.corpus.translate import Prepared, prepare +from tactics.corpus.translate import Prepared, prepare, runtime_sized_scratch from tactics.ir.comm import Skeleton, comm_class, isolation_refusal, skeleton, skeleton_difference from tactics.ir.dace_types import strings from tactics.ir.depends import KernelGraph, UnsupportedProgram, kernel_dependencies @@ -600,6 +600,9 @@ class KernelScope(Record): writes: tuple[str, ...] symbols: tuple[str, ...] parallel: bool + #: Temporaries the kernel sizes while it runs: it allocates them itself, has no NumPy oracle (the whole program + #: checks it) and stays on the CPU. + runtime_sized: tuple[str, ...] = () class KernelInfo(Record): @@ -2420,6 +2423,7 @@ def default_scopes(self) -> list[KernelScope]: writes=tuple(boundary.outputs), symbols=tuple(boundary.symbols), parallel=is_parallel_kernel(ext), + runtime_sized=() if ext.numpy_source else runtime_sized_scratch(boundary), ) for ext, boundary in lowered ] @@ -3087,12 +3091,12 @@ def default_build(self, name: str) -> None: """Build and link a kernel that has no build: stage 5's first configuration, or under ``codegen="sweep"`` the winner of stage 6's sweep (one swept before for the same source and sizes is relinked, not swept again; a sweep without a correct winner falls back to the first configuration, and so does a kernel taking a symbol - only the running program computes: its oracle has no value for it).""" + only the running program computes, or one without a NumPy oracle: nothing checks its variants).""" if self.codegen == "first" or self.pipeline is not None: self.first_build(name) return src = self.default_kernel(name) - if computed_symbols(src, self.kernel_sizes(name)): + if computed_symbols(src, self.kernel_sizes(name)) or self.prepare_kernel(name).unspelled: self.optimize_kernel(name) return known = self.swept.get(self.sweep_key(name, src)) diff --git a/tactics/stages/performance.py b/tactics/stages/performance.py index aaab6b7..430484f 100644 --- a/tactics/stages/performance.py +++ b/tactics/stages/performance.py @@ -180,6 +180,20 @@ def program_buffers( return buffers +def program_symbols( + sdfg: dace.SDFG, inputs: dict[str, np.ndarray], sizes: Mapping[str, SymbolValue] +) -> dict[str, SymbolValue]: + """``sizes``, and the value of each scalar input the program takes as a symbol: canonicalization makes a scalar + parameter a symbol where it sizes or bounds something (``ls3df_scf``'s ``dvol``), and the bench passes it as a + 0-d array, not a size.""" + scalars: dict[str, SymbolValue] = { + name: inputs[name].item() + for name in sorted(map(str, sdfg.free_symbols)) + if name not in sizes and name in inputs and np.ndim(inputs[name]) == 0 + } + return {**sizes, **scalars} + + def time_program( sdfg: dace.SDFG, out_dir: Path, @@ -197,8 +211,9 @@ def time_program( except Exception as err: # noqa: BLE001 -- a refused build is feedback, not a crash return ProgramReport(error=f"{type(err).__name__}: {err}") frame = out_dir / "src" / "cpu" / f"{program.name}.cpp" + symbols = program_symbols(sdfg, inputs, sizes) call = ProgramCall( - so_path, frame.read_text(), program.name, program_buffers(sdfg, inputs, sizes), sizes, reps, reference + so_path, frame.read_text(), program.name, program_buffers(sdfg, inputs, sizes), symbols, reps, reference ) timed = run_spawned(run_program, call) if gpu else run_isolated(lambda: run_program(call), ProgramTime) if isinstance(timed, Failure): diff --git a/tactics/stages/placement.py b/tactics/stages/placement.py index f2dbb63..76e47bc 100644 --- a/tactics/stages/placement.py +++ b/tactics/stages/placement.py @@ -25,7 +25,7 @@ from tactics.ir.depends import KernelGraph from tactics.stages.canonicalize import Targets from tactics.stages.expand import is_device_implementation, is_host_implementation -from tactics.stages.scopes import is_parallel_kernel +from tactics.stages.scopes import is_parallel_kernel, kernel_runtime_sized DEVICES = ("cpu", "gpu") @@ -101,13 +101,14 @@ def pinned_implementations(ext: ExternalCall) -> list[str]: def default_device(ext: ExternalCall, targets: Targets) -> str: """A kernel holding a call pinned to a device library on the GPU, one pinned to a host library on the CPU; - otherwise parallel kernels (doalls, library calls among them) on the GPU when it is a target.""" + otherwise parallel kernels (doalls, library calls among them) on the GPU when it is a target, except one that + sizes a temporary while it runs (:func:`kernel_runtime_sized`): a GPU kernel cannot allocate it.""" pinned = pinned_implementations(ext) if targets.gpu and any(is_device_implementation(i) for i in pinned): return "gpu" if any(is_host_implementation(i) for i in pinned): return "cpu" - return "gpu" if targets.gpu and is_parallel_kernel(ext) else "cpu" + return "gpu" if targets.gpu and is_parallel_kernel(ext) and not kernel_runtime_sized(ext) else "cpu" def default_devices(sdfg: dace.SDFG, targets: Targets) -> dict[str, str]: @@ -178,6 +179,18 @@ def check_devices(sdfg: dace.SDFG, targets: Targets, devices: dict[str, str]) -> return f"{', '.join(bad)}: a device is 'cpu' or 'gpu'." if not targets.gpu and "gpu" in devices.values(): return "the GPU is not a target of this session; every kernel runs on the CPU." + return runtime_sized_on_gpu(sdfg, devices) + + +def runtime_sized_on_gpu(sdfg: dace.SDFG, devices: dict[str, str]) -> str | None: + """Why a kernel ``devices`` puts on the GPU cannot run there: it sizes a temporary while it runs; or ``None``.""" + for ext in external_calls(sdfg): + sized = kernel_runtime_sized(ext) if devices.get(ext.name) == "gpu" else () + if sized: + return ( + f"{ext.name} sizes {', '.join(sized)} while it runs, which a GPU kernel cannot allocate; " + f"place it on the cpu." + ) return None diff --git a/tactics/stages/scopes.py b/tactics/stages/scopes.py index 2d484c1..efa9991 100644 --- a/tactics/stages/scopes.py +++ b/tactics/stages/scopes.py @@ -34,7 +34,7 @@ from dace.transformation.passes.outline_to_external_calls import reference_sdfg from dace.utils import find_new_name -from tactics.corpus.translate import prepare +from tactics.corpus.translate import prepare, runtime_sized_scratch from tactics.ir.comm import comm_class from tactics.ir.dace_types import strings from tactics.ir.extract import ( @@ -107,6 +107,14 @@ def node_boundary(ext: ExternalCall) -> Boundary: return Boundary(inputs, outputs, symbols, nsdfg_node=None, state=None, standalone_sdfg=nest) +def kernel_runtime_sized(ext: ExternalCall) -> tuple[str, ...]: + """The temporaries kernel ``ext`` sizes while it runs (:func:`runtime_sized_scratch`); only a kernel without a + NumPy oracle can have any, so one with an oracle costs nothing.""" + if ext.numpy_source or ext.standalone_sdfg is None: + return () + return runtime_sized_scratch(node_boundary(ext)) + + def connector(prefixed: Callable[[str], str], conn: str | None) -> str | None: """``prefixed(conn)``, or ``None`` for an ordering edge, which has no connector.""" return None if conn is None else prefixed(conn) diff --git a/tests/test_program_scalar_symbols.py b/tests/test_program_scalar_symbols.py new file mode 100644 index 0000000..af7463e --- /dev/null +++ b/tests/test_program_scalar_symbols.py @@ -0,0 +1,44 @@ +# Copyright 2021 ETH Zurich and the Tactics authors. +# SPDX-License-Identifier: GPL-3.0-or-later +"""A scalar parameter the program takes as a symbol gets its value from the bench's 0-d input in the whole-program +run, as a size would.""" + +import dace +import numpy as np + +from tactics.stages.performance import program_symbols + +N = dace.symbol("N", dtype=dace.int64) + + +def scaled_by_symbol() -> dace.SDFG: + """``y = x * dvol`` with ``dvol`` a symbol of the program, as canonicalization leaves ``ls3df_scf``'s.""" + sdfg = dace.SDFG("scaled_by_symbol") + sdfg.add_symbol("dvol", dace.float64) + sdfg.add_array("x", [N], dace.float64) + sdfg.add_array("y", [N], dace.float64) + state = sdfg.add_state() + state.add_mapped_tasklet( + "scale", + {"i": "0:N"}, + {"a": dace.Memlet("x[i]")}, + "b = a * dvol", + {"b": dace.Memlet("y[i]")}, + external_edges=True, + ) + return sdfg + + +# Reproducer: the whole-program run raised KeyError on a scalar parameter canonicalized to a symbol (#121 follow-up, ls3df_scf dvol, warpx_esirkepov_deposition do_ionization) +def test_a_scalar_input_the_program_takes_as_a_symbol_reaches_the_run_as_a_symbol_value() -> None: + sdfg = scaled_by_symbol() + inputs = {"x": np.ones(4), "dvol": np.array(0.008), "unused": np.array(3)} + symbols = program_symbols(sdfg, inputs, {"N": 4}) + assert symbols == {"N": 4, "dvol": 0.008} + assert isinstance(symbols["dvol"], float) + + +def test_a_size_given_twice_keeps_the_size() -> None: + sdfg = scaled_by_symbol() + symbols = program_symbols(sdfg, {"N": np.array(9), "dvol": np.array(1.0)}, {"N": 4}) + assert symbols["N"] == 4 diff --git a/tests/test_runtime_sized_scratch.py b/tests/test_runtime_sized_scratch.py new file mode 100644 index 0000000..1a4fba9 --- /dev/null +++ b/tests/test_runtime_sized_scratch.py @@ -0,0 +1,66 @@ +# Copyright 2021 ETH Zurich and the Tactics authors. +# SPDX-License-Identifier: GPL-3.0-or-later +"""A kernel whose temporary is sized by a value it reads while it runs (``lavamd``'s ``neighbor_counts[l]``): stage 3 +flags it instead of refusing the program, it has no NumPy oracle, and placement keeps it on the CPU.""" + +import dace +import numpy as np +import pytest + +from tactics.corpus.translate import prepare, runtime_sized_scratch +from tactics.ir.emit_python import RuntimeSizedScratch, oracle_sdfg +from tactics.records import MoveStatus +from tactics.session import Session +from tactics.stages.canonicalize import Targets +from tactics.stages.scopes import node_boundary + +N = dace.symbol("N", dtype=dace.int64) +M = dace.symbol("M", dtype=dace.int64) + + +@dace.program +def ragged_rows(counts: dace.int32[N], x: dace.float64[N, M], y: dace.float64[N]) -> None: + for i in range(N): + c = int(counts[i]) + row = np.empty(1 + c, dtype=np.float64) + row[0] = 1.0 + row[1:] = x[i, :c] + y[i] = np.sum(row) + + +def scoped(gpu: bool) -> tuple[Session, list[str]]: + """``ragged_rows`` through stages 1-3; the names of the kernels ``default_scopes`` flagged.""" + session = Session(ragged_rows.to_sdfg(), targets=Targets(gpu=gpu), sizes={"N": 8, "M": 4}) + session.canonicalize() + session.default_moves() + flagged = [k.name for k in session.default_scopes() if k.runtime_sized] + return session, flagged + + +# Reproducer: default_scopes raised UnsupportedNest on a scratch buffer sized by data read in the kernel (#121, lavamd) +def test_a_temporary_sized_by_data_read_in_the_kernel_is_flagged_not_refused() -> None: + session, flagged = scoped(gpu=False) + assert len(flagged) == 1 + ext = session.kernel(flagged[0]) + assert ext.numpy_source == "" + boundary = node_boundary(ext) + with pytest.raises(RuntimeSizedScratch) as err: + oracle_sdfg(boundary) + assert err.value.arrays == runtime_sized_scratch(boundary) + assert err.value.arrays + prep = prepare(boundary, ext.name) + assert prep.numpy_source == "" + assert prep.runtime_sized == err.value.arrays + assert "while it runs" in prep.unspelled + assert not set(prep.args) & set(err.value.arrays) # the kernel allocates its own: no scratch argument + + +def test_a_kernel_sizing_a_temporary_while_it_runs_stays_on_the_cpu() -> None: + session, flagged = scoped(gpu=True) + (name,) = flagged + placed = session.place() + assert placed.status is MoveStatus.APPLIED + assert placed.devices[name] == "cpu" + forced = session.place({name: "gpu"}) + assert forced.status is MoveStatus.ILLEGAL + assert "while it runs" in forced.reason From f75012297fbaaa8f074f7f3e7c5de5fb064f1fc9 Mon Sep 17 00:00:00 2001 From: Nicolas Pereira Ribeiro Date: Fri, 27 Nov 2026 18:02:45 +0100 Subject: [PATCH 2/2] Keep the names of the containers a kernel reads or writes when shortening temporaries shorten_temporaries renamed every generated program container with replace_dict, the __sym_out_ scalar a loop kernel exports its symbol through among them (qe_cegterg's __sym_out_nbase_iter became tmp165). replace_dict rewrites the kernel's abi_order (a string-list property) and, through ExternalCall.rename_symbols, its body, but not its _out_ connectors, so node_boundary took the output for a symbol and stage 5 raised KeyError: 'tmp165' in abi_ready_copy. A container bound to an ExternalCall is part of the kernel's interface and now keeps its name. Co-Authored-By: Claude Opus 5.5 --- tactics/ir/names.py | 14 +++++++++- tests/test_kernel_symbol_outputs.py | 41 +++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 tests/test_kernel_symbol_outputs.py diff --git a/tactics/ir/names.py b/tactics/ir/names.py index 4388503..4841cef 100644 --- a/tactics/ir/names.py +++ b/tactics/ir/names.py @@ -223,6 +223,18 @@ def index_array_of(name: str, arguments: set[str]) -> str | None: return next((a for a in sorted(arguments) if name.endswith(f"_{a}_index") and name != f"{a}_index"), None) +def kernel_bound(sdfg: dace.SDFG) -> set[str]: + """The containers a kernel (``ExternalCall``) of ``sdfg`` reads or writes. Their names are its interface: the + kernel's ``abi_order`` and its body name them bare, its connectors prefixed, and a ``replace_dict`` reaches the + first two only (a loop kernel's ``__sym_out_nbase_iter`` became ``tmp165`` in ``abi_order`` alone, ``qe_cegterg``). + """ + bound: set[str] = set() + for node, state in sdfg.all_nodes_recursive(): + if isinstance(node, ExternalCall): + bound |= {edge.data.data for edge in state.all_edges(node) if edge.data.data is not None} + return bound + + def temporary_renames(sdfg: dace.SDFG, namer: Namer) -> dict[str, str]: """The short name :func:`shorten_temporaries` gives each generated temporary of ``sdfg``, by its name now.""" declared: set[str] = set() @@ -233,7 +245,7 @@ def temporary_renames(sdfg: dace.SDFG, namer: Namer) -> dict[str, str]: for name, desc in sd.arrays.items(): shapes[name] = shapes.get(name, True) and scalar_like(desc) renames: dict[str, str] = {} - for name in sorted(declared - arguments - sdfg.symbols.keys()): + for name in sorted(declared - arguments - sdfg.symbols.keys() - kernel_bound(sdfg)): if name not in shapes: continue index_of = index_array_of(name, arguments) diff --git a/tests/test_kernel_symbol_outputs.py b/tests/test_kernel_symbol_outputs.py new file mode 100644 index 0000000..9f6844b --- /dev/null +++ b/tests/test_kernel_symbol_outputs.py @@ -0,0 +1,41 @@ +# Copyright 2021 ETH Zurich and the Tactics authors. +# SPDX-License-Identifier: GPL-3.0-or-later +"""A loop kernel that exports a symbol the program reads after it (DaCe's ``__sym_out_`` output) keeps one name +for that output in its connectors, its ``abi_order`` and its body, through the label normalization every change runs.""" + +import dace +from dace.libraries.standard.nodes.external_call import data_name + +from tactics.session import Session +from tactics.stages.canonicalize import Targets +from tactics.stages.scopes import node_boundary + +N = dace.symbol("N", dtype=dace.int64) + + +@dace.program +def count_then_fill(x: dace.float64[N], y: dace.float64[N], z: dace.float64[N]) -> None: + m = 0 + for i in range(1, N): + y[i] = y[i - 1] * x[i] + x[i] + if y[i] > 0.5: + m = m + 1 + z[0:m] = 1.0 + + +# Reproducer: shorten_temporaries renamed a loop kernel's __sym_out_ output in abi_order, not in its connectors (#122, qe_cegterg extcall_for42, KeyError: 'tmp165') +def test_a_kernel_exporting_a_symbol_keeps_its_output_named_alike_in_abi_order_and_connectors() -> None: + session = Session(count_then_fill.to_sdfg(), targets=Targets(gpu=False), sizes={"N": 8}) + session.canonicalize() + session.default_moves() + scopes = session.default_scopes() + (loop,) = [k for k in scopes if any(name.startswith("__sym_out_") for name in k.writes)] + ext = session.kernel(loop.name) + connected = {data_name(conn) for conn in [*ext.in_connectors, *ext.out_connectors]} + exported = [name for name in loop.writes if name.startswith("__sym_out_")] + assert set(exported) <= set(ext.abi_order) + assert set(exported) <= connected + boundary = node_boundary(ext) + assert not set(boundary.symbols) & set(session.sdfg.arrays) # no container taken for a symbol + session.place() + assert session.default_kernel(loop.name).boundary.outputs == boundary.outputs