dace.sdfg package

Submodules

dace.sdfg.graph module

File containing DaCe-serializable versions of graphs, nodes, and edges.

class dace.sdfg.graph.DiGraph

Bases: Graph[NodeT, EdgeT], Generic[NodeT, EdgeT]

add_edge(source, destination, data)

Adds an edge to the graph containing the specified data. Returns the added edge.

add_node(node)

Adds node to the graph.

edges()

Returns an iterable to internal graph edges.

edges_between(source, destination)

Returns all edges that connect source and destination directly

find_cycles()
has_cycles()
Return type:

bool

in_degree(node)

Returns the number of incoming edges to the specified node.

in_edges(node)

Returns an iterable to Edge objects.

is_directed()
is_multigraph()
nodes()

Returns an iterable to internal graph nodes.

number_of_edges()

Returns the total number of edges in the graph.

number_of_nodes()

Returns the total number of nodes in the graph.

out_degree(node)

Returns the number of outgoing edges from the specified node.

out_edges(node)

Returns an iterable to Edge objects.

remove_edge(edge)

Removes the specified Edge object.

remove_node(node)

Removes the specified node.

class dace.sdfg.graph.Edge(src, dst, data)

Bases: Generic[T]

property data: T
property dst
static from_json(json_obj, context=None)
reverse()
property src
to_json(parent_graph)
exception dace.sdfg.graph.EdgeNotFoundError

Bases: Exception

class dace.sdfg.graph.Graph

Bases: Generic[NodeT, EdgeT]

add_edge(source, destination, data)

Adds an edge to the graph containing the specified data. Returns the added edge.

add_node(node)

Adds node to the graph.

add_nodes_from(node_list)

Adds nodes from an iterable to the graph

all_edges(*nodes)

Returns an iterable to incoming and outgoing Edge objects.

Return type:

Iterable[Edge[TypeVar(EdgeT)]]

all_nodes_between(begin, end)

Finds all nodes between begin and end. Returns None if there is any path starting at begin that does not reach end.

Return type:

Sequence[TypeVar(NodeT)]

all_simple_paths(source_node, dest_node, as_edges=False)

Finds all simple paths (with no repeating nodes) from source_node to dest_node.

Parameters:
  • source_node (TypeVar(NodeT)) – Node to start from.

  • dest_node (TypeVar(NodeT)) – Node to end at.

  • as_edges (bool) – If True, returns list of edges instead of nodes.

Return type:

Iterable[Sequence[Union[Edge[TypeVar(EdgeT)], TypeVar(NodeT)]]]

bfs_nodes(source=None)

Returns an iterable over nodes traversed in breadth-first search order starting from source.

Return type:

Iterable[TypeVar(NodeT)]

degree(node)

Returns the number of edges connected to/from the specified node.

Return type:

int

dfs_edges(source, condition=None)

Traverse a graph (DFS) with an optional condition to filter out nodes

Return type:

Iterable[Edge[TypeVar(EdgeT)]]

edge_bfs(node, reverse=False)

Returns a generator over edges in the graph originating from the passed node in BFS order.

Note:

All reachable edges are yielded including back edges

Return type:

Iterable[Edge[TypeVar(EdgeT)]]

edge_id(edge)

Returns a numeric ID that corresponds to the edge index in the internal graph representation (unique).

Return type:

int

edges()

Returns an iterable to internal graph edges.

Return type:

Iterable[Edge[TypeVar(EdgeT)]]

edges_between(source, destination)

Returns all edges that connect source and destination directly

Return type:

Iterable[Edge[TypeVar(EdgeT)]]

in_degree(node)

Returns the number of incoming edges to the specified node.

Return type:

int

in_edges(node)

Returns an iterable to Edge objects.

Return type:

Iterable[Edge[TypeVar(EdgeT)]]

is_directed()
Return type:

bool

is_multigraph()
Return type:

bool

neighbors(node)
Return type:

Iterable[TypeVar(NodeT)]

node_id(node)

Returns a numeric ID that corresponds to the node index in the internal graph representation (unique).

Return type:

int

nodes()

Returns an iterable to internal graph nodes.

Return type:

Iterable[TypeVar(NodeT)]

number_of_edges()

Returns the total number of edges in the graph.

Return type:

int

number_of_nodes()

Returns the total number of nodes in the graph.

Return type:

int

property nx

Returns a networkx version of this graph if available.

out_degree(node)

Returns the number of outgoing edges from the specified node.

Return type:

int

out_edges(node)

Returns an iterable to Edge objects.

Return type:

Iterable[Edge[TypeVar(EdgeT)]]

predecessors(node)

Returns an iterable of nodes that have edges leading to the passed node

Return type:

Iterable[TypeVar(NodeT)]

remove_edge(edge)

Removes the specified Edge object.

remove_node(node)

Removes the specified node.

remove_nodes_from(node_list)

Removes the nodes specified in an iterable.

sink_nodes()

Returns nodes with no outgoing edges.

Return type:

List[TypeVar(NodeT)]

source_nodes()

Returns nodes with no incoming edges.

Return type:

List[TypeVar(NodeT)]

successors(node)

Returns an iterable of nodes that have edges leading to the passed node

Return type:

Iterable[TypeVar(NodeT)]

to_json()
class dace.sdfg.graph.MultiConnectorEdge(src, src_conn, dst, dst_conn, data, key)

Bases: MultiEdge, Generic[T]

property data: T
property dst_conn
static from_json(json_obj, context=None)
property src_conn
to_json(parent_graph)
class dace.sdfg.graph.MultiDiConnectorGraph

Bases: MultiDiGraph[NodeT, EdgeT], Generic[NodeT, EdgeT]

add_edge(source, src_connector, destination, dst_connector, data)

Adds an edge to the graph containing the specified data. Returns the added edge.

is_multigraph()
Return type:

bool

remove_edge(edge)

Removes the specified Edge object.

class dace.sdfg.graph.MultiDiGraph

Bases: DiGraph[NodeT, EdgeT], Generic[NodeT, EdgeT]

add_edge(source, destination, data)

Adds an edge to the graph containing the specified data. Returns the added edge.

is_multigraph()
Return type:

bool

remove_edge(edge)

Removes the specified Edge object.

class dace.sdfg.graph.MultiEdge(src, dst, data, key)

Bases: Edge, Generic[T]

property key
exception dace.sdfg.graph.NodeNotFoundError

Bases: Exception

class dace.sdfg.graph.OrderedDiGraph

Bases: Graph[NodeT, EdgeT], Generic[NodeT, EdgeT]

Directed graph where nodes and edges are returned in the order they were added.

add_edge(src, dst, data=None)

Adds an edge to the graph containing the specified data. Returns the added edge.

add_node(node)

Adds node to the graph.

edges()

Returns an iterable to internal graph edges.

Return type:

List[Edge[TypeVar(EdgeT)]]

edges_between(source, destination)

Returns all edges that connect source and destination directly

Return type:

List[Edge[TypeVar(EdgeT)]]

find_cycles()
has_cycles()
Return type:

bool

in_degree(node)

Returns the number of incoming edges to the specified node.

in_edges(node)

Returns an iterable to Edge objects.

Return type:

List[Edge[TypeVar(EdgeT)]]

is_directed()
is_multigraph()
node(id)
Return type:

TypeVar(NodeT)

node_id(node)

Returns a numeric ID that corresponds to the node index in the internal graph representation (unique).

Return type:

int

nodes()

Returns an iterable to internal graph nodes.

Return type:

List[TypeVar(NodeT)]

number_of_edges()

Returns the total number of edges in the graph.

number_of_nodes()

Returns the total number of nodes in the graph.

property nx

Returns a networkx version of this graph if available.

out_degree(node)

Returns the number of outgoing edges from the specified node.

out_edges(node)

Returns an iterable to Edge objects.

Return type:

List[Edge[TypeVar(EdgeT)]]

remove_edge(edge)

Removes the specified Edge object.

remove_node(node)

Removes the specified node.

reverse()

Reverses source and destination of all edges in the graph

class dace.sdfg.graph.OrderedMultiDiConnectorGraph

Bases: OrderedMultiDiGraph[NodeT, EdgeT], Generic[NodeT, EdgeT]

Directed multigraph with node connectors (SDFG states), where nodes and edges are returned in the order they were added.

add_edge(src, src_conn, dst, dst_conn, data)

Adds an edge to the graph containing the specified data. Returns the added edge.

Return type:

MultiConnectorEdge[TypeVar(EdgeT)]

add_nedge(src, dst, data)

Adds an edge without (value=None) connectors.

Return type:

MultiConnectorEdge[TypeVar(EdgeT)]

edges_between(source, destination)

Returns all edges that connect source and destination directly

Return type:

List[MultiConnectorEdge[TypeVar(EdgeT)]]

in_edges(node)

Returns an iterable to Edge objects.

Return type:

List[MultiConnectorEdge[TypeVar(EdgeT)]]

is_multigraph()
Return type:

bool

out_edges(node)

Returns an iterable to Edge objects.

Return type:

List[MultiConnectorEdge[TypeVar(EdgeT)]]

remove_edge(edge)

Removes the specified Edge object.

reverse()

Reverses source and destination of all edges in the graph

Return type:

None

class dace.sdfg.graph.OrderedMultiDiGraph

Bases: OrderedDiGraph[NodeT, EdgeT], Generic[NodeT, EdgeT]

Directed multigraph where nodes and edges are returned in the order they were added.

add_edge(src, dst, data)

Adds an edge to the graph containing the specified data. Returns the added edge.

Return type:

MultiEdge[TypeVar(EdgeT)]

edges_between(source, destination)

Returns all edges that connect source and destination directly

Return type:

List[MultiEdge[TypeVar(EdgeT)]]

in_edges(node)

Returns an iterable to Edge objects.

Return type:

List[MultiEdge[TypeVar(EdgeT)]]

is_multigraph()
Return type:

bool

out_edges(node)

Returns an iterable to Edge objects.

Return type:

List[MultiEdge[TypeVar(EdgeT)]]

remove_edge(edge)

Removes the specified Edge object.

reverse()

Reverses source and destination of all edges in the graph

Return type:

None

class dace.sdfg.graph.SubgraphView(graph, subgraph_nodes)

Bases: Graph[NodeT, EdgeT], Generic[NodeT, EdgeT]

add_edge(source, destination, data)

Adds an edge to the graph containing the specified data. Returns the added edge.

add_node(node)

Adds node to the graph.

add_nodes_from(node_list)

Adds nodes from an iterable to the graph

edges()

Returns an iterable to internal graph edges.

Return type:

List[Edge[TypeVar(EdgeT)]]

edges_between(source, destination)

Returns all edges that connect source and destination directly

property graph
in_degree(node)

Returns the number of incoming edges to the specified node.

in_edges(node)

Returns an iterable to Edge objects.

Return type:

List[Edge[TypeVar(EdgeT)]]

is_directed()
is_multigraph()
node_id(node)

Returns a numeric ID that corresponds to the node index in the internal graph representation (unique).

Return type:

int

nodes()

Returns an iterable to internal graph nodes.

Return type:

Sequence[TypeVar(NodeT)]

number_of_edges()

Returns the total number of edges in the graph.

number_of_nodes()

Returns the total number of nodes in the graph.

out_degree(node)

Returns the number of outgoing edges from the specified node.

out_edges(node)

Returns an iterable to Edge objects.

Return type:

List[Edge[TypeVar(EdgeT)]]

remove_edge(edge)

Removes the specified Edge object.

remove_node(node)

Removes the specified node.

remove_nodes_from(node_list)

Removes the nodes specified in an iterable.

dace.sdfg.graph.generate_element_id(element)
Return type:

str

dace.sdfg.nodes module

Contains classes implementing the different types of nodes of the stateful dataflow multigraph representation.

class dace.sdfg.nodes.AccessNode(*args, **kwargs)

Bases: Node

A node that accesses data in the SDFG. Denoted by a circular shape.

data

Data (array, stream, scalar) to access

debuginfo

Object property of type DebugInfo

desc(sdfg)
static from_json(json_obj, context=None)
has_reads(state)
has_writes(state)
instrument

Instrument data contents at this access

instrument_condition

Condition under which to trigger the instrumentation

property label
properties()
property root_data
root_desc(sdfg)
setzero

Initialize to zero

validate(sdfg, state)
class dace.sdfg.nodes.CodeNode(*args, **kwargs)

Bases: Node

A node that contains runnable code with acyclic external data dependencies. May either be a tasklet or a nested SDFG, and denoted by an octagonal shape.

environments

Environments required by CMake to build and run this code node.

property free_symbols: Set[str]

Returns a set of symbols used in this node’s properties.

label

Name of the CodeNode

location

Full storage location identifier (e.g., rank, GPU ID)

properties()
class dace.sdfg.nodes.Consume(*args, **kwargs)

Bases: object

Consume is a scope, like Map, that is a part of the parametric graph extension of the SDFG. It creates a producer-consumer relationship between the input stream and the scope subgraph. The subgraph is scheduled to a given number of processing elements for processing, and they will try to pop elements from the input stream until a given quiescence condition is reached.

as_map()

Compatibility function that allows to view the consume as a map, mainly in memlet propagation.

chunksize

Maximal size of elements to consume at a time

condition

Quiescence condition

debuginfo

Object property of type DebugInfo

get_param_num()

Returns the number of consume dimension parameters/symbols.

instrument

Measure execution statistics with given method

is_collapsed

Show this node/scope/state as collapsed

label

Name of the consume node

num_pes

Number of processing elements

pe_index

Processing element identifier

properties()
schedule

Consume schedule

validate(sdfg, state, node)
class dace.sdfg.nodes.ConsumeEntry(*args, **kwargs)

Bases: EntryNode

Node that opens a Consume scope.

See:

Consume

chunksize

Maximal size of elements to consume at a time

condition

Quiescence condition

property consume
debuginfo

Object property of type DebugInfo

property free_symbols: Set[str]

Returns a set of symbols used in this node’s properties.

static from_json(json_obj, context=None)
instrument

Measure execution statistics with given method

is_collapsed

Show this node/scope/state as collapsed

label

Name of the consume node

property map
new_symbols(sdfg, state, symbols)

Returns a mapping between symbols defined by this node (e.g., for scope entries) to their type.

Return type:

Dict[str, typeclass]

num_pes

Number of processing elements

pe_index

Processing element identifier

properties()
schedule

Consume schedule

class dace.sdfg.nodes.ConsumeExit(consume)

Bases: ExitNode

Node that closes a Consume scope.

See:

Consume

property consume
static from_json(json_obj, context=None)
property label
property map
property schedule
class dace.sdfg.nodes.EntryNode(*args, **kwargs)

Bases: Node

A type of node that opens a scope (e.g., Map or Consume).

validate(sdfg, state)
class dace.sdfg.nodes.ExitNode(*args, **kwargs)

Bases: Node

A type of node that closes a scope (e.g., Map or Consume).

validate(sdfg, state)
class dace.sdfg.nodes.LibraryNode(*args, **kwargs)

Bases: CodeNode

debuginfo

Object property of type DebugInfo

expand(sdfg, state, *args, **kwargs)

Create and perform the expansion transformation for this library node.

Return type:

str

Returns:

the name of the expanded implementation

property free_symbols: Set[str]

Returns a set of symbols used in this node’s properties.

classmethod from_json(json_obj, context=None)
property has_side_effects: bool

Returns True if this library node has other side effects (e.g., calling stateful libraries, communicating) when expanded. This method is meant to be extended by subclasses.

implementation

Which implementation this library node will expand into.Must match a key in the list of possible implementations.

name

Name of node

properties()
classmethod register_implementation(name, transformation_type)

Register an implementation to belong to this library node type.

schedule

If set, determines the default device mapping of the node upon expansion, if expanded to a nested SDFG.

to_json(parent)
class dace.sdfg.nodes.Map(*args, **kwargs)

Bases: object

A Map is a two-node representation of parametric graphs, containing an integer set by which the contents (nodes dominated by an entry node and post-dominated by an exit node) are replicated.

Maps contain a schedule property, which specifies how the scope should be scheduled (execution order). Code generators can use the schedule property to generate appropriate code, e.g., GPU kernels.

collapse

How many dimensions to collapse into the parallel range

debuginfo

Object property of type DebugInfo

get_param_num()

Returns the number of map dimension parameters/symbols.

gpu_block_size

GPU kernel block size

gpu_launch_bounds

GPU kernel launch bounds. A value of -1 disables the statement, 0 (default) enables the statement if block size is not symbolic, and any other value (including tuples) sets it explicitly.

instrument

Measure execution statistics with given method

is_collapsed

Show this node/scope/state as collapsed

label

Label of the map

omp_chunk_size

OpenMP schedule chunk size

omp_num_threads

Number of OpenMP threads executing the Map

omp_schedule

OpenMP schedule {static, dynamic, guided}

params

Mapped parameters

properties()
range

Ranges of map parameters

schedule

Map schedule

unroll

Map unrolling

unroll_factor

How much iterations should be unrolled. To prevent unrolling, set this value to 1.

validate(sdfg, state, node)
class dace.sdfg.nodes.MapEntry(*args, **kwargs)

Bases: EntryNode

Node that opens a Map scope.

See:

Map

collapse

How many dimensions to collapse into the parallel range

debuginfo

Object property of type DebugInfo

property free_symbols: Set[str]

Returns a set of symbols used in this node’s properties.

classmethod from_json(json_obj, context=None)
gpu_block_size

GPU kernel block size

gpu_launch_bounds

GPU kernel launch bounds. A value of -1 disables the statement, 0 (default) enables the statement if block size is not symbolic, and any other value (including tuples) sets it explicitly.

instrument

Measure execution statistics with given method

is_collapsed

Show this node/scope/state as collapsed

label

Label of the map

property map
static map_type()
new_symbols(sdfg, state, symbols)

Returns a mapping between symbols defined by this node (e.g., for scope entries) to their type.

Return type:

Dict[str, typeclass]

omp_chunk_size

OpenMP schedule chunk size

omp_num_threads

Number of OpenMP threads executing the Map

omp_schedule

OpenMP schedule {static, dynamic, guided}

params

Mapped parameters

properties()
range

Ranges of map parameters

schedule

Map schedule

unroll

Map unrolling

unroll_factor

How much iterations should be unrolled. To prevent unrolling, set this value to 1.

class dace.sdfg.nodes.MapExit(map)

Bases: ExitNode

Node that closes a Map scope.

See:

Map

classmethod from_json(json_obj, context=None)
property label
property map
static map_type()
property schedule
class dace.sdfg.nodes.NestedSDFG(*args, **kwargs)

Bases: CodeNode

An SDFG state node that contains an SDFG of its own, runnable using the data dependencies specified using its connectors.

It is encouraged to use nested SDFGs instead of coarse-grained tasklets since they are analyzable with respect to transformations.

Note:

A nested SDFG cannot create recursion (one of its parent SDFGs).

debuginfo

Object property of type DebugInfo

property free_symbols: Set[str]

Returns a set of symbols used in this node’s properties.

static from_json(json_obj, context=None)
infer_connector_types(sdfg, state)

Infers and fills remaining connectors (i.e., set to None) with their types.

instrument

Measure execution statistics with given method

is_collapsed

Show this node/scope/state as collapsed

no_inline

If True, this nested SDFG will not be inlined during simplification

properties()
schedule

SDFG schedule

sdfg: SDFG

The SDFG

symbol_mapping

Mapping between internal symbols and their values, expressed as symbolic expressions

unique_name

Unique name of the SDFG

used_symbols(all_symbols)
Return type:

Set[str]

validate(sdfg, state, references=None, **context)
class dace.sdfg.nodes.Node(*args, **kwargs)

Bases: object

Base node class.

add_in_connector(connector_name, dtype=None, force=False)

Adds a new input connector to the node. The operation will fail if a connector (either input or output) with the same name already exists in the node.

Parameters:
  • connector_name (str) – The name of the new connector.

  • dtype (Optional[typeclass]) – The type of the connector, or None for auto-detect.

  • force (bool) – Add connector even if output connector already exists.

Returns:

True if the operation is successful, otherwise False.

add_out_connector(connector_name, dtype=None, force=False)

Adds a new output connector to the node. The operation will fail if a connector (either input or output) with the same name already exists in the node.

Parameters:
  • connector_name (str) – The name of the new connector.

  • dtype (Optional[typeclass]) – The type of the connector, or None for auto-detect.

  • force (bool) – Add connector even if input connector already exists.

Returns:

True if the operation is successful, otherwise False.

property free_symbols: Set[str]

Returns a set of symbols used in this node’s properties.

guid

Object property of type str

in_connectors

A set of input connectors for this node.

infer_connector_types(sdfg, state)

Infers and fills remaining connectors (i.e., set to None) with their types.

last_connector()

Returns the last used connector ID (as a string). Used for filling connectors when adding edges to scopes.

Return type:

str

new_symbols(sdfg, state, symbols)

Returns a mapping between symbols defined by this node (e.g., for scope entries) to their type.

Return type:

Dict[str, typeclass]

next_connector(try_name=None)

Returns the next unused connector ID (as a string). Used for filling connectors when adding edges to scopes.

Parameters:

try_name (Optional[str]) – First try the connector with this name. If already exists, use the next integer connector.

Return type:

str

out_connectors

A set of output connectors for this node.

properties()
remove_in_connector(connector_name)

Removes an input connector from the node.

Parameters:

connector_name (str) – The name of the connector to remove.

Returns:

True if the operation was successful.

remove_out_connector(connector_name)

Removes an output connector from the node.

Parameters:

connector_name (str) – The name of the connector to remove.

Returns:

True if the operation was successful.

to_json(parent)
validate(sdfg, state)
class dace.sdfg.nodes.PipelineEntry(*args, **kwargs)

Bases: MapEntry

additional_iterators

Additional iterators, managed by the user inside the scope.

drain_overlap

Whether to increment regular map indices during pipeline drain.

drain_size

Number of drain iterations.

init_overlap

Whether to increment regular map indices during initialization.

init_size

Number of initialization iterations.

static map_type()
new_symbols(sdfg, state, symbols)

Returns a mapping between symbols defined by this node (e.g., for scope entries) to their type.

Return type:

Dict[str, typeclass]

property pipeline
properties()
class dace.sdfg.nodes.PipelineExit(map)

Bases: MapExit

static map_type()
property pipeline
class dace.sdfg.nodes.PipelineScope(*args, **kwargs)

Bases: Map

This a convenience-subclass of Map that allows easier implementation of loop nests (using regular Map indices) that need a constant-sized initialization and drain phase (e.g., N*M + c iterations), which would otherwise need a flattened one-dimensional map.

additional_iterators

Additional iterators, managed by the user inside the scope.

drain_condition()

Variable that can be checked to see if pipeline is currently in draining phase.

drain_overlap

Whether to increment regular map indices during pipeline drain.

drain_size

Number of drain iterations.

init_condition()

Variable that can be checked to see if pipeline is currently in initialization phase.

init_overlap

Whether to increment regular map indices during initialization.

init_size

Number of initialization iterations.

iterator_str()
loop_bound_str()
properties()
class dace.sdfg.nodes.RTLTasklet(*args, **kwargs)

Bases: Tasklet

A specialized tasklet, which is a functional computation procedure that can only access external data specified using connectors.

This tasklet is specialized for tasklets implemented in System Verilog in that it adds support for adding metadata about the IP cores in use.

add_ip_core(module_name, name, vendor, version, params)
ip_cores

A set of IP cores used by the tasklet.

properties()
class dace.sdfg.nodes.Tasklet(*args, **kwargs)

Bases: CodeNode

A node that contains a tasklet: a functional computation procedure that can only access external data specified using connectors.

Tasklets may be implemented in Python, C++, or any supported language by the code generator.

code

Tasklet code

code_exit

Extra code that is called on DaCe runtime cleanup

code_global

Global scope code needed for tasklet execution

code_init

Extra code that is called on DaCe runtime initialization

debuginfo

Object property of type DebugInfo

property free_symbols: Set[str]

Returns a set of symbols used in this node’s properties.

static from_json(json_obj, context=None)
has_side_effects(sdfg)

Returns True if this tasklet may have other side effects (e.g., calling stateful libraries, communicating).

Return type:

bool

ignored_symbols

A set of symbols to ignore when computing the symbols used by this tasklet. Used to skip certain symbols in non-Python tasklets, where only string analysis is possible; and to skip globals in Python tasklets that should not be given as parameters to the SDFG.

infer_connector_types(sdfg, state)

Infers and fills remaining connectors (i.e., set to None) with their types.

instrument

Measure execution statistics with given method

property language
property name
properties()
side_effects

If True, this tasklet calls a function that may have additional side effects on the system state (e.g., callback). Defaults to None, which lets the framework make assumptions based on the tasklet contents

state_fields

Fields that are added to the global state

validate(sdfg, state)
class dace.sdfg.nodes.UnregisteredLibraryNode(json_obj={}, label=None)

Bases: LibraryNode

expand(sdfg, state, *args, **kwargs)

Create and perform the expansion transformation for this library node.

Returns:

the name of the expanded implementation

classmethod from_json(json_obj, context=None)
original_json = {}
to_json(parent)
dace.sdfg.nodes.full_class_path(cls_or_obj)

dace.sdfg.analysis module

Control-Flow Graph Analysis

Various analyses related to control flow in SDFGs.

dace.sdfg.analysis.cfg.acyclic_dominance_frontier(cfg, idom=None)

Finds the dominance frontier for a CFG while ignoring any back edges.

This is a modified version of the dominance frontiers algorithm as implemented by networkx.

Parameters:
  • cfg (ControlFlowRegion) – The CFG for which to compute the acyclic dominance frontier.

  • idom – Optional precomputed immediate dominators.

Return type:

Dict[ControlFlowBlock, Set[ControlFlowBlock]]

Returns:

A dictionary keyed by control flow blocks, containing the dominance frontier for each control flow block.

dace.sdfg.analysis.cfg.all_dominators(cfg, idom=None)

Returns a mapping between each control flow block and all its dominators.

Return type:

Dict[ControlFlowBlock, Set[ControlFlowBlock]]

dace.sdfg.analysis.cfg.back_edges(cfg, idom=None, alldoms=None)

Returns a list of back-edges in a control flow graph.

Return type:

List[Edge[InterstateEdge]]

dace.sdfg.analysis.cfg.block_parent_tree(cfg, loopexits=None, idom=None, with_loops=True)

Computes an upward-pointing tree of each control flow block, pointing to the “parent block” it belongs to (in terms of structured control flow). More formally, each block is either mapped to its immediate dominator with out degree >= 2, one block upwards if the block occurs after a loop and with_loops is True, or the start block if no such block exist.

Parameters:
  • sdfg – The SDFG to analyze.

  • idom (Optional[Dict[ControlFlowBlock, ControlFlowBlock]]) – An optional, pre-computed immediate dominator dictionary.

  • with_loops (bool) – Respect loops in the parent computation, mapping blocks to a parent one block upwards of a loop if the block occurs after a loop. Defaults to true.

Return type:

Dict[ControlFlowBlock, ControlFlowBlock]

Returns:

A dictionary that maps each block to a parent block, or None if the root (start) block.

dace.sdfg.analysis.cfg.blockorder_topological_sort(cfg, recursive=True, ignore_nonstate_blocks=False)

Returns a generator that produces control flow blocks in the order that they will be executed, disregarding multiple loop iterations and employing topological sort for branches.

Parameters:
  • cfg (ControlFlowRegion) – The CFG to iterate over.

  • recursive (bool) – Whether or not to recurse down hierarchies of control flow regions (not across Nested SDFGs).

  • ignore_nonstate_blocks (bool) – If true, only produce basic blocks / SDFGStates. Defaults to False.

Return type:

Iterator[ControlFlowBlock]

Returns:

Generator that yields control flow blocks in execution-order.

dace.sdfg.analysis.cfg.branch_merges(cfg, idom=None, alldoms=None)
Return type:

Dict[ControlFlowBlock, ControlFlowBlock]

Graph Cutouts

Functionality that allows users to “cut out” parts of an SDFG in a smart way (i.e., memory preserving) for localized testing or optimization.

class dace.sdfg.analysis.cutout.SDFGCutout(name, constants_prop=None)

Bases: SDFG

find_inputs(*args, **kwargs)
Return type:

Dict[str, Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, _NestedSequence[Union[bool, int, float, complex, str, bytes]], Number]]

classmethod from_json(json_obj, context=None)
classmethod from_transformation(sdfg, transformation, make_side_effects_global=True, use_alibi_nodes=True, reduce_input_config=True, symbols_map=None)

Create a cutout from a transformation’s set of affected graph elements.

Parameters:
  • sdfg (SDFG) – The SDFG to create the cutout from.

  • transformation (Union[PatternTransformation, SubgraphTransformation]) – The transformation to create the cutout from.

  • make_side_effects_global – Whether to make side effect data containers global, i.e. non-transient.

  • use_alibi_nodes (bool) – Whether to use alibi nodes for the cutout across scope borders.

  • reduce_input_config – Whether to reduce the input configuration where possible in singlestate cutouts.

  • symbols_map (Optional[Dict[str, Any]]) – A mapping of symbols to values to use for the cutout. Optional, only used when reducing the input configuration.

Return type:

Union[SDFGCutout, SDFG]

Returns:

The cutout.

input_config: Set[str] = {}
classmethod multistate_cutout(*states, make_side_effects_global=True, override_start_block=None)

Cut out a multi-state subgraph from an SDFG to run separately for localized testing or optimization.

The subgraph defined by the list of states will be extended to include any additional states necessary to make the resulting cutout valid and executable, i.e, to ensure that there is a distinct start state. This is achieved by gradually adding more states from the cutout’s predecessor frontier until a distinct, single entry state is obtained.

See:

_stateset_predecessor_frontier

Parameters:
  • states (SDFGState) – The subgraph states to cut out.

  • make_side_effects_global (bool) – If True, all transient data containers which are read inside the cutout but may be written to _before_ the cutout, or any data containers which are written to inside the cutout but may be read _after_ the cutout, are made global.

  • override_start_block (Optional[ControlFlowBlock]) – If set, explicitly force a given control flow block to be the start block. If left None (default), the start block is automatically determined based on domination relationships in the original graph.

Return type:

Union[SDFGCutout, SDFG]

Returns:

The created SDFGCutout or the original SDFG where no smaller cutout could be obtained.

output_config: Set[str] = {}
classmethod singlestate_cutout(state, *nodes, make_copy=True, make_side_effects_global=True, use_alibi_nodes=True, reduce_input_config=False, symbols_map=None)

Cut out a subgraph of a state from an SDFG to run separately for localized testing or optimization. The subgraph defined by the list of nodes will be extended to include access nodes of data containers necessary to run the graph separately. In addition, all transient data containers that may contain data when the cutout is executed are made global, as well as any transient data containers which are written to inside the cutout but may be read after the cutout.

Parameters:
  • state (SDFGState) – The SDFG state in which the subgraph resides.

  • nodes (Node) – The nodes in the subgraph to cut out.

  • make_copy (bool) – If True, deep-copies every SDFG element in the copy. Otherwise, original references are kept.

  • make_side_effects_global (bool) – If True, all transient data containers which are read inside the cutout but may be written to _before_ the cutout, or any data containers which are written to inside the cutout but may be read _after_ the cutout, are made global.

  • use_alibi_nodes (bool) – If True, do not extend the cutout with access nodes that span outside of a scope, but introduce alibi nodes instead that represent only the accesses subset.

  • reduce_input_config (bool) – Whether to reduce the input configuration where possible in singlestate cutouts.

  • symbols_map (Optional[Dict[str, Any]]) – A mapping of symbols to values to use for the cutout. Optional, only used when reducing the input configuration.

Return type:

SDFGCutout

Returns:

The created SDFGCutout.

to_json(hash=False)

Serializes this object to JSON format.

Returns:

A string representing the JSON-serialized SDFG.

translate_transformation_into(transformation)

Vector-Type Inference

dace.sdfg.infer_types module

dace.sdfg.infer_types.infer_aliasing(node, sdfg, state)

Infers aliasing information on nested SDFG arrays based on external edges and connectors. Operates in-place on nested SDFG node.

Parameters:
  • node (NestedSDFG) – The nested SDFG node.

  • sdfg (SDFG) – Parent SDFG of the nested SDFG node.

  • state (SDFGState) – Parent state of the nested SDFG node.

Return type:

None

dace.sdfg.infer_types.infer_connector_types(sdfg)

Infers connector types throughout an SDFG and its nested SDFGs in-place.

Parameters:

sdfg (SDFG) – The SDFG to infer.

dace.sdfg.infer_types.infer_out_connector_type(sdfg, state, node, cname)

Tries to infer a single output connector type on a Tasklet or Nested SDFG node.

Parameters:
  • sdfg (SDFG) – The SDFG to infer in.

  • state (SDFGState) – The state in which the code node resides.

  • node (CodeNode) – The tasklet to infer.

  • cname (str) – An input/output connector name to infer.

Return type:

Optional[typeclass]

Returns:

The connector type, or None if a type could not be inferred.

dace.sdfg.infer_types.set_default_schedule_and_storage_types(scope, parent_schedules=None, use_parent_schedule=False, state=None, child_nodes=None)

Sets default storage and schedule types throughout SDFG in-place. Replaces ScheduleType.Default and StorageType.Default with the corresponding types according to the parent scope’s schedule.

The defaults for storage types are determined by the dtypes.SCOPEDEFAULT_STORAGE dictionary (for example, a GPU device schedule, by default, will allocate containers on the shared memory). Following storage type inference for a scope, nested scopes (e.g., map entry, nested SDFG) are evaluated using the dtypes.STORAGEDEFAULT_SCHEDULE dictionary (for example, a default map with only GPU arrays connected to it will execute on the GPU). This decision is superseded if the schedule is specified in dtypes.SCOPEDEFAULT_SCHEDULE (e.g., a map nested in a CPU multi-core map will by default run within a single thread). If no default schedule is found while traversing the parent scopes, the chosen schedule will be determined based on the SDFG’s device, as specified in dtypes.DEFAULT_TOPLEVEL_STORAGE and dtypes.DEFAULT_TOPLEVEL_SCHEDULE. May raise InvalidSDFGNodeError if a default scope is ambiguous based on surrounding storage types. :type scope: Union[SDFG, SDFGState, EntryNode] :param scope: The SDFG, state, or scope to infer. :type parent_schedules: Optional[List[ScheduleType]] :param parent_schedules: A list of ScheduleType elements representing

an ordered list of schedules, from the global schedule on the top-level SDFG (usually None), up to this point.

Parameters:
  • use_parent_schedule (bool) – If True, uses the parent scope’s schedule type directly, instead of the default schedule type. Used when expanding nested SDFGs to preserve their top-level schedule.

  • state (Optional[SDFGState]) – (Use when working with a single scope) The parent state.

  • child_nodes (Optional[Dict[Node, List[Node]]]) – (Use when working with a single scope) A mapping of each scope entry node to its children.

dace.sdfg.propagation module

Functionality relating to Memlet propagation (deducing external memlets from internal memory accesses and scope ranges).

class dace.sdfg.propagation.AffineSMemlet

Bases: SeparableMemletPattern

Separable memlet pattern that matches affine expressions, i.e., of the form a * {index} + b.

can_be_applied(dim_exprs, variable_context, node_range, orig_edges, dim_index, total_dims)
propagate(array, dim_exprs, node_range)
class dace.sdfg.propagation.ConstantRangeMemlet

Bases: MemletPattern

Memlet pattern that matches arbitrary expressions with constant range.

can_be_applied(expressions, variable_context, node_range, orig_edges)
propagate(array, expressions, node_range)
class dace.sdfg.propagation.ConstantSMemlet

Bases: SeparableMemletPattern

Separable memlet pattern that matches constant (i.e., unrelated to current scope) expressions.

can_be_applied(dim_exprs, variable_context, node_range, orig_edges, dim_index, total_dims)
propagate(array, dim_exprs, node_range)
class dace.sdfg.propagation.GenericSMemlet

Bases: SeparableMemletPattern

Separable memlet pattern that detects any expression, and propagates interval bounds. Used as a last resort.

can_be_applied(dim_exprs, variable_context, node_range, orig_edges, dim_index, total_dims)
propagate(array, dim_exprs, node_range)
class dace.sdfg.propagation.MemletPattern

Bases: object

A pattern match on a memlet subset that can be used for propagation.

can_be_applied(expressions, variable_context, node_range, orig_edges)
extensions()
propagate(array, expressions, node_range)
register(**kwargs)
unregister()
class dace.sdfg.propagation.ModuloSMemlet

Bases: SeparableMemletPattern

Separable memlet pattern that matches modulo expressions, i.e., of the form f(x) % N.

Acts as a meta-pattern: Finds the underlying pattern for f(x).

can_be_applied(dim_exprs, variable_context, node_range, orig_edges, dim_index, total_dims)
propagate(array, dim_exprs, node_range)
class dace.sdfg.propagation.SeparableMemlet

Bases: MemletPattern

Meta-memlet pattern that applies all separable memlet patterns.

can_be_applied(expressions, variable_context, node_range, orig_edges)
propagate(array, expressions, node_range)
class dace.sdfg.propagation.SeparableMemletPattern

Bases: object

Memlet pattern that can be applied to each of the dimensions separately.

can_be_applied(dim_exprs, variable_context, node_range, orig_edges, dim_index, total_dims)
extensions()
propagate(array, dim_exprs, node_range)
register(**kwargs)
unregister()
dace.sdfg.propagation.align_memlet(state, e, dst)
Return type:

Memlet

dace.sdfg.propagation.propagate_memlet(dfg_state, memlet, scope_node, union_inner_edges, arr=None, connector=None)

Tries to propagate a memlet through a scope (computes the image of the memlet function applied on an integer set of, e.g., a map range) and returns a new memlet object.

Parameters:
  • dfg_state – An SDFGState object representing the graph.

  • memlet (Memlet) – The memlet adjacent to the scope node from the inside.

  • scope_node (EntryNode) – A scope entry or exit node.

  • union_inner_edges (bool) – True if the propagation should take other neighboring internal memlets within the same scope into account.

dace.sdfg.propagation.propagate_memlets_nested_sdfg(parent_sdfg, parent_state, nsdfg_node)

Propagate memlets out of a nested sdfg.

Parameters:
  • parent_sdfg – The parent SDFG this nested SDFG is in.

  • parent_state – The state containing this nested SDFG.

  • nsdfg_node – The NSDFG node containing this nested SDFG.

Note:

This operates in-place on the parent SDFG.

dace.sdfg.propagation.propagate_memlets_scope(sdfg, state, scopes, propagate_entry=True, propagate_exit=True)

Propagate memlets from the given scopes outwards.

Parameters:
  • sdfg – The SDFG in which the scopes reside.

  • state – The SDFG state in which the scopes reside.

  • scopes – The ScopeTree object or a list thereof to start from.

  • propagate_entry – If False, skips propagating out of the scope entry node.

  • propagate_exit – If False, skips propagating out of the scope exit node.

Note:

This operation is performed in-place on the given SDFG.

dace.sdfg.propagation.propagate_memlets_sdfg(sdfg)

Propagates memlets throughout an entire given SDFG.

Note:

This is an in-place operation on the SDFG.

dace.sdfg.propagation.propagate_memlets_state(sdfg, state)

Propagates memlets throughout one SDFG state.

Parameters:
  • sdfg – The SDFG in which the state is situated.

  • state – The state to propagate in.

Note:

This is an in-place operation on the SDFG state.

dace.sdfg.propagation.propagate_states(sdfg, concretize_dynamic_unbounded=False)

Annotate the states of an SDFG with the number of executions.

Algorithm:

  1. Clean up the state machine by splitting condition and assignment edges into separate edes with a dummy state in between.

  2. Detect and annotate any for-loop constructs with their corresponding loop variable ranges.

  3. Start traversing the state machine from the start state (start state gets executed once by default). At every state, check the following:

    1. The state was already visited -> in this case it can either be the guard of a loop we’re returning to - in which case the number of executions is additively combined - or it is a state that can be reached through multiple paths (e.g. if/else branches), in which case the number of executions is equal to the maximum number of executions for each incoming path (in case this fully merges a previously branched out tree again, the number of executions isn’t dynamic anymore). In both cases we override the calculated number of executions if we’re propagating dynamic unbounded. This DFS traversal is complete and we continue with the next unvisited state.

    2. We’re propagating dynamic unbounded -> this overrides every calculated number of executions, so this gets unconditionally propagated to all child states.

    3. None of the above, the next regular traversal step is executed:

      1. If there is no further outgoing edge, this DFS traversal is done and we continue with the next unvisited state.

      2. If there is one outgoing edge, we continue propagating the same number of executions to the child state. If the transition to the child state is conditional, the current state might be an implicit exit state, in which case we mark the next state as dynamic to signal that it’s an upper bound.

      3. If there is more than one outgoing edge we:

        1. Check if it’s an annotated loop guard with a range. If so, we calculate the number of executions for the loop and propagate this down the loop.

        2. Check if it’s a loop that hasn’t been unannotated, which means it’s unbounded. In this case we propagate dynamic unbounded down the loop.

        3. Otherwise this must be a conditional branch, so this state’s number of executions is given to all child states as an upper bound.

  4. The traversal ends when all reachable states have been visited at least once.

Parameters:
  • sdfg – The SDFG to annotate.

  • concretize_dynamic_unbounded – If True, we annotate dyncamic unbounded states with symbols of the form “num_execs_{cfg_id}_{loop_start_state_id}”. Hence, for each unbounded loop its states will have the same number of symbolic executions.

Note:

This operates on the SDFG in-place.

Return type:

None

dace.sdfg.propagation.propagate_subset(memlets, arr, params, rng, defined_variables=None, use_dst=False)

Tries to propagate a list of memlets through a range (computes the image of the memlet function applied on an integer set of, e.g., a map range) and returns a new memlet object.

Parameters:
  • memlets (List[Memlet]) – The memlets to propagate.

  • arr (Data) – Array descriptor for memlet (used for obtaining extents).

  • params (List[str]) – A list of variable names.

  • rng (Subset) – A subset with dimensionality len(params) that contains the range to propagate with.

  • defined_variables (Optional[Set[Union[Basic, SymExpr]]]) – A set of symbols defined that will remain the same throughout propagation. If None, assumes that all symbols outside of params have been defined.

  • use_dst (bool) – Whether to propagate the memlets’ dst subset or use the src instead, depending on propagation direction.

Return type:

Memlet

Returns:

Memlet with propagated subset and volume.

dace.sdfg.propagation.reset_state_annotations(sdfg)

Resets the state (loop-related) annotations of an SDFG.

Note:

This operation is shallow (does not go into nested SDFGs).

dace.sdfg.replace module

Contains functionality to perform find-and-replace of symbols in SDFGs.

dace.sdfg.replace.replace(subgraph, name, new_name)

Finds and replaces all occurrences of a symbol or array in the given subgraph.

Parameters:
  • subgraph (StateSubgraphView) – The given graph or subgraph to replace in.

  • name (str) – Name to find.

  • new_name (str) – Name to replace.

dace.sdfg.replace.replace_datadesc_names(sdfg, repl)

Reduced form of replace which only replaces data descriptor names.

dace.sdfg.replace.replace_dict(subgraph, repl, symrepl=None)

Finds and replaces all occurrences of a set of symbols/arrays in the given subgraph.

Parameters:
  • subgraph (StateSubgraphView) – The given graph or subgraph to replace in.

  • repl (Dict[str, str]) – Dictionary of replacements (key -> value).

  • symrepl (Optional[Dict[Union[Basic, SymExpr], Union[Basic, SymExpr]]]) – Optional cached dictionary of repl as symbolic expressions.

dace.sdfg.replace.replace_properties(node, symrepl, name, new_name)
dace.sdfg.replace.replace_properties_dict(node, repl, symrepl=None)

dace.sdfg.scope module

class dace.sdfg.scope.ScopeSubgraphView(graph, subgraph_nodes, entry_node)

Bases: StateSubgraphView

An extension to SubgraphView that enables the creation of scope dictionaries in subgraphs and free symbols.

property parent
top_level_transients()

Iterate over top-level transients of this subgraph.

class dace.sdfg.scope.ScopeTree(entrynode, exitnode)

Bases: object

A class defining a scope, its parent and children scopes, and scope entry/exit nodes.

dace.sdfg.scope.common_parent_scope(sdict, scope_a, scope_b)

Finds a common parent scope for both input scopes, or None if the scopes are in different connected components.

Parameters:
  • sdict (Dict[Node, List[Node]]) – Scope parent dictionary.

  • scope_a (Node) – First scope.

  • scope_b (Node) – Second scope.

Return type:

Node

Returns:

Scope node or None for top-level scope.

dace.sdfg.scope.devicelevel_block_size(sdfg, state, node)

Returns the current thread-block size if the given node is enclosed in a GPU kernel, or None otherwise.

Parameters:
  • sdfg (SDFG) – The SDFG in which the node resides.

  • state (SDFGState) – The SDFG state in which the node resides.

  • node (Node) – The node in question

Return type:

Tuple[SymExpr]

Returns:

A tuple of sizes or None if the node is not in device-level code.

dace.sdfg.scope.is_devicelevel_fpga(sdfg, state, node)

Tests whether a node in an SDFG is contained within FPGA device-level code.

Parameters:
  • sdfg (SDFG) – The SDFG in which the node resides.

  • state (SDFGState) – The SDFG state in which the node resides.

  • node (Node) – The node in question

Return type:

bool

Returns:

True if node is in device-level code, False otherwise.

dace.sdfg.scope.is_devicelevel_gpu(sdfg, state, node, with_gpu_default=False)

Tests whether a node in an SDFG is contained within GPU device-level code.

Parameters:
  • sdfg (SDFG) – The SDFG in which the node resides.

  • state (SDFGState) – The SDFG state in which the node resides.

  • node (Node) – The node in question

Return type:

bool

Returns:

True if node is in device-level code, False otherwise.

dace.sdfg.scope.is_devicelevel_gpu_kernel(sdfg, state, node)

Tests whether a node in an SDFG is contained within an actual GPU kernel. The main difference from is_devicelevel_gpu() is that it returns False for NestedSDFGs that have a GPU device-level schedule, but are not within an actual GPU kernel. :type sdfg: SDFG :param sdfg: The SDFG in which the node resides. :type state: SDFGState :param state: The SDFG state in which the node resides. :type node: Node :param node: The node in question :rtype: bool :return: True if node is in GPU kernel code, False otherwise.

dace.sdfg.scope.is_in_scope(sdfg, state, node, schedules)

Tests whether a node in an SDFG is contained within a certain set of scope schedules.

Parameters:
  • sdfg (SDFG) – The SDFG in which the node resides.

  • state (SDFGState) – The SDFG state in which the node resides.

  • node (Node) – The node in question

Return type:

bool

Returns:

True if node is in device-level code, False otherwise.

dace.sdfg.scope.scope_contains_scope(sdict, node, other_node)

Returns true iff scope of node contains the scope of other_node.

Return type:

bool

dace.sdfg.sdfg module

class dace.sdfg.sdfg.InterstateEdge(*args, **kwargs)

Bases: object

An SDFG state machine edge. These edges can contain a condition (which may include data accesses for data-dependent decisions) and zero or more assignments of values to inter-state variables (e.g., loop iterates).

assignments

Assignments to perform upon transition (e.g., ‘x=x+1; y = 0’)

condition

Transition condition

condition_sympy()
property free_symbols: Set[str]

Returns a set of symbols used in this edge’s properties.

static from_json(json_obj, context=None)
get_read_memlets(arrays)

Returns a list of memlets (with data descriptors and subsets) used in this edge. This includes both reads in the condition and in every assignment.

Parameters:

arrays (Dict[str, Data]) – A dictionary mapping names to their corresponding data descriptors (a-la sdfg.arrays)

Return type:

List[Memlet]

Returns:

A list of Memlet objects for each read.

guid

Object property of type str

is_unconditional()

Returns True if the state transition is unconditional.

property label
new_symbols(sdfg, symbols)

Returns a mapping between symbols defined by this edge (i.e., assignments) to their type.

Return type:

Dict[str, typeclass]

properties()
read_symbols()

Returns a set of symbols read in this edge (including symbols in the condition and assignment values).

Return type:

Set[str]

replace(name, new_name, replace_keys=True)

Replaces all occurrences of name with new_name.

Parameters:
  • name (str) – The source name.

  • new_name (str) – The replacement name.

  • replace_keys – If False, skips replacing assignment keys.

Return type:

None

replace_dict(repl, replace_keys=True)

Replaces all given keys with their corresponding values.

Parameters:
  • repl (Dict[str, str]) – Replacement dictionary.

  • replace_keys – If False, skips replacing assignment keys.

Return type:

None

to_json(parent=None)
used_symbols(all_symbols)

Returns a set of symbols used in this edge’s properties.

Return type:

Set[str]

class dace.sdfg.sdfg.LogicalGroup(*args, **kwargs)

Bases: object

Logical element groupings on a per-SDFG level.

color

Color for the group, given as a hexadecimal string

static from_json(json_obj, context=None)
name

Logical group name

nodes

Nodes in this group given by [State, Node] id tuples

properties()
states

States in this group given by their ids

to_json()
class dace.sdfg.sdfg.NestedDict(mapping=None)

Bases: dict

keys() a set-like object providing a view on D's keys
class dace.sdfg.sdfg.SDFG(*args, **kwargs)

Bases: ControlFlowRegion

The main intermediate representation of code in DaCe.

A Stateful DataFlow multiGraph (SDFG) is a directed graph of directed acyclic multigraphs (i.e., where two nodes can be connected by more than one edge). The top-level directed graph represents a state machine, where edges can contain state transition conditions and assignments (see the InterstateEdge class documentation). The nested acyclic multigraphs represent dataflow, where nodes may represent data regions in memory, tasklets, or parametric graph scopes (see dace.sdfg.nodes for a full list of available node types); edges in the multigraph represent data movement using memlets, as described in the Memlet class documentation.

add_array(name, shape, dtype, storage=<StorageType.Default: 1>, location=None, transient=False, strides=None, offset=None, lifetime=<AllocationLifetime.Scope: 1>, debuginfo=None, allow_conflicts=False, total_size=None, find_new_name=False, alignment=0, may_alias=False)

Adds an array to the SDFG data descriptor store.

Return type:

Tuple[str, Array]

add_constant(name, value, dtype=None)

Adds/updates a new compile-time constant to this SDFG.

A constant may either be a scalar or a numpy ndarray thereof. It is not an error if there is already a symbol or an array with the same name inside the SDFG. However, the data descriptors must refer to the same type.

Parameters:
  • name (str) – The name of the constant.

  • value (Any) – The constant value.

  • dtype (Optional[Data]) – Optional data type of the symbol, or None to deduce automatically.

add_datadesc(name, datadesc, find_new_name=False)

Adds an existing data descriptor to the SDFG array store.

Parameters:
  • name (str) – Name to use.

  • datadesc (Data) – Data descriptor to add.

  • find_new_name – If True and data descriptor with this name exists, finds a new name to add.

Return type:

str

Returns:

Name of the new data descriptor

add_datadesc_reference(name, datadesc, find_new_name=False)

Adds a reference of a given data descriptor to the SDFG array store.

Parameters:
  • name (str) – Name to use.

  • datadesc (Data) – Data descriptor to view.

  • find_new_name – If True and data descriptor with this name exists, finds a new name to add.

Return type:

str

Returns:

Name of the new data descriptor

add_datadesc_view(name, datadesc, find_new_name=False)

Adds a view of a given data descriptor to the SDFG array store.

Parameters:
  • name (str) – Name to use.

  • datadesc (Data) – Data descriptor to view.

  • find_new_name – If True and data descriptor with this name exists, finds a new name to add.

Return type:

str

Returns:

Name of the new data descriptor

add_loop(before_state, loop_state, after_state, loop_var, initialize_expr, condition_expr, increment_expr, loop_end_state=None)

Helper function that adds a looping state machine around a given state (or sequence of states).

Parameters:
  • before_state – The state after which the loop should begin, or None if the loop is the first state (creates an empty state).

  • loop_state – The state that begins the loop. See also loop_end_state if the loop is multi-state.

  • after_state – The state that should be invoked after the loop ends, or None if the program should terminate (creates an empty state).

  • loop_var (str) – A name of an inter-state variable to use for the loop. If None, initialize_expr and increment_expr must be None.

  • initialize_expr (str) – A string expression that is assigned to loop_var before the loop begins. If None, does not define an expression.

  • condition_expr (str) – A string condition that occurs every loop iteration. If None, loops forever (undefined behavior).

  • increment_expr (str) – A string expression that is assigned to loop_var after every loop iteration. If None, does not define an expression.

  • loop_end_state – If the loop wraps multiple states, the state where the loop iteration ends. If None, sets the end state to loop_state as well.

Returns:

A 3-tuple of (before_state, generated loop guard state, after_state).

add_pgrid(shape=None, parent_grid=None, color=None, exact_grid=None, root=0)

Adds a process-grid to the process-grid descriptor store. For more details on process-grids, please read the documentation of the ProcessGrid class.

Parameters:
Returns:

Name of the new process-grid descriptor.

add_rdistrarray(array_a, array_b)

Adds a sub-array redistribution to the sub-array redistribution descriptor store. For more details on redistributions, please read the documentation of the RedistrArray class.

Parameters:
  • array_a (str) – Input sub-array descriptor.

  • array_b (str) – Output sub-array descriptor.

Returns:

Name of the new redistribution descriptor.

add_reference(name, shape, dtype, storage=<StorageType.Default: 1>, strides=None, offset=None, debuginfo=None, allow_conflicts=False, total_size=None, find_new_name=False, alignment=0, may_alias=False)

Adds a reference to the SDFG data descriptor store.

Return type:

Tuple[str, Reference]

add_scalar(name, dtype, storage=<StorageType.Default: 1>, transient=False, lifetime=<AllocationLifetime.Scope: 1>, debuginfo=None, find_new_name=False)

Adds a scalar to the SDFG data descriptor store.

Return type:

Tuple[str, Scalar]

add_stream(name, dtype, buffer_size=1, shape=(1, ), storage=<StorageType.Default: 1>, transient=False, offset=None, lifetime=<AllocationLifetime.Scope: 1>, debuginfo=None, find_new_name=False)

Adds a stream to the SDFG data descriptor store.

Return type:

Tuple[str, Stream]

add_subarray(dtype, shape, subshape, pgrid=None, correspondence=None)

Adds a sub-array to the sub-array descriptor store. For more details on sub-arrays, please read the documentation of the SubArray class.

Parameters:
Returns:

Name of the new sub-array descriptor.

add_symbol(name, stype, find_new_name=False)

Adds a symbol to the SDFG.

Parameters:
  • name – Symbol name.

  • stype – Symbol type.

  • find_new_name (bool) – Find a new name.

add_temp_transient(shape, dtype, storage=<StorageType.Default: 1>, location=None, strides=None, offset=None, lifetime=<AllocationLifetime.Scope: 1>, debuginfo=None, allow_conflicts=False, total_size=None, alignment=0, may_alias=False)

Convenience function to add a transient array with a temporary name to the data descriptor store.

add_temp_transient_like(desc, dtype=None, debuginfo=None)

Convenience function to add a transient array with a temporary name to the data descriptor store.

add_transient(name, shape, dtype, storage=<StorageType.Default: 1>, location=None, strides=None, offset=None, lifetime=<AllocationLifetime.Scope: 1>, debuginfo=None, allow_conflicts=False, total_size=None, find_new_name=False, alignment=0, may_alias=False)

Convenience function to add a transient array to the data descriptor store.

Return type:

Tuple[str, Array]

add_view(name, shape, dtype, storage=<StorageType.Default: 1>, strides=None, offset=None, debuginfo=None, allow_conflicts=False, total_size=None, find_new_name=False, alignment=0, may_alias=False)

Adds a view to the SDFG data descriptor store.

Return type:

Tuple[str, ArrayView]

append_exit_code(cpp_code, location='frame')

Appends C++ code that will be generated in the __dace_exit_* functions on one of the generated code files.

Parameters:
  • cpp_code (str) – The code to append.

  • location (str) – The file/backend in which to generate the code. Options are None (all files), “frame”, “openmp”, “cuda”, “xilinx”, “intel_fpga”, or any code generator name.

append_global_code(cpp_code, location='frame')

Appends C++ code that will be generated in a global scope on one of the generated code files.

Parameters:
  • cpp_code (str) – The code to set.

  • location (str) – The file/backend in which to generate the code. Options are None (all files), “frame”, “openmp”, “cuda”, “xilinx”, “intel_fpga”, or any code generator name.

append_init_code(cpp_code, location='frame')

Appends C++ code that will be generated in the __dace_init_* functions on one of the generated code files.

Parameters:
  • cpp_code (str) – The code to append.

  • location (str) – The file/backend in which to generate the code. Options are None (all files), “frame”, “openmp”, “cuda”, “xilinx”, “intel_fpga”, or any code generator name.

append_transformation(transformation)

Appends a transformation to the treansformation history of this SDFG. If this is the first transformation being applied, it also saves the initial state of the SDFG to return to and play back the history.

Parameters:

transformation – The transformation to append.

apply_fpga_transformations(states=None, validate=True, validate_all=False, permissive=False)

Applies a series of transformations on the SDFG for it to generate FPGA code.

Note:

This is an in-place operation on the SDFG.

apply_gpu_transformations(states=None, validate=True, validate_all=False, permissive=False, sequential_innermaps=True, register_transients=True, simplify=True)

Applies a series of transformations on the SDFG for it to generate GPU code.

Parameters:
  • sequential_innermaps – Make all internal maps Sequential.

  • register_transients – Make all transients inside GPU maps registers.

Note:

It is recommended to apply redundant array removal transformation after this transformation. Alternatively, you can simplify() after this transformation.

Note:

This is an in-place operation on the SDFG.

apply_strict_transformations(validate=True, validate_all=False)

This method is DEPRECATED in favor of simplify. Applies safe transformations (that will surely increase the performance) on the SDFG. For example, this fuses redundant states (safely) and removes redundant arrays.

B{Note:} This is an in-place operation on the SDFG.

apply_transformations(xforms, options=None, validate=True, validate_all=False, permissive=False, states=None, print_report=None)

This function applies a transformation or a sequence thereof consecutively. Operates in-place.

Parameters:
  • xforms (Union[Type, List[Type]]) – A PatternTransformation class or a sequence.

  • options (Union[Dict[str, Any], List[Dict[str, Any]], None]) – An optional dictionary (or sequence of dictionaries) to modify transformation parameters.

  • validate (bool) – If True, validates after all transformations.

  • validate_all (bool) – If True, validates after every transformation.

  • permissive (bool) – If True, operates in permissive mode.

  • states (Optional[List[Any]]) – If not None, specifies a subset of states to apply transformations on.

  • print_report (Optional[bool]) – Whether to show debug prints or not (None if the DaCe config option ‘debugprint’ should apply)

Return type:

int

Returns:

Number of transformations applied.

Examples:

# Applies MapTiling, then MapFusion, followed by
# GPUTransformSDFG, specifying parameters only for the
# first transformation.
sdfg.apply_transformations(
  [MapTiling, MapFusion, GPUTransformSDFG],
  options=[{'tile_size': 16}, {}, {}])
apply_transformations_once_everywhere(xforms, options=None, validate=True, validate_all=False, permissive=False, states=None, print_report=None, order_by_transformation=True, progress=None)

This function applies a transformation or a set of (unique) transformations until throughout the entire SDFG once. Operates in-place.

Parameters:
  • xforms (Union[Type, List[Type]]) – A PatternTransformation class or a set thereof.

  • options (Union[Dict[str, Any], List[Dict[str, Any]], None]) – An optional dictionary (or sequence of dictionaries) to modify transformation parameters.

  • validate (bool) – If True, validates after all transformations.

  • validate_all (bool) – If True, validates after every transformation.

  • permissive (bool) – If True, operates in permissive mode.

  • states (Optional[List[Any]]) – If not None, specifies a subset of states to apply transformations on.

  • print_report (Optional[bool]) – Whether to show debug prints or not (None if the DaCe config option ‘debugprint’ should apply).

  • order_by_transformation (bool) – Try to apply transformations ordered by class rather than SDFG.

  • progress (Optional[bool]) – If True, prints every intermediate transformation applied. If False, never prints anything. If None (default), prints only after 5 seconds of transformations.

Return type:

int

Returns:

Number of transformations applied.

Examples:

# Tiles all maps once
sdfg.apply_transformations_once_everywhere(MapTiling, options=dict(tile_size=16))
apply_transformations_repeated(xforms, options=None, validate=True, validate_all=False, permissive=False, states=None, print_report=None, order_by_transformation=True, progress=None)

This function repeatedly applies a transformation or a set of (unique) transformations until none can be found. Operates in-place.

Parameters:
  • xforms (Union[Type, List[Type]]) – A PatternTransformation class or a set thereof.

  • options (Union[Dict[str, Any], List[Dict[str, Any]], None]) – An optional dictionary (or sequence of dictionaries) to modify transformation parameters.

  • validate (bool) – If True, validates after all transformations.

  • validate_all (bool) – If True, validates after every transformation.

  • permissive (bool) – If True, operates in permissive mode.

  • states (Optional[List[Any]]) – If not None, specifies a subset of states to apply transformations on.

  • print_report (Optional[bool]) – Whether to show debug prints or not (None if the DaCe config option ‘debugprint’ should apply).

  • order_by_transformation (bool) – Try to apply transformations ordered by class rather than SDFG.

  • progress (Optional[bool]) – If True, prints every intermediate transformation applied. If False, never prints anything. If None (default), prints only after 5 seconds of transformations.

Return type:

int

Returns:

Number of transformations applied.

Examples:

# Applies InlineSDFG until no more subgraphs can be inlined
sdfg.apply_transformations_repeated(InlineSDFG)
arg_names

Ordered argument names (used for calling conventions).

arglist(scalars_only=False, free_symbols=None)

Returns an ordered dictionary of arguments (names and types) required to invoke this SDFG.

The arguments follow the following order: <sorted data arguments>, <sorted scalar arguments>. Data arguments are all the non-transient data containers in the SDFG; and scalar arguments are all the non-transient scalar data containers and free symbols (see SDFG.free_symbols). This structure will create a sorted list of pointers followed by a sorted list of PoDs and structs.

Return type:

Dict[str, Data]

Returns:

An ordered dictionary of (name, data descriptor type) of all the arguments, sorted as defined here.

argument_typecheck(args, kwargs, types_only=False)

Checks if arguments and keyword arguments match the SDFG types. Raises RuntimeError otherwise.

Raises:
  • RuntimeError – Argument count mismatch.

  • TypeError – Argument type mismatch.

  • NotImplementedError – Unsupported argument type.

property arrays

Returns a dictionary of data descriptors (Data objects) used in this SDFG, with an extra None entry for empty memlets.

arrays_recursive(include_nested_data=False)

Iterate over all arrays in this SDFG, including arrays within nested SDFGs. Yields 3-tuples of (sdfg, array name, array).

Parameters:

include_nested_data (bool) – If True, also yields nested data.

Returns:

A generator of (sdfg, array name, array) tuples.

available_data_reports()

Returns a list of available instrumented data reports for this SDFG.

Return type:

List[str]

property build_folder: str

Returns a relative path to the build cache folder for this SDFG.

call_with_instrumented_data(dreport, *args, **kwargs)

Invokes an SDFG with an instrumented data report, generating and compiling code if necessary. Arguments given as args and kwargs will be overriden by the data containers defined in the report.

Parameters:
  • dreport (InstrumentedDataReport) – The instrumented data report to use upon calling.

  • args – Arguments to call SDFG with.

  • kwargs – Keyword arguments to call SDFG with.

Returns:

The return value(s) of this SDFG.

callback_mapping

Mapping between callback name and its original callback (for when the same callback is used with a different signature)

clear_data_reports()

Clears the instrumented data report folders of this SDFG.

clear_instrumentation_reports()

Clears the instrumentation report folder of this SDFG.

compile(output_file=None, validate=True)

Compiles a runnable binary from this SDFG.

Parameters:
  • output_file – If not None, copies the output library file to the specified path.

  • validate – If True, validates the SDFG prior to generating code.

Return type:

CompiledSDFG

Returns:

A callable CompiledSDFG object.

property constants

A dictionary of compile-time constants defined in this SDFG.

constants_prop

Compile-time constants

data(dataname)

Looks up a data descriptor from its name, which can be an array, stream, or scalar symbol.

debuginfo

Object property of type DebugInfo

exit_code

Code generated in the __dace_exit function.

expand_library_nodes(recursive=True)

Recursively expand all unexpanded library nodes in the SDFG, resulting in a “pure” SDFG that the code generator can handle.

Parameters:

recursive – If True, expands all library nodes recursively, including library nodes that expand to library nodes.

fill_scope_connectors()

Fills missing scope connectors (i.e., “IN_#”/”OUT_#” on entry/exit nodes) according to data on the memlets.

find_new_constant(name)

Tries to find a new name for a constant.

find_new_symbol(name)

Tries to find a new symbol name by adding an underscore and a number.

find_state(state_id_or_label)

Finds a state according to its ID (if integer is provided) or label (if string is provided).

Parameters:

state_id_or_label – State ID (if int) or label (if str).

Returns:

An SDFGState object.

static from_file(filename)

Constructs an SDFG from a file.

Parameters:

filename (str) – File name to load SDFG from.

Return type:

SDFG

Returns:

An SDFG.

classmethod from_json(json_obj, context=None)
generate_code()

Generates code from this SDFG and returns it.

Returns:

A list of CodeObject objects containing the generated code of different files and languages.

get_all_toplevel_symbols()

Returns a set of all symbol names that are used by the SDFG’s state machine. This includes all symbols in the descriptor repository and interstate edges, whether free or defined. Used to identify duplicates when, e.g., inlining or dealiasing a set of nested SDFGs.

Return type:

Set[str]

get_instrumentation_reports()

Returns a list of instrumentation reports from previous runs of this SDFG.

Return type:

List[InstrumentationReport]

Returns:

A List of timestamped InstrumentationReport objects.

get_instrumented_data(timestamp=None)

Returns an instrumented data report from the latest run of this SDFG, with a given timestamp, or None if no reports exist.

Parameters:

timestamp (Optional[int]) – An optional timestamp to use for the report.

Return type:

Optional[InstrumentedDataReport]

Returns:

An InstrumentedDataReport object, or None if one does not exist.

get_latest_report()

Returns an instrumentation report from the latest run of this SDFG, or None if the file does not exist.

Return type:

Optional[InstrumentationReport]

Returns:

A timestamped InstrumentationReport object, or None if does not exist.

get_latest_report_path()

Returns an instrumentation report file path from the latest run of this SDFG, or None if the file does not exist.

Return type:

Optional[str]

Returns:

A path to the latest instrumentation report, or None if one does not exist.

global_code

Code generated in a global scope on the output files.

hash_sdfg(jsondict=None)

Returns a hash of the current SDFG, without considering IDs and attribute names.

Parameters:

jsondict (Optional[Dict[str, Any]]) – If not None, uses given JSON dictionary as input.

Return type:

str

Returns:

The hash (in SHA-256 format).

init_code

Code generated in the __dace_init function.

init_signature(for_call=False, free_symbols=None)

Returns a C/C++ signature of this SDFG, used when generating the initalization code. It only contains symbols.

Parameters:

for_call – If True, returns arguments that can be used when calling the SDFG.

Return type:

str

instrument

Measure execution statistics with given method

is_instrumented()

Returns True if the SDFG has performance instrumentation enabled on it or any of its elements.

Return type:

bool

is_loaded()

Returns True if the SDFG binary is already loaded in the current process.

Return type:

bool

is_name_free(name)

Test if name is free, i.e. is not used by anything else.

Return type:

bool

is_name_used(name)

Checks if name is already used inside the SDFG.

Return type:

bool

is_valid()

Returns True if the SDFG is verified correctly (using validate).

Return type:

bool

property label

The name of this SDFG.

logical_groups

Logical groupings of nodes and edges

make_array_memlet(array)

Convenience method to generate a Memlet that transfers a full array.

Parameters:

array (str) – the name of the array

Returns:

a Memlet that fully transfers array

name

Name of the SDFG

openmp_sections

Whether to generate OpenMP sections in code

orig_sdfg

Object property of type OptionalSDFGReferenceProperty

property parent: SDFGState

Returns the parent SDFG state of this SDFG, if exists.

property parent_nsdfg_node: NestedSDFG

Returns the parent NestedSDFG node of this SDFG, if exists.

property parent_sdfg: SDFG

Returns the parent SDFG of this SDFG, if exists.

predecessor_state_transitions(state)

Yields paths (lists of edges) that the SDFG can pass through before computing the given state.

predecessor_states(state)

Returns a list of unique states that the SDFG can pass through before computing the given state.

prepend_exit_code(cpp_code, location='frame')

Prepends C++ code that will be generated in the __dace_exit_* functions on one of the generated code files.

Parameters:
  • cpp_code (str) – The code to prepend.

  • location (str) – The file/backend in which to generate the code. Options are None (all files), “frame”, “openmp”, “cuda”, “xilinx”, “intel_fpga”, or any code generator name.

property process_grids

Returns a dictionary of process-grid descriptors (ProcessGrid objects) used in this SDFG.

property propagate
properties()
python_signature(with_types=True, for_call=False, with_arrays=True, arglist=None)

Returns a Data-Centric Python signature of this SDFG, used when generating code.

Parameters:
  • with_types – If True, includes argument types (can be used for a function prototype). If False, only include argument names (can be used for function calls).

  • for_call – If True, returns arguments that can be used when calling the SDFG.

  • with_arrays – If True, includes arrays, otherwise, only symbols and scalars are included.

  • arglist – An optional cached argument list.

Return type:

str

python_signature_arglist(with_types=True, for_call=False, with_arrays=True, arglist=None)

Returns a list of arguments necessary to call this SDFG, formatted as a list of Data-Centric Python definitions.

Parameters:
  • with_types – If True, includes argument types in the result.

  • for_call – If True, returns arguments that can be used when calling the SDFG.

  • with_arrays – If True, includes arrays, otherwise, only symbols and scalars are included.

  • arglist – An optional cached argument list.

Return type:

List[str]

Returns:

A list of strings. For example: [‘A: dace.float32[M]’, ‘b: dace.int32’].

property rdistrarrays

Returns a dictionary of sub-array redistribution descriptors (RedistrArray objects) used in this SDFG.

read_and_write_sets()

Determines what data containers are read and written in this SDFG. Does not include reads to subsets of containers that have previously been written within the same state.

Return type:

Tuple[Set[AnyStr], Set[AnyStr]]

Returns:

A two-tuple of sets of things denoting ({data read}, {data written}).

recheck_using_experimental_blocks()
Return type:

bool

remove_data(name, validate=True)

Removes a data descriptor from the SDFG.

Parameters:
  • name – The name of the data descriptor to remove.

  • validate – If True, verifies that there are no access nodes that are using this data descriptor prior to removing it.

remove_node(node)

Removes the specified node.

remove_symbol(name)

Removes a symbol from the SDFG.

Parameters:

name – Symbol name.

replace(name, new_name)

Finds and replaces all occurrences of a symbol or array name in SDFG.

Parameters:
  • name (str) – Name to find.

  • new_name (str) – Name to replace.

Raises:

FileExistsError – If name and new_name already exist as data descriptors or symbols.

replace_dict(repldict, symrepl=None, replace_in_graph=True, replace_keys=True)

Replaces all occurrences of keys in the given dictionary with the mapped values.

Parameters:
  • repldict (Dict[str, str]) – The replacement dictionary.

  • replace_keys (bool) – If False, skips replacing assignment keys.

  • symrepl (Optional[Dict[Union[Basic, SymExpr], Union[Basic, SymExpr]]]) – A symbolic expression replacement dictionary (for performance reasons).

  • replace_in_graph (bool) – Whether to replace in SDFG nodes / edges.

  • replace_keys – If True, replaces in SDFG property names (e.g., array, symbol, and constant names).

Return type:

None

reset_sdfg_list()

Reset the CFG list when changes have been made to the SDFG’s CFG tree. This collects all control flow graphs recursively and propagates the collection to all CFGs as the new CFG list. :note: reset_sdfg_list is deprecated, please use reset_cfg_list instead.

Returns:

The newly updated CFG list.

save(filename, use_pickle=False, hash=None, exception=None, compress=False)

Save this SDFG to a file.

Parameters:
  • filename (str) – File name to save to.

  • use_pickle – Use Python pickle as the SDFG format (default: JSON).

  • hash – By default, saves the hash if SDFG is JSON-serialized. Otherwise, if True, saves the hash along with the SDFG.

  • exception – If not None, stores error information along with SDFG.

  • compress – If True, uses gzip to compress the file upon saving.

Return type:

Optional[str]

Returns:

The hash of the SDFG, or None if failed/not requested.

property sdfg_id

Returns the unique index of the current CFG within the current tree of CFGs (Top-level CFG/SDFG is 0, nested CFGs/SDFGs are greater). :note: sdfg_id is deprecated, please use cfg_id instead.

property sdfg_list: List[ControlFlowRegion]
set_exit_code(cpp_code, location='frame')

Sets C++ code that will be generated in the __dace_exit_* functions on one of the generated code files.

Parameters:
  • cpp_code (str) – The code to set.

  • location (str) – The file/backend in which to generate the code. Options are None (all files), “frame”, “openmp”, “cuda”, “xilinx”, “intel_fpga”, or any code generator name.

set_global_code(cpp_code, location='frame')

Sets C++ code that will be generated in a global scope on one of the generated code files.

Parameters:
  • cpp_code (str) – The code to set.

  • location (str) – The file/backend in which to generate the code. Options are None (all files), “frame”, “openmp”, “cuda”, “xilinx”, “intel_fpga”, or any code generator name.

set_init_code(cpp_code, location='frame')

Sets C++ code that will be generated in the __dace_init_* functions on one of the generated code files.

Parameters:
  • cpp_code (str) – The code to set.

  • location (str) – The file/backend in which to generate the code. Options are None (all files), “frame”, “openmp”, “cuda”, “xilinx”, “intel_fpga”, or any code generator name.

set_sourcecode(code, lang=None)

Set the source code of this SDFG (for IDE purposes).

Parameters:
  • code (str) – A string of source code.

  • lang – A string representing the language of the source code, for syntax highlighting and completion.

shared_transients(check_toplevel=True, include_nested_data=False)

Returns a list of transient data that appears in more than one state.

Parameters:
  • check_toplevel (bool) – If True, consider the descriptors’ toplevel attribute.

  • include_nested_data (bool) – If True, also include nested data.

Return type:

List[str]

Returns:

A list of transient data names.

signature(with_types=True, for_call=False, with_arrays=True, arglist=None)

Returns a C/C++ signature of this SDFG, used when generating code.

Parameters:
  • with_types – If True, includes argument types (can be used for a function prototype). If False, only include argument names (can be used for function calls).

  • for_call – If True, returns arguments that can be used when calling the SDFG.

  • with_arrays – If True, includes arrays, otherwise, only symbols and scalars are included.

  • arglist – An optional cached argument list.

Return type:

str

signature_arglist(with_types=True, for_call=False, with_arrays=True, arglist=None)

Returns a list of arguments necessary to call this SDFG, formatted as a list of C definitions.

Parameters:
  • with_types – If True, includes argument types in the result.

  • for_call – If True, returns arguments that can be used when calling the SDFG.

  • with_arrays – If True, includes arrays, otherwise, only symbols and scalars are included.

  • arglist – An optional cached argument list.

Return type:

List[str]

Returns:

A list of strings. For example: [‘float *A’, ‘int b’].

simplify(validate=True, validate_all=False, verbose=False)

Applies safe transformations (that will surely increase the performance) on the SDFG. For example, this fuses redundant states (safely) and removes redundant arrays.

Note:

This is an in-place operation on the SDFG.

specialize(symbols)

Sets symbolic values in this SDFG to constants.

Parameters:

symbols (Dict[str, Any]) – Values to specialize.

property start_state
states()

Returns the states in this SDFG, recursing into state scope blocks.

property subarrays

Returns a dictionary of sub-array descriptors (SubArray objects) used in this SDFG.

symbols

Global symbols for this SDFG

temp_data_name()

Returns a temporary data descriptor name that can be used in this SDFG.

to_json(hash=False)

Serializes this object to JSON format.

Returns:

A string representing the JSON-serialized SDFG.

transformation_hist

Object property of type list

transients()

Returns a dictionary mapping transient data descriptors to their parent scope entry node, or None if top-level (i.e., exists in multiple scopes).

update_sdfg_list(sdfg_list)

Given a collection of CFGs, add them all to the current SDFG’s CFG list. Any CFGs already in the list are skipped, and the newly updated list is propagated across all CFGs in the CFG tree. :note: update_sdfg_list is deprecated, please use update_cfg_list instead.

Parameters:

sdfg_list – The collection of CFGs to add to the CFG list.

using_experimental_blocks

Whether the SDFG contains experimental control flow blocks

validate(references=None, **context)
Return type:

None

view(filename=None, verbose=False)

View this sdfg in the system’s HTML viewer

Parameters:
  • filename – the filename to write the HTML to. If None, a temporary file will be created.

  • verbose – Be verbose, False by default.

dace.sdfg.sdfg.memlets_in_ast(node, arrays)

Generates a list of memlets from each of the subscripts that appear in the Python AST. Assumes the subscript slice can be coerced to a symbolic expression (e.g., no indirect access).

Parameters:
  • node (AST) – The AST node to find memlets in.

  • arrays (Dict[str, Data]) – A dictionary mapping array names to their data descriptors (a-la sdfg.arrays)

Return type:

List[Memlet]

Returns:

A list of Memlet objects in the order they appear in the AST.

dace.sdfg.state module

Contains classes of a single SDFG state and dataflow subgraphs.

class dace.sdfg.state.BlockGraphView

Bases: object

Read-only view interface of an SDFG control flow block, containing methods for memlet tracking, traversal, subgraph creation, queries, and replacements. ControlFlowBlock and StateSubgraphView inherit from this class to share methods.

abstract all_edges_recursive()

Iterate over all edges in this graph or subgraph. This includes dataflow edges, inter-state edges, and recursive edges within nested SDFGs. It returns tuples of the form (edge, parent), where the edge is either a dataflow edge, in which case the parent is an SDFG state, or an inter-stte edge, in which case the parent is a control flow graph (i.e., an SDFG or a scope block).

Return type:

Iterator[Tuple[Union[MultiConnectorEdge[Memlet], Edge[InterstateEdge]], Union[ControlFlowRegion, SDFGState]]]

abstract all_nodes_recursive(predicate=None)

Iterate over all nodes in this graph or subgraph. This includes control flow blocks, nodes in those blocks, and recursive control flow blocks and nodes within nested SDFGs. It returns tuples of the form (node, parent), where the node is either a dataflow node, in which case the parent is an SDFG state, or a control flow block, in which case the parent is a control flow graph (i.e., an SDFG or a scope block). :rtype: Iterator[Tuple[Union[Node, ControlFlowBlock], Union[ControlFlowRegion, SDFGState]]]

Parameters:

predicate (Optional[Callable[[Union[Node, ControlFlowBlock], Union[ControlFlowRegion, SDFGState]], bool]]) – An optional predicate function that decides on whether the traversal should recurse or not.

If the predicate returns False, traversal is not recursed any further into the graph found under NodeT for a given [NodeT, GraphT] pair.

abstract all_transients()

Iterate over all transients in this graph.

Return type:

List[str]

arglist(defined_syms=None, shared_transients=None)

Returns an ordered dictionary of arguments (names and types) required to invoke this subgraph.

The arguments differ from SDFG.arglist, but follow the same order, namely: <sorted data arguments>, <sorted scalar arguments>.

Data arguments contain:
  • All used non-transient data containers in the subgraph

  • All used transient data containers that were allocated outside. This includes data from memlets, transients shared across multiple states, and transients that could not be allocated within the subgraph (due to their AllocationLifetime or according to the dtypes.can_allocate function).

Scalar arguments contain:
  • Free symbols in this state/subgraph.

  • All transient and non-transient scalar data containers used in this subgraph.

This structure will create a sorted list of pointers followed by a sorted list of PoDs and structs.

Return type:

Dict[str, Data]

Returns:

An ordered dictionary of (name, data descriptor type) of all the arguments, sorted as defined here.

abstract data_nodes()

Returns all data nodes (i.e., AccessNodes, arrays) present in this graph or subgraph. Note: This does not recurse into nested SDFGs.

Return type:

List[AccessNode]

edges(**kwds)

Helper for @overload to raise when called.

abstract edges_by_connector(node, connector)

Returns a generator over edges entering or exiting the given connector of the given node.

Parameters:
  • node (Node) – Source/destination node of edges.

  • connector (AnyStr) – Source/destination connector of edges.

Return type:

Iterable[MultiConnectorEdge[Memlet]]

abstract entry_node(node)

Returns the entry node that wraps the current node, or None if it is top-level in a state.

Return type:

Optional[EntryNode]

abstract exit_node(entry_node)

Returns the exit node leaving the context opened by the given entry node.

Return type:

Optional[ExitNode]

property free_symbols: Set[str]

Returns a set of symbol names that are used, but not defined, in this graph view. In the case of an SDFG, this property is used to determine the symbolic parameters of the SDFG and verify that SDFG.symbols is complete.

Note:

Assumes that the graph is valid (i.e., without undefined or overlapping symbols).

in_degree(**kwds)

Helper for @overload to raise when called.

abstract in_edges_by_connector(node, connector)

Returns a generator over edges entering the given connector of the given node.

Parameters:
  • node (Node) – Destination node of edges.

  • connector (AnyStr) – Destination connector of edges.

Return type:

Iterable[MultiConnectorEdge[Memlet]]

abstract memlet_path(edge)

Given one edge, returns a list of edges representing a path between its source and sink nodes. Used for memlet tracking.

Note:

Behavior is undefined when there is more than one path involving this edge.

Parameters:

edge (MultiConnectorEdge[Memlet]) – An edge within a state (memlet).

Return type:

List[MultiConnectorEdge[Memlet]]

Returns:

A list of edges from a source node to a destination node.

abstract memlet_tree(edge)

Given one edge, returns a tree of edges between its node source(s) and sink(s). Used for memlet tracking.

Parameters:

edge (MultiConnectorEdge) – An edge within a state (memlet).

Return type:

MemletTree

Returns:

A tree of edges whose root is the source/sink node (depending on direction) and associated children edges.

nodes(**kwds)

Helper for @overload to raise when called.

out_degree(**kwds)

Helper for @overload to raise when called.

abstract out_edges_by_connector(node, connector)

Returns a generator over edges exiting the given connector of the given node.

Parameters:
  • node (Node) – Source node of edges.

  • connector (AnyStr) – Source connector of edges.

Return type:

Iterable[MultiConnectorEdge[Memlet]]

abstract read_and_write_sets()

Determines what data is read and written in this graph. Does not include reads to subsets of containers that have previously been written within the same state.

Return type:

Tuple[Set[AnyStr], Set[AnyStr]]

Returns:

A two-tuple of sets of things denoting ({data read}, {data written}).

abstract replace(name, new_name)

Finds and replaces all occurrences of a symbol or array in this graph.

Parameters:
  • name (str) – Name to find.

  • new_name (str) – Name to replace.

abstract replace_dict(repl, symrepl=None)

Finds and replaces all occurrences of a set of symbols or arrays in this graph.

Parameters:
  • repl (Dict[str, str]) – Mapping from names to replacements.

  • symrepl (Optional[Dict[Union[Basic, SymExpr], Union[Basic, SymExpr]]]) – Optional symbolic version of repl.

property sdfg: SDFG
signature_arglist(with_types=True, for_call=False)

Returns a list of arguments necessary to call this state or subgraph, formatted as a list of C definitions.

Parameters:
  • with_types – If True, includes argument types in the result.

  • for_call – If True, returns arguments that can be used when calling the SDFG.

Returns:

A list of strings. For example: [‘float *A’, ‘int b’].

abstract top_level_transients()

Iterate over top-level transients of this graph.

Return type:

Set[str]

abstract unordered_arglist(defined_syms=None, shared_transients=None)
Return type:

Tuple[Dict[str, Data], Dict[str, Data]]

abstract used_symbols(all_symbols, keep_defined_in_mapping=False)

Returns a set of symbol names that are used in the graph.

Parameters:
  • all_symbols (bool) – If False, only returns symbols that are needed as arguments (only used in generated code).

  • keep_defined_in_mapping (bool) – If True, symbols defined in inter-state edges that are in the symbol mapping will be removed from the set of defined symbols.

Return type:

Set[str]

class dace.sdfg.state.BreakBlock(*args, **kwargs)

Bases: ControlFlowBlock

Special control flow block to represent a continue inside of loops or switch / select blocks.

properties()
to_json(parent=None)
class dace.sdfg.state.ConditionalBlock(*args, **kwargs)

Bases: ControlFlowBlock, ControlGraphView

add_branch(condition, branch)
property branches: List[Tuple[CodeBlock | None, ControlFlowRegion]]
edges()

Helper for @overload to raise when called.

Return type:

List[Edge[InterstateEdge]]

classmethod from_json(json_obj, context=None)
inline()

Inlines the conditional region into its parent control flow region.

Return type:

Tuple[bool, Any]

Returns:

True if the inlining succeeded, false otherwise.

nodes()

Helper for @overload to raise when called.

Return type:

List[ControlFlowBlock]

properties()
replace_dict(repl, symrepl=None, replace_in_graph=True, replace_keys=True)

Finds and replaces all occurrences of a set of symbols or arrays in this graph.

Parameters:
  • repl (Dict[str, str]) – Mapping from names to replacements.

  • symrepl (Optional[Dict[Union[Basic, SymExpr], Union[Basic, SymExpr]]]) – Optional symbolic version of repl.

to_json(parent=None)
class dace.sdfg.state.ContinueBlock(*args, **kwargs)

Bases: ControlFlowBlock

Special control flow block to represent a continue inside of loops.

properties()
to_json(parent=None)
class dace.sdfg.state.ControlFlowBlock(*args, **kwargs)

Bases: BlockGraphView, ABC

property block_id: int
edges()

Helper for @overload to raise when called.

classmethod from_json(json_obj, context=None)
guid

Object property of type str

invariant_conditions

Invariant conditions for this block

is_collapsed

Show this block as collapsed

property label: str
property name: str
nodes()

Helper for @overload to raise when called.

property parent_graph: ControlFlowRegion
post_conditions

Post-conditions for this block

pre_conditions

Pre-conditions for this block

properties()
property sdfg: SDFG
set_default_lineinfo(lineinfo)

Sets the default source line information to be lineinfo, or None to revert to default mode.

to_json(parent=None)
view()
class dace.sdfg.state.ControlFlowRegion(*args, **kwargs)

Bases: OrderedDiGraph[ControlFlowBlock, dace.sdfg.InterstateEdge], ControlGraphView, ControlFlowBlock

add_edge(src, dst, data)

Adds a new edge to the graph. Must be an InterstateEdge or a subclass thereof.

Parameters:
  • u – Source node.

  • v – Destination node.

  • edge – The edge to add.

add_node(node, is_start_block=False, ensure_unique_name=False, *, is_start_state=None)

Adds node to the graph.

add_return(label=None)
Return type:

ReturnBlock

add_state(label=None, is_start_block=False, *, is_start_state=None)
Return type:

SDFGState

add_state_after(state, label=None, is_start_block=False, condition=None, assignments=None, *, is_start_state=None)

Adds a new SDFG state after an existing state, reconnecting it to the successors instead.

Parameters:
  • state (SDFGState) – The state to append the new state after.

  • label – State label.

  • is_start_block – If True, resets scope block starting state to this state.

  • condition (Optional[CodeBlock]) – Transition condition of the newly created edge between state and the new state.

  • assignments (Optional[Dict]) – Assignments to perform upon transition.

Return type:

SDFGState

Returns:

A new SDFGState object.

add_state_before(state, label=None, is_start_block=False, condition=None, assignments=None, *, is_start_state=None)

Adds a new SDFG state before an existing state, reconnecting predecessors to it instead.

Parameters:
  • state (SDFGState) – The state to prepend the new state before.

  • label – State label.

  • is_start_block – If True, resets scope block starting state to this state.

  • condition (Optional[CodeBlock]) – Transition condition of the newly created edge between state and the new state.

  • assignments (Optional[Dict]) – Assignments to perform upon transition.

Return type:

SDFGState

Returns:

A new SDFGState object.

all_control_flow_blocks(recursive=False)

Iterate over all control flow blocks in this control flow graph.

Return type:

Iterator[ControlFlowBlock]

all_control_flow_regions(recursive=False)

Iterate over this and all nested control flow regions.

Return type:

Iterator[ControlFlowRegion]

all_interstate_edges(recursive=False)

Iterate over all interstate edges in this control flow graph.

Return type:

Iterator[Edge[InterstateEdge]]

all_sdfgs_recursive()

Iterate over this and all nested SDFGs.

Return type:

Iterator[SDFG]

all_states()

Iterate over all states in this control flow graph.

Return type:

Iterator[SDFGState]

property cfg_id: int

Returns the unique index of the current CFG within the current tree of CFGs (Top-level CFG/SDFG is 0, nested CFGs/SDFGs are greater).

property cfg_list: List[ControlFlowRegion]
classmethod from_json(json_obj, context=None)
inline()

Inlines the control flow region into its parent control flow region (if it exists).

Return type:

Tuple[bool, Any]

Returns:

True if the inlining succeeded, false otherwise.

properties()
reset_cfg_list()

Reset the CFG list when changes have been made to the SDFG’s CFG tree. This collects all control flow graphs recursively and propagates the collection to all CFGs as the new CFG list.

Return type:

List[ControlFlowRegion]

Returns:

The newly updated CFG list.

property root_sdfg: SDFG
property start_block

Returns the starting block of this ControlFlowGraph.

state(state_id)
Return type:

SDFGState

to_json(parent=None)
update_cfg_list(cfg_list)

Given a collection of CFGs, add them all to the current SDFG’s CFG list. Any CFGs already in the list are skipped, and the newly updated list is propagated across all CFGs in the CFG tree.

Parameters:

cfg_list – The collection of CFGs to add to the CFG list.

class dace.sdfg.state.ControlGraphView(*args, **kwargs)

Bases: BlockGraphView, ABC

all_edges_recursive()

Iterate over all edges in this graph or subgraph. This includes dataflow edges, inter-state edges, and recursive edges within nested SDFGs. It returns tuples of the form (edge, parent), where the edge is either a dataflow edge, in which case the parent is an SDFG state, or an inter-stte edge, in which case the parent is a control flow graph (i.e., an SDFG or a scope block).

Return type:

Iterator[Tuple[Union[MultiConnectorEdge[Memlet], Edge[InterstateEdge]], Union[ControlFlowRegion, SDFGState]]]

all_nodes_recursive(predicate=None)

Iterate over all nodes in this graph or subgraph. This includes control flow blocks, nodes in those blocks, and recursive control flow blocks and nodes within nested SDFGs. It returns tuples of the form (node, parent), where the node is either a dataflow node, in which case the parent is an SDFG state, or a control flow block, in which case the parent is a control flow graph (i.e., an SDFG or a scope block). :rtype: Iterator[Tuple[Union[Node, ControlFlowBlock], Union[ControlFlowRegion, SDFGState]]]

Parameters:

predicate – An optional predicate function that decides on whether the traversal should recurse or not.

If the predicate returns False, traversal is not recursed any further into the graph found under NodeT for a given [NodeT, GraphT] pair.

all_transients()

Iterate over all transients in this graph.

Return type:

List[str]

data_nodes()

Returns all data nodes (i.e., AccessNodes, arrays) present in this graph or subgraph. Note: This does not recurse into nested SDFGs.

Return type:

List[AccessNode]

edges(**kwds)

Helper for @overload to raise when called.

edges_by_connector(node, connector)

Returns a generator over edges entering or exiting the given connector of the given node.

Parameters:
  • node (Node) – Source/destination node of edges.

  • connector (AnyStr) – Source/destination connector of edges.

Return type:

Iterable[MultiConnectorEdge[Memlet]]

entry_node(node)

Returns the entry node that wraps the current node, or None if it is top-level in a state.

Return type:

Optional[EntryNode]

exit_node(entry_node)

Returns the exit node leaving the context opened by the given entry node.

Return type:

Optional[ExitNode]

in_edges_by_connector(node, connector)

Returns a generator over edges entering the given connector of the given node.

Parameters:
  • node (Node) – Destination node of edges.

  • connector (AnyStr) – Destination connector of edges.

Return type:

Iterable[MultiConnectorEdge[Memlet]]

memlet_path(edge)

Given one edge, returns a list of edges representing a path between its source and sink nodes. Used for memlet tracking.

Note:

Behavior is undefined when there is more than one path involving this edge.

Parameters:

edge (MultiConnectorEdge[Memlet]) – An edge within a state (memlet).

Return type:

List[MultiConnectorEdge[Memlet]]

Returns:

A list of edges from a source node to a destination node.

memlet_tree(edge)

Given one edge, returns a tree of edges between its node source(s) and sink(s). Used for memlet tracking.

Parameters:

edge (MultiConnectorEdge) – An edge within a state (memlet).

Return type:

MemletTree

Returns:

A tree of edges whose root is the source/sink node (depending on direction) and associated children edges.

nodes(**kwds)

Helper for @overload to raise when called.

out_edges_by_connector(node, connector)

Returns a generator over edges exiting the given connector of the given node.

Parameters:
  • node (Node) – Source node of edges.

  • connector (AnyStr) – Source connector of edges.

Return type:

Iterable[MultiConnectorEdge[Memlet]]

properties()
read_and_write_sets()

Determines what data is read and written in this graph. Does not include reads to subsets of containers that have previously been written within the same state.

Return type:

Tuple[Set[AnyStr], Set[AnyStr]]

Returns:

A two-tuple of sets of things denoting ({data read}, {data written}).

replace(name, new_name)

Finds and replaces all occurrences of a symbol or array in this graph.

Parameters:
  • name (str) – Name to find.

  • new_name (str) – Name to replace.

replace_dict(repl, symrepl=None, replace_in_graph=True, replace_keys=False)

Finds and replaces all occurrences of a set of symbols or arrays in this graph.

Parameters:
  • repl (Dict[str, str]) – Mapping from names to replacements.

  • symrepl (Optional[Dict[Union[Basic, SymExpr], Union[Basic, SymExpr]]]) – Optional symbolic version of repl.

top_level_transients()

Iterate over top-level transients of this graph.

Return type:

Set[str]

unordered_arglist(defined_syms=None, shared_transients=None)
Return type:

Tuple[Dict[str, Data], Dict[str, Data]]

used_symbols(all_symbols, keep_defined_in_mapping=False)

Returns a set of symbol names that are used in the graph.

Parameters:
  • all_symbols (bool) – If False, only returns symbols that are needed as arguments (only used in generated code).

  • keep_defined_in_mapping (bool) – If True, symbols defined in inter-state edges that are in the symbol mapping will be removed from the set of defined symbols.

Return type:

Set[str]

class dace.sdfg.state.DataflowGraphView(*args, **kwargs)

Bases: BlockGraphView, ABC

all_edges_recursive()

Iterate over all edges in this graph or subgraph. This includes dataflow edges, inter-state edges, and recursive edges within nested SDFGs. It returns tuples of the form (edge, parent), where the edge is either a dataflow edge, in which case the parent is an SDFG state, or an inter-stte edge, in which case the parent is a control flow graph (i.e., an SDFG or a scope block).

Return type:

Iterator[Tuple[Union[MultiConnectorEdge[Memlet], Edge[InterstateEdge]], Union[ControlFlowRegion, SDFGState]]]

all_nodes_recursive(predicate=None)

Iterate over all nodes in this graph or subgraph. This includes control flow blocks, nodes in those blocks, and recursive control flow blocks and nodes within nested SDFGs. It returns tuples of the form (node, parent), where the node is either a dataflow node, in which case the parent is an SDFG state, or a control flow block, in which case the parent is a control flow graph (i.e., an SDFG or a scope block). :rtype: Iterator[Tuple[Union[Node, ControlFlowBlock], Union[ControlFlowRegion, SDFGState]]]

Parameters:

predicate – An optional predicate function that decides on whether the traversal should recurse or not.

If the predicate returns False, traversal is not recursed any further into the graph found under NodeT for a given [NodeT, GraphT] pair.

all_transients()

Iterate over all transients in this state.

Return type:

List[str]

data_nodes()

Returns all data_nodes (arrays) present in this state.

Return type:

List[AccessNode]

defined_symbols()

Returns a dictionary that maps currently-defined symbols in this SDFG state or subgraph to their types.

Return type:

Dict[str, Data]

edges(**kwds)

Helper for @overload to raise when called.

edges_by_connector(node, connector)

Returns a generator over edges entering or exiting the given connector of the given node.

Parameters:
  • node (Node) – Source/destination node of edges.

  • connector (AnyStr) – Source/destination connector of edges.

Return type:

Iterable[MultiConnectorEdge[Memlet]]

entry_node(node)

Returns the entry node that wraps the current node, or None if it is top-level in a state.

Return type:

Optional[EntryNode]

exit_node(entry_node)

Returns the exit node leaving the context opened by the given entry node.

Return type:

Optional[ExitNode]

property free_symbols: Set[str]

Returns a set of symbol names that are used, but not defined, in this graph view (SDFG state or subgraph thereof).

Note:

Assumes that the graph is valid (i.e., without undefined or overlapping symbols).

in_edges_by_connector(node, connector)

Returns a generator over edges entering the given connector of the given node.

Parameters:
  • node (Node) – Destination node of edges.

  • connector (AnyStr) – Destination connector of edges.

Return type:

Iterable[MultiConnectorEdge[Memlet]]

is_leaf_memlet(e)
memlet_path(edge)

Given one edge, returns a list of edges representing a path between its source and sink nodes. Used for memlet tracking.

Note:

Behavior is undefined when there is more than one path involving this edge.

Parameters:

edge (MultiConnectorEdge[Memlet]) – An edge within this state.

Return type:

List[MultiConnectorEdge[Memlet]]

Returns:

A list of edges from a source node to a destination node.

memlet_tree(edge)

Given one edge, returns a tree of edges between its node source(s) and sink(s). Used for memlet tracking.

Parameters:

edge (MultiConnectorEdge) – An edge within a state (memlet).

Return type:

MemletTree

Returns:

A tree of edges whose root is the source/sink node (depending on direction) and associated children edges.

nodes(**kwds)

Helper for @overload to raise when called.

out_edges_by_connector(node, connector)

Returns a generator over edges exiting the given connector of the given node.

Parameters:
  • node (Node) – Source node of edges.

  • connector (AnyStr) – Source connector of edges.

Return type:

Iterable[MultiConnectorEdge[Memlet]]

properties()
read_and_write_sets()

Determines what data is read and written in this subgraph.

Return type:

Tuple[Set[AnyStr], Set[AnyStr]]

Returns:

A two-tuple of sets of things denoting ({data read}, {data written}).

replace(name, new_name)

Finds and replaces all occurrences of a symbol or array in this state.

Parameters:
  • name (str) – Name to find.

  • new_name (str) – Name to replace.

replace_dict(repl, symrepl=None)

Finds and replaces all occurrences of a set of symbols or arrays in this graph.

Parameters:
  • repl (Dict[str, str]) – Mapping from names to replacements.

  • symrepl (Optional[Dict[Union[Basic, SymExpr], Union[Basic, SymExpr]]]) – Optional symbolic version of repl.

scope_children(return_ids=False, validate=True)
Return type:

Dict[Union[Node, SDFGState], List[Node]]

scope_dict(return_ids=False, validate=True)
Return type:

Dict[Node, Union[SDFGState, Node]]

scope_leaves()
Return type:

List[ScopeTree]

scope_subgraph(entry_node, include_entry=True, include_exit=True)
scope_tree()
Return type:

ScopeTree

signature_arglist(with_types=True, for_call=False)

Returns a list of arguments necessary to call this state or subgraph, formatted as a list of C definitions.

Parameters:
  • with_types – If True, includes argument types in the result.

  • for_call – If True, returns arguments that can be used when calling the SDFG.

Returns:

A list of strings. For example: [‘float *A’, ‘int b’].

top_level_transients()

Iterate over top-level transients of this state.

unordered_arglist(defined_syms=None, shared_transients=None)
Return type:

Tuple[Dict[str, Data], Dict[str, Data]]

used_symbols(all_symbols, keep_defined_in_mapping=False)

Returns a set of symbol names that are used in the graph.

Parameters:
  • all_symbols (bool) – If False, only returns symbols that are needed as arguments (only used in generated code).

  • keep_defined_in_mapping (bool) – If True, symbols defined in inter-state edges that are in the symbol mapping will be removed from the set of defined symbols.

Return type:

Set[str]

class dace.sdfg.state.FunctionCallRegion(*args, **kwargs)

Bases: NamedRegion

arguments

Object property of type dict

properties()
class dace.sdfg.state.LoopRegion(*args, **kwargs)

Bases: ControlFlowRegion

A control flow region that represents a loop.

Like in traditional programming languages, a loop has a condition that is checked before each iteration. It may have zero or more initialization statements that are executed before the first loop iteration, and zero or more update statements that are executed after each iteration. For example, a loop with only a condition and neither an initialization nor an update statement is equivalent to a while loop, while a loop with initialization and update statements represents a for loop. Loops may additionally be inverted, meaning that the condition is checked after the first iteration instead of before.

A loop region, like any other control flow region, has a single distinct entry / start block, and one or more exit blocks. Exit blocks are blocks that have no outgoing edges or only conditional outgoing edges. Whenever an exit block finshes executing, one iteration of the loop is completed.

Loops may have an arbitrary number of break states. Whenever a break state finishes executing, the loop is exited immediately. A loop may additionally have an arbitrary number of continue states. Whenever a continue state finishes executing, the next iteration of the loop is started immediately (with execution of the update statement(s), if present).

add_break(label=None)
Return type:

BreakBlock

add_continue(label=None)
Return type:

ContinueBlock

property has_break: bool
property has_continue: bool
property has_return: bool
init_statement

The loop init statement. May be None if the initialization happens elsewhere.

inline()

Inlines the loop region into its parent control flow region.

Return type:

Tuple[bool, Any]

Returns:

True if the inlining succeeded, false otherwise.

inverted

If True, the loop condition is checked after the first iteration.

loop_condition

The loop condition

loop_variable

The loop variable, if given

properties()
replace_dict(repl, symrepl=None, replace_in_graph=True, replace_keys=True)

Finds and replaces all occurrences of a set of symbols or arrays in this graph.

Parameters:
  • repl (Dict[str, str]) – Mapping from names to replacements.

  • symrepl (Optional[Dict[Union[Basic, SymExpr], Union[Basic, SymExpr]]]) – Optional symbolic version of repl.

update_before_condition

If False, the loop condition is checked before the update statement is executed. This only applies to inverted loops, turning them from a typical do-while style into a while(true) with a break before the update (at the end of an iteration) if the condition no longer holds.

update_statement

The loop update statement. May be None if the update happens elsewhere.

class dace.sdfg.state.NamedRegion(*args, **kwargs)

Bases: ControlFlowRegion

debuginfo

Object property of type DebugInfo

properties()
class dace.sdfg.state.ReturnBlock(*args, **kwargs)

Bases: ControlFlowBlock

Special control flow block to represent an early return out of the SDFG or a nested procedure / SDFG.

properties()
to_json(parent=None)
class dace.sdfg.state.SDFGState(*args, **kwargs)

Bases: OrderedMultiDiConnectorGraph[Node, Memlet], ControlFlowBlock, DataflowGraphView

An acyclic dataflow multigraph in an SDFG, corresponding to a single state in the SDFG state machine.

add_access(array_or_stream_name, debuginfo=None)

Adds an access node to this SDFG state.

Parameters:
  • array_or_stream_name (str) – The name of the array/stream.

  • debuginfo (Optional[DebugInfo]) – Source line information for this access node.

Return type:

AccessNode

Returns:

An array access node.

add_array(name, shape, dtype, storage=<StorageType.Default: 1>, transient=False, strides=None, offset=None, lifetime=<AllocationLifetime.Scope: 1>, debuginfo=None, total_size=None, find_new_name=False, alignment=0)
Note:

This function is deprecated.

add_consume(name, elements, condition=None, schedule=<ScheduleType.Default: 1>, chunksize=1, debuginfo=None, language=<Language.Python: 1>)

Adds consume entry and consume exit nodes.

Parameters:
  • name – Label

  • elements (Tuple[str, str]) – A 2-tuple signifying the processing element index and number of total processing elements

  • condition (Optional[str]) – Quiescence condition to finish consuming, or None (by default) to consume until the stream is empty for the first time. If false, will consume forever.

  • schedule – Consume schedule type.

  • chunksize – Maximal number of elements to consume at a time.

  • debuginfo – Source code line information for debugging.

  • language – Code language for condition.

Return type:

Tuple[ConsumeEntry, ConsumeExit]

Returns:

(consume_entry, consume_exit) node 2-tuple

add_edge(u, u_connector, v, v_connector, memlet)

Adds an edge to the graph containing the specified data. Returns the added edge.

add_edge_pair(scope_node, internal_node, external_node, internal_memlet, external_memlet=None, scope_connector=None, internal_connector=None, external_connector=None)

Adds two edges around a scope node (e.g., map entry, consume exit).

The internal memlet (connecting to the internal node) has to be specified. If external_memlet (i.e., connecting to the node out of the scope) is not specified, it is propagated automatically using internal_memlet and the scope.

Parameters:
  • scope_node – A scope node (for example, map exit) to add edges around.

  • internal_node – The node within the scope to connect to. If scope_node is an entry node, this means the node connected to the outgoing edge, else incoming.

  • external_node – The node out of the scope to connect to.

  • internal_memlet – The memlet on the edge to/from internal_node.

  • external_memlet – The memlet on the edge to/from external_node (optional, will propagate internal_memlet if not specified).

  • scope_connector – A scope connector name (or a unique number if not specified).

  • internal_connector – The connector on internal_node to connect to.

  • external_connector – The connector on external_node to connect to.

Returns:

A 2-tuple representing the (internal, external) edges.

add_map(name, ndrange, schedule=<ScheduleType.Default: 1>, unroll=False, debuginfo=None)

Adds a map entry and map exit.

Parameters:
  • name – Map label

  • ndrange (Union[Dict[str, Union[str, Subset]], List[Tuple[str, Union[str, Subset]]]]) – Mapping between range variable names and their subsets (parsed from strings)

  • schedule – Map schedule type

  • unroll – True if should unroll the map in code generation

Return type:

Tuple[MapEntry, MapExit]

Returns:

(map_entry, map_exit) node 2-tuple

add_mapped_tasklet(name, map_ranges, inputs, code, outputs, schedule=<ScheduleType.Default: 1>, unroll_map=False, location=None, language=<Language.Python: 1>, debuginfo=None, external_edges=False, input_nodes=None, output_nodes=None, propagate=True)

Convenience function that adds a map entry, tasklet, map exit, and the respective edges to external arrays.

Parameters:
  • name (str) – Tasklet (and wrapping map) name

  • map_ranges (Union[Dict[str, Union[str, Subset]], List[Tuple[str, Union[str, Subset]]]]) – Mapping between variable names and their subsets

  • inputs (Dict[str, Memlet]) – Mapping between input local variable names and their memlets

  • code (str) – Code (written in language)

  • outputs (Dict[str, Memlet]) – Mapping between output local variable names and their memlets

  • schedule – Map schedule

  • unroll_map – True if map should be unrolled in code generation

  • location – Execution location indicator.

  • language – Programming language in which the code is written

  • debuginfo – Source line information

  • external_edges – Create external access nodes and connect them with memlets automatically

  • input_nodes (Union[Dict[str, AccessNode], List[AccessNode], Set[AccessNode], None]) – Mapping between data names and corresponding input nodes to link to, if external_edges is True.

  • output_nodes (Union[Dict[str, AccessNode], List[AccessNode], Set[AccessNode], None]) – Mapping between data names and corresponding output nodes to link to, if external_edges is True.

  • propagate – If True, computes outer memlets via propagation. False will run faster but the SDFG may not be semantically correct.

Return type:

Tuple[Tasklet, MapEntry, MapExit]

Returns:

tuple of (tasklet, map_entry, map_exit)

add_memlet_path(*path_nodes, memlet=None, src_conn=None, dst_conn=None, propagate=True)

Adds a path of memlet edges between the given nodes, propagating from the given innermost memlet.

Parameters:
  • path_nodes – Nodes participating in the path (in the given order).

  • memlet – (mandatory) The memlet at the innermost scope (e.g., the incoming memlet to a tasklet (last node), or an outgoing memlet from an array (first node), followed by scope exits).

  • src_conn – Connector at the beginning of the path.

  • dst_conn – Connector at the end of the path.

add_nested_sdfg(sdfg, parent, inputs, outputs, symbol_mapping=None, name=None, schedule=<ScheduleType.Default: 1>, location=None, debuginfo=None)

Adds a nested SDFG to the SDFG state.

add_node(node)

Adds node to the graph.

add_pipeline(name, ndrange, init_size=0, init_overlap=False, drain_size=0, drain_overlap=False, additional_iterators={}, schedule=<ScheduleType.FPGA_Device: 13>, debuginfo=None, **kwargs)

Adds a pipeline entry and pipeline exit. These are used for FPGA kernels to induce distinct behavior between an “initialization” phase, a main streaming phase, and a “draining” phase, which require a additive number of extra loop iterations (i.e., N*M + I + D), where I and D are the number of initialization/drain iterations. The code can detect which phase it is in by querying the init_condition() and drain_condition() boolean variable.

Parameters:
  • name – Pipeline label

  • ndrange – Mapping between range variable names and their subsets (parsed from strings)

  • init_size – Number of iterations of initialization phase.

  • init_overlap – Whether the initialization phase overlaps with the “main” streaming phase of the loop.

  • drain_size – Number of iterations of draining phase.

  • drain_overlap – Whether the draining phase overlaps with the “main” streaming phase of the loop.

  • additional_iterators – a dictionary containing additional iterators that will be created for this scope and that are not automatically managed by the scope code. The dictionary takes the form ‘variable_name’ -> init_value

Return type:

Tuple[PipelineEntry, PipelineExit]

Returns:

(map_entry, map_exit) node 2-tuple

add_read(array_or_stream_name, debuginfo=None)

Adds an access node to this SDFG state (alias of add_access).

Parameters:
  • array_or_stream_name (str) – The name of the array/stream.

  • debuginfo (Optional[DebugInfo]) – Source line information for this access node.

Return type:

AccessNode

Returns:

An array access node.

See:

add_access

add_reduce(wcr, axes, identity=None, schedule=<ScheduleType.Default: 1>, debuginfo=None)

Adds a reduction node.

Parameters:
  • wcr – A lambda function representing the reduction operation

  • axes – A tuple of axes to reduce the input memlet from, or None for all axes

  • identity – If not None, initializes output memlet values with this value

  • schedule – Reduction schedule type

Return type:

Reduce

Returns:

A Reduce node

add_scalar(name, dtype, storage=<StorageType.Default: 1>, transient=False, lifetime=<AllocationLifetime.Scope: 1>, debuginfo=None)
Note:

This function is deprecated.

add_stream(name, dtype, buffer_size=1, shape=(1, ), storage=<StorageType.Default: 1>, transient=False, offset=None, lifetime=<AllocationLifetime.Scope: 1>, debuginfo=None)
Note:

This function is deprecated.

add_tasklet(name, inputs, outputs, code, language=<Language.Python: 1>, state_fields=None, code_global='', code_init='', code_exit='', location=None, side_effects=None, debuginfo=None)

Adds a tasklet to the SDFG state.

add_transient(name, shape, dtype, storage=<StorageType.Default: 1>, strides=None, offset=None, lifetime=<AllocationLifetime.Scope: 1>, debuginfo=None, total_size=None, alignment=0)
Note:

This function is deprecated.

add_write(array_or_stream_name, debuginfo=None)

Adds an access node to this SDFG state (alias of add_access).

Parameters:
  • array_or_stream_name (str) – The name of the array/stream.

  • debuginfo (Optional[DebugInfo]) – Source line information for this access node.

Return type:

AccessNode

Returns:

An array access node.

See:

add_access

all_edges_and_connectors(*nodes)

Returns an iterable to incoming and outgoing Edge objects, along with their connector types.

dynamic_executions

The number of executions of this state is dynamic

executions

The number of times this state gets executed (0 stands for unbounded)

fill_scope_connectors()

Creates new “IN_%d” and “OUT_%d” connectors on each scope entry and exit, depending on array names.

classmethod from_json(json_obj, context={'sdfg': None}, pre_ret=None)

Loads the node properties, label and type into a dict.

Parameters:

json_obj – The object containing information about this node. NOTE: This may not be a string!

Returns:

An SDFGState instance constructed from the passed data

instrument

Measure execution statistics with given method

is_empty()
location

Full storage location identifier (e.g., rank, GPU ID)

nodes()

Returns an iterable to internal graph nodes.

Return type:

List[Node]

nosync

Do not synchronize at the end of the state

property parent

Returns the parent SDFG of this state.

properties()
ranges

Variable ranges, typically within loops

remove_edge(edge)

Removes the specified Edge object.

remove_edge_and_connectors(edge)
remove_memlet_path(edge, remove_orphans=True)

Removes all memlets and associated connectors along a path formed by a given edge. Undefined behavior if the path is ambiguous. Orphaned entry and exit nodes will be connected with empty edges to maintain connectivity of the graph.

Parameters:
  • edge (MultiConnectorEdge) – An edge that is part of the path that should be removed, which will be passed to memlet_path to determine the edges to be removed.

  • remove_orphans (bool) – Remove orphaned data nodes from the graph if they become orphans from removing this memlet path.

Return type:

None

remove_node(node)

Removes the specified node.

symbol_instrument

Instrument symbol values when this state is executed

symbol_instrument_condition

Condition under which to trigger the symbol instrumentation

symbols_defined_at(node)

Returns all symbols available to a given node. The symbols a node can access are a combination of the global SDFG symbols, symbols defined in inter-state paths to its state, and symbols defined in scope entries in the path to this node.

Parameters:

node (Node) – The given node.

Return type:

Dict[str, typeclass]

Returns:

A dictionary mapping symbol names to their types.

to_json(parent=None)
validate()
Return type:

None

class dace.sdfg.state.StateSubgraphView(graph, subgraph_nodes)

Bases: SubgraphView, DataflowGraphView

A read-only subgraph view of an SDFG state.

property sdfg: SDFG

dace.sdfg.utils module

Various utility functions to create, traverse, and modify SDFGs.

exception dace.sdfg.utils.StopTraversal

Bases: Exception

Special exception that stops DFS conditional traversal beyond the current node.

See:

dfs_conditional

dace.sdfg.utils.change_edge_dest(graph, node_a, node_b)

Changes the destination of edges from node A to node B.

The function finds all edges in the graph that have node A as their destination. It then creates a new edge for each one found, using the same source nodes and data, but node B as the destination. Afterwards, it deletes the edges found and inserts the new ones into the graph.

Parameters:
dace.sdfg.utils.change_edge_src(graph, node_a, node_b)

Changes the sources of edges from node A to node B.

The function finds all edges in the graph that have node A as their source. It then creates a new edge for each one found, using the same destination nodes and data, but node B as the source. Afterwards, it deletes the edges found and inserts the new ones into the graph.

Parameters:
dace.sdfg.utils.check_sdfg(sdfg)

Checks that the parent attributes of an SDFG are correct.

Parameters:

sdfg (SDFG) – The SDFG to check.

Raises:

AssertionError – If any of the parent attributes are incorrect.

dace.sdfg.utils.concurrent_subgraphs(graph)

Finds subgraphs of an SDFGState or ScopeSubgraphView that can run concurrently.

dace.sdfg.utils.consolidate_edges(sdfg, starting_scope=None)

Union scope-entering memlets relating to the same data node in all states. This effectively reduces the number of connectors and allows more transformations to be performed, at the cost of losing the individual per-tasklet memlets.

Parameters:
  • sdfg (SDFG) – The SDFG to consolidate.

  • starting_scope – If not None, starts with a certain scope

  • propagate – If True, applies memlet propagation after consolidation

Return type:

int

Returns:

Number of edges removed.

dace.sdfg.utils.consolidate_edges_scope(state, scope_node)

Union scope-entering memlets relating to the same data node in a scope. This effectively reduces the number of connectors and allows more transformations to be performed, at the cost of losing the individual per-tasklet memlets.

Parameters:
  • state (SDFGState) – The SDFG state in which the scope to consolidate resides.

  • scope_node (Union[EntryNode, ExitNode]) – The scope node whose edges will be consolidated.

Return type:

int

Returns:

Number of edges removed.

dace.sdfg.utils.depth_limited_dfs_iter(source, depth)

Produce nodes in a Depth-Limited DFS.

Return best node and its value using a limited-depth Search (depth-limited DFS).

dace.sdfg.utils.dfs_conditional(G, sources=None, condition=None, reverse=False, yield_parent=False)

Produce nodes in a depth-first ordering with an optional condition to stop traversal. If StopTraversal is raised during iteration, the outgoing edges of the current node will not be traversed.

Parameters:
  • G – An input DiGraph (may have cycles).

  • sources – (optional) node or list of nodes that specify starting point(s) for depth-first search and return edges in the component reachable from source. If None, traverses from every node in the graph.

  • condition – (optional) a callback that receives the traversed parent and child. Called before each child node is traversed. If it returns True, traversal proceeds normally. If False, the child and reachable nodes are not traversed.

  • reverse – If True, traverses the graph backwards from the sources.

  • yield_parent – If True, yields a 2-tuple of (parent, child)

Returns:

A generator of edges in the lastvisit depth-first-search.

Note:

Based on http://www.ics.uci.edu/~eppstein/PADS/DFS.py by D. Eppstein, July 2004.

Note:

If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph are searched.

dace.sdfg.utils.dfs_topological_sort(G, sources=None, condition=None, reverse=False)

Produce nodes in a depth-first topological ordering.

The function produces nodes in a depth-first topological ordering (DFS to make sure maps are visited properly), with the condition that each node visited had all its predecessors visited. Applies for DAGs only, but works on any directed graph.

Parameters:
  • G – An input DiGraph (assumed acyclic).

  • sources – (optional) node or list of nodes that specify starting point(s) for depth-first search and return edges in the component reachable from source.

  • reverse – If True, traverses the graph backwards from the sources.

Returns:

A generator of nodes in the lastvisit depth-first-search.

Note:

Based on http://www.ics.uci.edu/~eppstein/PADS/DFS.py by D. Eppstein, July 2004.

Note:

If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph are searched.

dace.sdfg.utils.distributed_compile(sdfg, comm, validate=True)

Compiles an SDFG in rank 0 of MPI communicator comm. Then, the compiled SDFG is loaded in all other ranks.

Parameters:
  • sdfg (SDFG) – SDFG to be compiled.

  • comm – MPI communicator. Intracomm is the base mpi4py communicator class.

Return type:

CompiledSDFG

Returns:

Compiled SDFG.

Note:

This method can be used only if the module mpi4py is installed.

dace.sdfg.utils.dynamic_map_inputs(state, map_entry)

For a given map entry node, returns a list of dynamic-range input edges.

Parameters:
  • state (SDFGState) – The state in which the map entry node resides.

  • map_entry (MapEntry) – The given node.

Return type:

List[MultiConnectorEdge]

Returns:

A list of edges in state whose destination is map entry and denote dynamic-range input memlets.

dace.sdfg.utils.find_input_arraynode(graph, edge)
dace.sdfg.utils.find_output_arraynode(graph, edge)
dace.sdfg.utils.fuse_states(sdfg, permissive=False, progress=None)

Fuses all possible states of an SDFG (and all sub-SDFGs) using an optimized routine that uses the structure of the StateFusion transformation.

Parameters:
  • sdfg (SDFG) – The SDFG to transform.

  • permissive (bool) – If True, operates in permissive mode, which ignores some race condition checks.

  • progress (Optional[bool]) – If True, prints out a progress bar of fusion (may be inaccurate, requires tqdm). If None, prints out progress if over 5 seconds have passed. If False, never shows progress bar.

Return type:

int

Returns:

The total number of states fused.

dace.sdfg.utils.get_all_view_nodes(state, view)

Given a view access node, returns a list of viewed access nodes if existent, else None

Return type:

List[AccessNode]

dace.sdfg.utils.get_global_memlet_path_dst(sdfg, state, edge)

Finds the global destination node of an edge/memlet path, crossing nested SDFG scopes.

Parameters:
  • sdfg (SDFG) – The SDFG containing the edge.

  • state (SDFGState) – The state containing the edge.

  • edge (MultiConnectorEdge) – The edge to find the global destination node for.

Return type:

Node

Returns:

The global destination node of the edge.

dace.sdfg.utils.get_global_memlet_path_src(sdfg, state, edge)

Finds the global source node of an edge/memlet path, crossing nested SDFG scopes.

Parameters:
  • sdfg (SDFG) – The SDFG containing the edge.

  • state (SDFGState) – The state containing the edge.

  • edge (MultiConnectorEdge) – The edge to find the global source node for.

Return type:

Node

Returns:

The global source node of the edge.

dace.sdfg.utils.get_last_view_node(state, view)

Given a view access node, returns the last viewed access node if existent, else None

Return type:

AccessNode

dace.sdfg.utils.get_next_nonempty_states(sdfg, state)

From the given state, return the next set of states that are reachable in the SDFG, skipping empty states. Traversal stops at the non-empty state.

This function is used to determine whether synchronization should happen at the end of a GPU state.

Parameters:
  • sdfg (SDFG) – The SDFG that contains the state.

  • state (SDFGState) – The state to start from.

Return type:

Set[SDFGState]

Returns:

A set of reachable non-empty states.

dace.sdfg.utils.get_thread_local_data(sdfg)

Returns a list of all data that are thread-local in the SDFG.

This method DOES NOT apply recursively to nested SDFGs. It is also does not take into account outer Maps.

Parameters:

sdfg (SDFG) – The SDFG to check.

Return type:

List[str]

Returns:

A list of the names of all data that are thread-local in the SDFG.

dace.sdfg.utils.get_view_edge(state, view)

Given a view access node, returns the incoming/outgoing edge which points to the viewed access node. See the ruleset in the documentation of dace.data.View.

Parameters:
  • state (SDFGState) – The state in which the view resides.

  • view (AccessNode) – The view access node.

Return type:

MultiConnectorEdge[Memlet]

Returns:

An edge pointing to the viewed data or None if view is invalid.

See:

dace.data.View

dace.sdfg.utils.get_view_node(state, view)

Given a view access node, returns the viewed access node if existent, else None

Return type:

AccessNode

dace.sdfg.utils.has_dynamic_map_inputs(state, map_entry)

Returns True if a map entry node has dynamic-range inputs.

Parameters:
  • state (SDFGState) – The state in which the map entry node resides.

  • map_entry (MapEntry) – The given node.

Return type:

bool

Returns:

True if there are dynamic-range input memlets, False otherwise.

dace.sdfg.utils.inline_conditional_blocks(sdfg, permissive=False, progress=None)
Return type:

int

dace.sdfg.utils.inline_control_flow_regions(sdfg, permissive=False, progress=None)
Return type:

int

dace.sdfg.utils.inline_loop_blocks(sdfg, permissive=False, progress=None)
Return type:

int

dace.sdfg.utils.inline_sdfgs(sdfg, permissive=False, progress=None, multistate=True)

Inlines all possible nested SDFGs (or sub-SDFGs) using an optimized routine that uses the structure of the SDFG hierarchy.

Parameters:
  • sdfg (SDFG) – The SDFG to transform.

  • permissive (bool) – If True, operates in permissive mode, which ignores some checks.

  • progress (Optional[bool]) – If True, prints out a progress bar of inlining (may be inaccurate, requires tqdm). If None, prints out progress if over 5 seconds have passed. If False, never shows progress bar.

  • multistate (bool) – Include

Return type:

int

Returns:

The total number of SDFGs inlined.

dace.sdfg.utils.is_array_stream_view(sdfg, dfg, node)

Test whether a stream is directly connected to an array.

dace.sdfg.utils.is_fpga_kernel(sdfg, state)

Returns whether the given state is an FPGA kernel and should be dispatched to the FPGA code generator.

Returns:

True if this is an FPGA kernel, False otherwise.

dace.sdfg.utils.is_nonfree_sym_dependent(node, desc, state, fsymbols)

Checks whether the Array or View descriptor is non-free symbol dependent. An Array is non-free symbol dependent when its attributes (e.g., shape) depend on non-free symbols. A View is non-free symbol dependent when either its adjacent edges or its viewed node depend on non-free symbols.

Parameters:
  • node (AccessNode) – the access node to check

  • desc (Data) – the data descriptor to check

  • state (SDFGState) – the state that contains the node

  • fsymbols (Set[str]) – the free symbols to check against

Return type:

bool

dace.sdfg.utils.is_parallel(state, node=None)

Returns True if a node or state are contained within a parallel section.

Parameters:
  • state (SDFGState) – The state to test.

  • node (Optional[Node]) – An optional node in the state to test. If None, only checks state.

Return type:

bool

Returns:

True if the state or node are located within a map scope that is scheduled to run in parallel, False otherwise.

dace.sdfg.utils.load_precompiled_sdfg(folder)

Loads a pre-compiled SDFG from an output folder (e.g. “.dacecache/program”). Folder must contain a file called “program.sdfg” and a subfolder called “build” with the shared object.

Parameters:

folder (str) – Path to SDFG output folder.

Returns:

A callable CompiledSDFG object.

dace.sdfg.utils.local_transients(sdfg, dfg, entry_node, include_nested=False)

Returns transients local to the scope defined by the specified entry node in the dataflow graph.

Parameters:
  • entry_node – The entry node that opens the scope. If None, the top-level scope is used.

  • include_nested – Include transients defined in nested scopes.

dace.sdfg.utils.make_dynamic_map_inputs_unique(sdfg)
dace.sdfg.utils.map_view_to_array(vdesc, adesc, subset)

Finds the matching dimensions mapping between a data descriptor and a view reinterpreting it, if and only if the view represents a slice (with potential new, “unsqueezed” axes). Views have the following relationship (w.l.o.g.): (array) –subset–> (view). For every memlet that goes out of a view, we need to compose the subset with the new view dimensions and new subset. The precondition to this method is that the array has unique strides (if not, the process fails). The process works in three steps, as follows:

  • First, The degenerate (shape=1) dimensions are removed from both the array and the view for consideration.

  • The mapping between non-degenerate dimensions is done from the view to the array based on the strides.

    Note that in a slice, the strides can be expanded or squeezed, but never reordered. This fact is used during matching. If any non-degenerate dimension remains in the view, the process fails.

  • Second, we find the “unsqueezed” dimensions by looking at the remainder of the view dimensions:

    any dimension that is between the dimensions in the existing mapping is considered for strides. Dimensions that fall before or after the sizes, or between two consecutive dimensions, are considered new axes.

  • Third, the remainder of the dimensions of the original (non-view) data descriptor are considered

    “squeezed”.

For example, a scalar view A[i, j] -> v would return ({}, [], [0, 1]). Example 2: A[0:2, 3:5, i, j, 0:N] -> V[0:2, 0, 0:2, 0, 0:N, 0] would return ({0: 0, 2: 1, 3: 2, 4: 4}, [1, 5], [3]). :type vdesc: View :param vdesc: The data descriptor of the view. :type adesc: Array :param adesc: The data descriptor of the viewed data container. :rtype: Optional[Tuple[Dict[int, int], List[int], List[int]]] :return: A tuple of (mapping of view->array, expanded, squeezed) dimensions, or None if the process failed.

dace.sdfg.utils.merge_maps(graph, outer_map_entry, outer_map_exit, inner_map_entry, inner_map_exit, param_merge=<function <lambda>>, range_merge=<function <lambda>>)

Merges two maps (their entries and exits). It is assumed that the operation is valid.

Return type:

Tuple[MapEntry, MapExit]

dace.sdfg.utils.node_path_graph(*args)

Generates a path graph passing through the input nodes.

The function generates a graph using as nodes the input arguments. Subsequently, it creates a path passing through all the nodes, in the same order as they were given in the function input.

Parameters:

args – Variable number of nodes or a list of nodes.

Return type:

OrderedDiGraph

Returns:

A directed graph based on the input arguments.

dace.sdfg.utils.nodes_in_all_simple_paths(G, source, target, condition=None)

Returns a set of nodes that appear in any of the paths from source to targets. Optionally, a condition can be given to control traversal.

Parameters:
  • G – The graph to traverse.

  • source – Source node.

  • targets

Note:

This algorithm uses a modified depth-first search, adapted from networkx.all_simple_paths.

Note:

The algorithm is written for directed graphs. For multigraphs, use networkx.all_simple_paths!

Return type:

Set[Any]

References: [1] R. Sedgewick, “Algorithms in C, Part 5: Graph Algorithms”, Addison Wesley Professional, 3rd ed., 2001.

dace.sdfg.utils.normalize_offsets(sdfg)

Normalizes descriptor offsets to 0 and adjusts the Memlet subsets accordingly. This operation is done in-place.

Parameters:

sdfg (SDFG) – The SDFG to be normalized.

dace.sdfg.utils.postdominators(sdfg, return_alldoms=False)

Return the immediate postdominators of an SDFG. This may require creating new nodes and removing them, which happens in-place on the SDFG.

Parameters:
  • sdfg (SDFG) – The SDFG to generate the postdominators from.

  • return_alldoms (bool) – If True, returns the “all postdominators” dictionary as well.

Return type:

Union[Dict[SDFGState, SDFGState], Tuple[Dict[SDFGState, SDFGState], Dict[SDFGState, Set[SDFGState]]], None]

Returns:

Immediate postdominators, or a 2-tuple of (ipostdom, allpostdoms) if return_alldoms is True.

dace.sdfg.utils.prune_symbols(sdfg)

Prunes unused symbols from the SDFG and the NestedSDFG symbol mappings. This operation is done in place. See also dace.transformation.interstate.PruneSymbols.

Parameters:

sdfg (SDFG) – The SDFG to have its symbols pruned.

dace.sdfg.utils.remove_edge_and_dangling_path(state, edge)

Removes an edge and all of its parent edges in a memlet path, cleaning dangling connectors and isolated nodes resulting from the removal.

Parameters:
dace.sdfg.utils.scope_aware_topological_sort(G, sources=None, condition=None, reverse=False, visited=None)

Traverses an SDFG state in topological order, yielding one node at a time, with the requirement that every scope (e.g., map) is traversed continuously. This means that the sort will start on the outer nodes, and as it encounters an entry node it will traverse the scope completely, without skipping out of it, until all nodes in the scope (and sub-scopes) have been visited.

Parameters:
  • G (SDFGState) – The state to traverse.

  • sources (Optional[Sequence[Node]]) – An optional sequence of nodes to start traversal from. If not given, all source (or sink) nodes will be used.

  • condition (Optional[Callable[[Node, Node], bool]]) – An optional callable that receives (current node, child node), and upon returning False, will stop traversal of the child node and its descendants.

  • reverse (bool) – If True, the graph will be traversed in reverse order (entering scopes via their exit node)

  • visited (Optional[Set[Node]]) – An optional set that will be filled with the visited nodes.

dace.sdfg.utils.separate_maps(state, dfg, schedule)

Separates the given ScopeSubgraphView into subgraphs with and without maps of the given schedule type. The function assumes that the given ScopeSubgraph view does not contain any concurrent segments (i.e. pass it through concurrent_subgraphs first). Only top level maps will be accounted for, if the desired schedule occurs in another (undesired) map, it will be ignored.

Returns a list with the subgraph views in order of the original DFG. ScopeSubgraphViews for the parts with maps, StateSubgraphViews for the parts without maps.

dace.sdfg.utils.trace_nested_access(node, state, sdfg)

Given an AccessNode in a nested SDFG, trace the accessed memory back to the outermost scope in which it is defined.

Parameters:
  • node (AccessNode) – An access node.

  • state (SDFGState) – State in which the access node is located.

  • sdfg (SDFG) – SDFG in which the access node is located.

Return type:

List[Tuple[AccessNode, SDFGState, SDFG]]

Returns:

A list of scopes ((input_node, output_node), (memlet_read, memlet_write), state, sdfg) in which the given data is accessed, from outermost scope to innermost scope.

dace.sdfg.utils.traverse_sdfg_with_defined_symbols(sdfg, recursive=False)

Traverses the SDFG, its states and nodes, yielding the defined symbols and their types at each node.

Return type:

Generator[Tuple[SDFGState, Node, Dict[str, typeclass]], None, None]

Returns:

A generator that yields tuples of (state, node in state, currently-defined symbols)

dace.sdfg.utils.unique_node_repr(graph, node)

Returns unique string representation of the given node, considering its placement into the SDFG graph. Useful for hashing, or building node-based dictionaries.

Parameters:
Return type:

str

Returns:

the unique representation

dace.sdfg.utils.weakly_connected_component(dfg, node_in_component)

Returns a subgraph of all nodes that form the weakly connected component in dfg that contains node_in_component.

Return type:

StateSubgraphView

dace.sdfg.validation module

Exception classes and methods for validation of SDFGs.

exception dace.sdfg.validation.InvalidSDFGEdgeError(message, sdfg, state_id, edge_id)

Bases: InvalidSDFGError

Exceptions of invalid edges in an SDFG state.

to_json()
exception dace.sdfg.validation.InvalidSDFGError(message, sdfg, state_id)

Bases: Exception

A class of exceptions thrown when SDFG validation fails.

to_json()
exception dace.sdfg.validation.InvalidSDFGInterstateEdgeError(message, sdfg, edge_id)

Bases: InvalidSDFGError

Exceptions of invalid inter-state edges in an SDFG.

to_json()
exception dace.sdfg.validation.InvalidSDFGNodeError(message, sdfg, state_id, node_id)

Bases: InvalidSDFGError

Exceptions of invalid nodes in an SDFG state.

to_json()
exception dace.sdfg.validation.NodeNotExpandedError(sdfg, state_id, node_id)

Bases: InvalidSDFGNodeError

Exception that is raised whenever a library node was not expanded before code generation.

dace.sdfg.validation.validate(graph)
dace.sdfg.validation.validate_control_flow_region(sdfg, region, initialized_transients, symbols, references=None, **context)
dace.sdfg.validation.validate_memlet_data(memlet_data, access_data)

Validates that the src/dst access node data matches the memlet data.

Parameters:
  • memlet_data (str) – The data of the memlet.

  • access_data (str) – The data of the access node.

Return type:

bool

Returns:

True if the memlet data matches the access node data.

dace.sdfg.validation.validate_sdfg(sdfg, references=None, **context)

Verifies the correctness of an SDFG by applying multiple tests.

Parameters:
  • sdfg (SDFG) – The SDFG to verify.

  • references (Optional[Set[int]]) – An optional set keeping seen IDs for object miscopy validation.

  • context (bool) – An optional dictionary of boolean attributes used to understand the context of this validation (e.g., is this in a GPU kernel).

Raises an InvalidSDFGError with the erroneous node/edge on failure.

dace.sdfg.validation.validate_state(state, state_id=None, sdfg=None, symbols=None, initialized_transients=None, references=None, **context)

Verifies the correctness of an SDFG state by applying multiple tests. Raises an InvalidSDFGError with the erroneous node on failure.

Module contents