Skip to content
Draft
8 changes: 7 additions & 1 deletion dace/codegen/targets/framecode.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from dace.transformation.passes.analysis import loop_analysis
from dace.transformation.passes.analysis.scopes import AccessInstances, AllocationScopes, CodegenAnalysisPipeline
from dace.transformation.passes.canonicalize import supply_num_threads
from dace.transformation.passes.persistent_transients import reassigned_symbols

#: Scalar constants of these types are written as ``constexpr float``: their vendor types have no constexpr
#: constructor.
Expand Down Expand Up @@ -1014,6 +1015,8 @@ def determine_allocation_lifetime(self, top_sdfg: SDFG):

# Symbols-and-constants stays here: it is memoized on this code generator, not on the SDFG.
fsyms = {sdfg.cfg_id: self.symbols_and_constants(sdfg) for sdfg in top_sdfg.all_sdfgs_recursive()}
# Free is not constant: a size symbol the tree also assigns changes between the hoist point and the use
reassigned = {sdfg.cfg_id: reassigned_symbols(sdfg) for sdfg in top_sdfg.all_sdfgs_recursive()}

for sdfg, name, desc in top_sdfg.arrays_recursive(include_nested_data=True):
if isinstance(desc, data.DistributedDescriptor):
Expand Down Expand Up @@ -1176,10 +1179,12 @@ def determine_allocation_lifetime(self, top_sdfg: SDFG):
and not utils.is_nonfree_sym_dependent(
first_node_instance, desc, first_state_instance, fsyms[sdfg.cfg_id]
)
and not {str(s) for s in desc.free_symbols} & reassigned[sdfg.cfg_id]
):
# Placing it at the one state that uses it re-allocates the buffer on every iteration of
# the enclosing loop; the SDFG entry dominates that state, so one buffer serves them all.
# Only the PLACEMENT moves -- ``desc.lifetime`` stays Scope.
# Only the PLACEMENT moves -- ``desc.lifetime`` stays Scope. A size the tree assigns stays
# at the use: at the entry it would keep its first value (QE cegterg's growing subspace).
alloc_scope = sdfg
alloc_state = curstate
else:
Expand Down Expand Up @@ -1630,6 +1635,7 @@ def generate_code(
self._initcode.getvalue(),
self._exitcode.getvalue(),
has_state=bool(self.statestruct),
has_context=any(field.endswith(" *gpu_context;") for field in self.statestruct),
)
else:
if params:
Expand Down
53 changes: 34 additions & 19 deletions dace/cpf_lowering.py
Original file line number Diff line number Diff line change
Expand Up @@ -1696,6 +1696,26 @@ def bfloat16_overloads(vendor: str) -> str:
return "\n".join(lines) + "\n"


def cub_functor(name: str, body: str) -> str:
"""A CUB binary operator ``name`` computing ``body`` (``{a}`` and ``{b}`` the operands) on one type, and on two.

CUB deduces a scan's accumulator from ``op(init, input)``: an ``int8_t`` scan into ``int64_t`` with an ``int64_t``
initial value calls it on two types, which a one-type template cannot deduce (``AccumT=<error-type>``, dbcsr).
The mixed overload works in the common type; the one-type template is more specialized and still wins on equal
types, so a same-type scan is unchanged.
"""
same = body.format(a="a", b="b")
mixed = body.format(a="C(a)", b="C(b)")
return (
f"struct {name} {{\n"
" template <typename T>\n"
f" __host__ __device__ T operator()(const T& a, const T& b) const {{ return {same}; }}\n"
" template <typename T, typename U, typename C = std::common_type_t<T, U>>\n"
f" __host__ __device__ C operator()(const T& a, const U& b) const {{ return {mixed}; }}\n"
"};\n"
)


#: Device preamble blocks only SOME units need, keyed by the identifier that pulls each one in.
#:
#: Same principle as :func:`helpers_used`, and for the same reason: what a unit needs is a property
Expand Down Expand Up @@ -1761,22 +1781,10 @@ def bfloat16_overloads(vendor: str) -> str:
//: keeps the functor structs CCCL 3 dropped, and a unit built by hipcc is never built against CCCL.
namespace gpucub = hipcub;
""",
"cpf_cub_multiplies": "struct cpf_cub_multiplies {\n"
" template <typename T>\n"
" __host__ __device__ T operator()(const T& a, const T& b) const { return a * b; }\n"
"};\n",
"cpf_cub_plus": "struct cpf_cub_plus {\n"
" template <typename T>\n"
" __host__ __device__ T operator()(const T& a, const T& b) const { return a + b; }\n"
"};\n",
"cpf_cub_minimum": "struct cpf_cub_minimum {\n"
" template <typename T>\n"
" __host__ __device__ T operator()(const T& a, const T& b) const { return a < b ? a : b; }\n"
"};\n",
"cpf_cub_maximum": "struct cpf_cub_maximum {\n"
" template <typename T>\n"
" __host__ __device__ T operator()(const T& a, const T& b) const { return a > b ? a : b; }\n"
"};\n",
"cpf_cub_multiplies": cub_functor("cpf_cub_multiplies", "{a} * {b}"),
"cpf_cub_plus": cub_functor("cpf_cub_plus", "{a} + {b}"),
"cpf_cub_minimum": cub_functor("cpf_cub_minimum", "{a} < {b} ? {a} : {b}"),
"cpf_cub_maximum": cub_functor("cpf_cub_maximum", "{a} > {b} ? {a} : {b}"),
"cpf_gpu_atomic": """\
//: A conflicting accumulation, applied atomically under any binary operator.
//:
Expand Down Expand Up @@ -2080,7 +2088,9 @@ def device_preamble(code: str, dialect: Dialect) -> str:
)


def device_entry_prologue(state_struct: str, init_code: str = "", exit_code: str = "", has_state: bool = True) -> str:
def device_entry_prologue(
state_struct: str, init_code: str = "", exit_code: str = "", has_state: bool = True, has_context: bool = True
) -> str:
"""The device setup CPF's single entry function opens with.

An ordinary build does this in ``__dace_init_<name>`` and undoes it in ``__dace_exit_<name>``,
Expand All @@ -2102,6 +2112,8 @@ def device_entry_prologue(state_struct: str, init_code: str = "", exit_code: str
:param exit_code: the state's teardown, the code ``__dace_exit`` would run.
:param has_state: whether the state struct has any field; without boilerplate (:func:`no_boilerplate`) an empty
one is not emitted, so there is no state to declare.
:param has_context: whether the state struct has the ``gpu_context`` field the generated body reaches the
stream through; a unit with no device code has none.
:returns: the prologue lines, indented one level.
"""
teardown = ""
Expand All @@ -2120,12 +2132,15 @@ def device_entry_prologue(state_struct: str, init_code: str = "", exit_code: str
f" {state_struct} __cpf_state{{}};\n {state_struct} *__state = &__cpf_state;\n" if has_state else ""
)
return f"{state}{init_code}{teardown}"
# By name, not as the first initializer: the context is not always the struct's first field, and a unit with no
# device code has no field for it (an empty struct takes no initializer at all).
link = " __cpf_state.gpu_context = &__cpf_context;\n" if has_context else ""
return f"""\
// The device handshake, which a single entry point has nowhere else to put.
cpf_gpu_context __cpf_context{{}};
__cpf_context.streams[0] = nullptr;
{state_struct} __cpf_state{{&__cpf_context}};
{state_struct} *__state = &__cpf_state;
{state_struct} __cpf_state{{}};
{link} {state_struct} *__state = &__cpf_state;
{init_code}
{teardown} struct __cpf_drain {{
~__cpf_drain() {{ cpf_gpu_check(gpuDeviceSynchronize()); }}
Expand Down
10 changes: 9 additions & 1 deletion dace/libraries/standard/block_reduce.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,14 @@ def enclosing_maps(node: nodes.Node, state: SDFGState) -> list[nodes.MapEntry]:
return [s for s in get_parent_map_and_loop_scopes(state.sdfg, node, state) if isinstance(s, nodes.MapEntry)]


def runs_per_thread(entry: nodes.MapEntry) -> bool:
"""Whether the body of ``entry`` is thread-level code although the map is a ``GPU_Device`` map: a kernel whose
grid is final (``explicit_sync``, a megakernel) spans threads, each running its own grid-stride iterations. A
block collective there adds a thread-block map, after which the launch takes the thread range for the grid
(qe_vexx_k's ``copy_psi_to_tg``: 256 times more blocks than a cooperative launch holds)."""
return entry.map.schedule == dtypes.ScheduleType.GPU_Device and entry.map.explicit_sync


def in_kernel_block_implementation(
node: nodes.LibraryNode, state: SDFGState, share_private_outputs: bool = False
) -> str | None:
Expand All @@ -296,7 +304,7 @@ def in_kernel_block_implementation(
maps = enclosing_maps(node, state)
if not any(m.map.schedule == dtypes.ScheduleType.GPU_Device for m in maps):
return None
if any(m.map.schedule in THREAD_LEVEL_SCHEDULES for m in maps):
if any(m.map.schedule in THREAD_LEVEL_SCHEDULES or runs_per_thread(m) for m in maps):
return None
# One thread's work: a block of lanes would idle over a handful of elements
if small_operands(node, state):
Expand Down
21 changes: 21 additions & 0 deletions dace/symbolic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1274,6 +1274,20 @@ def overapproximate(expr):
return _overapproximate(expr)


def _integer_valued(expr) -> bool:
"""Whether ``expr`` is an integer for every value of its symbols: sympy says so, or it is a polynomial with integer
coefficients in DaCe symbols of an integer type (a map index plus a tile offset, ``g + 15``)."""
if expr.is_integer:
return True
names = expr.free_symbols
if not names or not all(isinstance(s, symbol) and s.dtype in dtypes.INTEGER_TYPES for s in names):
return False
try:
return all(c.is_Integer for c in sympy.Poly(expr, *names).coeffs())
except sympy.PolynomialError:
return False


@lru_cache(maxsize=2048, typed=True)
def _overapproximate(expr):
if isinstance(expr, SymExpr):
Expand Down Expand Up @@ -1302,6 +1316,13 @@ def _overapproximate(expr):
# first (measured 4.6x on the miss path). NOT gated on ``is_Add``: the trailing ``+ c`` is a
# Wild that happily binds 0, so ``Min(4, N)`` matches the first pattern with no Add in sight.
if expr.has(sympy.Min):
# ``ceiling`` is monotonic, so ``ceiling(Min(x, y))`` IS ``Min(ceiling(x), ceiling(y))``: spelled that way, a
# tile clipped by a ceiling-valued bound (stockham_fft's ``-g + ceiling(Min(g + 15, ceiling(R**k) - 1)) + 1``)
# reaches the ``Min(a, b) + c`` rule below.
expr = expr.replace(
lambda e: isinstance(e, sympy.ceiling) and isinstance(e.args[0], sympy.Min),
lambda e: sympy.Min(*(arg if _integer_valued(arg) else sympy.ceiling(arg) for arg in e.args[0].args)),
)
a = sympy.Wild("a")
b = sympy.Wild("b")
c = sympy.Wild("c")
Expand Down
13 changes: 13 additions & 0 deletions dace/transformation/dataflow/prune_connectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,19 @@ def _get_prune_sets(self, state: SDFGState) -> tuple[set[str], set[str], set[str
prune_in -= symbolic_uses
prune_out -= symbolic_uses

# A container whose access node carries only empty memlets (an ordering anchor) is neither read nor written,
# so ``read_and_write_sets`` leaves it out, but ``apply`` cannot remove a descriptor a node still names
# (npbench nbody's ``softening`` in a CPF unit: ``Cannot remove data descriptor softening``). Keep it.
if prune_in or prune_out:
anchored = {
node.data
for inner_state in nsdfg.sdfg.states()
for node in inner_state.data_nodes()
if node.data not in all_data_used
}
prune_in -= anchored
prune_out -= anchored

return prune_in, prune_out, all_data_used

def apply(self, state: SDFGState, sdfg: SDFG):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import warnings
from typing import Any

from dace import SDFG, Memlet, dtypes, nodes, properties
from dace import SDFG, Memlet, SDFGState, dtypes, nodes, properties
from dace.transformation import pass_pipeline as ppl
from dace.transformation import transformation

Expand Down Expand Up @@ -128,6 +128,55 @@ def apply_thread_block_maps(sdfg: SDFG, xform: transformation.SingleStateTransfo
return applied


#: The thread-level schedules a map below a megakernel cannot keep: its body already runs per thread.
THREAD_LEVEL_MAP_SCHEDULES = (dtypes.ScheduleType.GPU_ThreadBlock, dtypes.ScheduleType.GPU_ThreadBlock_Dynamic)


def maps_below(kernel: nodes.MapEntry, state: SDFGState) -> list[nodes.MapEntry]:
"""Every map below ``kernel``, through nested SDFGs."""
below: list[nodes.MapEntry] = []
for node in state.scope_subgraph(kernel).nodes():
if isinstance(node, nodes.MapEntry) and node is not kernel:
below.append(node)
elif isinstance(node, nodes.NestedSDFG):
below.extend(n for n, _ in node.sdfg.all_nodes_recursive() if isinstance(n, nodes.MapEntry))
return below


@properties.make_properties
@transformation.explicit_cf_compatible
class SequentialMegakernelBodies(ppl.Pass):
"""Keep the body of a kernel whose grid is final (``explicit_sync``, a megakernel) per thread.

Such a kernel spans threads, each running its own grid-stride iterations, so it has no thread-block level: a
thread-block map below it (the default schedule of a map in a ``GPU_Device`` scope, or a library node expanded
inside it) runs sequentially in its thread instead. Left a thread-block map, it stops ``AddThreadBlockMaps`` from
tiling the kernel, and the launch then takes the kernel's thread range for its grid (qe_vexx_k: 256 times more
blocks than a cooperative launch holds).
"""

def modifies(self) -> ppl.Modifies:
return ppl.Modifies.Nodes

def should_reapply(self, modified: ppl.Modifies) -> bool:
return False

def apply_pass(self, sdfg: SDFG, pipeline_results: dict[str, Any]) -> int | None:
demoted = 0
for node, state in sdfg.all_nodes_recursive():
if (
isinstance(node, nodes.MapEntry)
and node.map.schedule == dtypes.ScheduleType.GPU_Device
and node.map.explicit_sync
):
for inner in maps_below(node, state):
if inner.map.schedule in THREAD_LEVEL_MAP_SCHEDULES:
inner.map.schedule = dtypes.ScheduleType.Sequential
inner.map.gpu_force_syncthreads = False
demoted += 1
return demoted or None


@properties.make_properties
@transformation.explicit_cf_compatible
class AddThreadBlockMaps(ppl.Pass):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ def __init__(self, memory_engine_copies: bool | None = None):
ExpandLibraryNodes,
InferDefaultSchedulesAndStorages,
ReinferConnectorTypes,
SequentialMegakernelBodies,
SynchronizeStreamUnawareGPUCallbacks,
)
from dace.transformation.passes.gpu_specialization.grid_stride_kernels import GridStrideKernels
Expand All @@ -120,6 +121,8 @@ def __init__(self, memory_engine_copies: bool | None = None):
# Order constraints:
# * NestedGPUDeviceMapLowering first -- everything downstream assumes one-level kernels.
# * scheduler after ExpandLibraryNodes -- it would miss opaque libnodes.
# * SequentialMegakernelBodies after ExpandLibraryNodes and before AddThreadBlockMaps -- an expansion or the
# default schedule can put a thread-block map in a megakernel, which would then go untiled.
# * PromoteWarpTiles before AddThreadBlockMaps -- canonicalize promotes a pending ``is_warp_tile``
# before choosing a block size; a graph that reaches codegen with one still pending gets its
# thread-block level from the tile, not a second one on top of it.
Expand Down Expand Up @@ -159,6 +162,7 @@ def __init__(self, memory_engine_copies: bool | None = None):
InsertExplicitCopies(),
*copy_selection,
ExpandLibraryNodes(),
SequentialMegakernelBodies(),
strategy,
GPUStreamWiring(strategy),
SynchronizeStreamUnawareGPUCallbacks(),
Expand Down
31 changes: 30 additions & 1 deletion dace/transformation/passes/offloading/offload_to_accelerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,21 @@ def in_sequential_specialization_arm(block) -> bool:
return False


def is_own_fallback_arm(conditional: ControlFlowBlock | None, block: ControlFlowBlock | None) -> bool:
"""Whether ``block`` sits at the top level of a branch of ``conditional`` that holds a pinned fallback loop.

Narrower than :func:`in_sequential_specialization_arm`, which is also true for every block nested deeper in
the arm (the fallback loop's own body and the conditionals inside it): only ``conditional`` itself owns this
arm, so only its entry location must not be taken from the arm.
"""
if not isinstance(conditional, ConditionalBlock) or block is None:
return False
return any(
block.parent_graph is branch and any(isinstance(b, LoopRegion) and b.pinned_sequential for b in branch.nodes())
for _, branch in conditional.branches
)


def runs_on_every_path(block) -> bool:
"""Whether ``block`` runs on every path through its SDFG: no conditional around it, only loops that provably
iterate, and no conditional edge, break, continue or return on the way."""
Expand Down Expand Up @@ -1994,6 +2009,12 @@ def __populate_open_node_sets(self, IR: OffloadingIRNode):
children = [child for child in IR.next if child.block not in self._fallthrough_entries]
if len(children) != 1:
return
# Unless that one real arm is the conditional's own sequential fallback: the arm copies in and out inside
# itself (:func:`in_sequential_specialization_arm`), so its host use is no entry location. Taken as one, the
# copies sat around the conditional and ran on every execution, the arm taken or not (qe_vexx_k's
# ``if okvan and tqr`` scatter: ``rhoc`` to the host and back once per band pair, about 0.9 GB per call).
if is_own_fallback_arm(IR.block, children[0].block):
return

# Behavior 2:
# if there is a single direct child, then analyse the section & find first known location of each used array
Expand Down Expand Up @@ -2364,8 +2385,16 @@ def insert_copies(node, next, node_block, next_block):
# never written already matches on the device, and when it is a nested SDFG's input
# connector the copy is not merely wasted -- it writes a container the body may only read
# (npbench scattering_self_energies' ``neigh_idx``).
# An argument whose entry value nothing reads needs no copy IN, the host-to-device fill of a host
# array's device twin. For an argument whose home is the device, the same direction is the copy BACK
# of what its host twin computed, which is the result: a host library node writing a host connector
# (ScatterConflictCheck's flag and scratch) left the device argument unwritten without it.
cpu_set, gpu_set = self.exit_sets(node)
gpu_copies = {name for name in cpu_set & next.gpu_set if name not in self._no_copy_in_needed}
gpu_copies = {
name
for name in cpu_set & next.gpu_set
if name not in self._no_copy_in_needed or is_array_stored_on_GPU(sdfg, name)
}
if gpu_copies:
place_copy(node_block, next_block, gpu_copies, to_gpu=True)

Expand Down
Loading