Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/oracle.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
31 changes: 28 additions & 3 deletions tactics/corpus/translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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 ()
61 changes: 43 additions & 18 deletions tactics/ir/emit_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")},
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]:
Expand Down
14 changes: 13 additions & 1 deletion tactics/ir/names.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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)
Expand Down
10 changes: 7 additions & 3 deletions tactics/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
]
Expand Down Expand Up @@ -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))
Expand Down
17 changes: 16 additions & 1 deletion tactics/stages/performance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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):
Expand Down
19 changes: 16 additions & 3 deletions tactics/stages/placement.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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


Expand Down
10 changes: 9 additions & 1 deletion tactics/stages/scopes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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)
Expand Down
41 changes: 41 additions & 0 deletions tests/test_kernel_symbol_outputs.py
Original file line number Diff line number Diff line change
@@ -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_<s>`` 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
Loading
Loading