17 peano_project:
"peano4.api.Project",
18 non_fusable_task_pairs: Optional[List[Tuple[Task, Task]]] =
None,
19) -> List[
"peano4.api.solversteps.Step"]:
22 Task graph compiler which fuses tasks into as few mesh traversals as possible
24 You can use this task graph compiler in your ExaHyPE 2 project through
26 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
27 project.compiler = peano4.api.taskgraph.compiler.FuseSteps.translate
28 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
30 Where peano4.api.taskgraph.compiler.Sequential.translate() maps every
31 task onto a mesh traversal (Observer) of its own, this compiler packs
32 several tasks into one traversal whenever this is safe.
34 ## When can two tasks be fused?
36 Two tasks end up in the same traversal if and only if all of the
37 following constraints hold:
39 1. **Entity order.** Each grid sweep first does something with the
40 vertices, then with the faces, then with the cells (@ref
41 peano4.api.taskgraph.Task.Task.GridEntity, whose values follow exactly this order). A task that
42 works on a face can therefore be followed by a task working on a face
43 or a cell within the same traversal, but a task working on a vertex
44 has to go into the next traversal. In general, a node can be appended
45 to the traversal built up so far if and only if the lowest grid
46 entity it works on is not lower than the highest grid entity the
47 traversal works on so far. Tasks of one dependency layer (see
48 below) are independent of each other, so this constraint does not
50 2. **No conflicting face or vertex data.** A face or a vertex is shared
51 between several cells. If one task of a traversal writes a face or
52 vertex submodel (WRITE or READ_AND_WRITE) while another task of the
53 same traversal reads or writes the very same submodel, a cell might
54 see the submodel before or after a neighbouring cell has already
55 altered it, depending on the traversal order. Such tasks are never
56 fused (@ref peano4.api.taskgraph.compiler.FuseSteps._have_conflicting_data()). Cell data are not shared
57 between cells and hence do not constrain the fusion. TEMPORARY uses
58 are ignored. There is one exception which follows from the entity
59 order: Peano touches every vertex and face of a cell for the first
60 time before it enters the cell, and every vertex of a face before the
61 face. A FACE task which reads or writes face data therefore has
62 finished with a face before any subsequent face or cell task of the
63 same traversal sees this face. The same holds for a VERTEX task and
64 vertex data. A conflict on face (vertex) data hence is ignored if the
65 earlier of the two tasks is a FACE (VERTEX) task. Two FACE tasks with
66 conflicting face data thus can share one traversal, but they never
67 run in parallel (constraint 2 of the algorithm below). Apart from
68 this exception, the constraint is conservative: it relies only on
69 the Task.DataAccess qualifiers and the tasks' grid entities, and does
70 not know that a cell task might for example write the face data only
71 when it touches a face for the last time.
72 3. **No repetition.** Tasks which have to repeat (Task.has_to_repeat)
73 are never fused. They always yield a traversal of their own.
74 4. **No annotation.** The caller can annotate the fusion through
75 non_fusable_task_pairs: two tasks forming such a pair never end up
76 in the same traversal.
77 5. **Global tasks.** A GLOBAL task (@ref peano4.api.taskgraph.Task.Task.GridEntity)
78 does not touch any mesh entity. It does not take part in the
79 algorithm below. Instead, it is appended to the traversal holding
80 its last dependency, even if this traversal repeats. A GLOBAL task
81 without dependencies goes into the very last traversal. Other tasks
82 may depend on a GLOBAL task. As it acts in prepareTraversal() and
83 unprepareTraversal() of the traversal that it is appended to, such a
84 task never shares a traversal with a task that it depends on: it
85 starts a traversal of its own.
86 6. **Start and end of the step.** GLOBAL_START_OF_STEP and
87 GLOBAL_END_OF_STEP tasks do not take part in the algorithm below,
88 either, and they never yield a traversal of their own.
89 The action sets of the former are the first ones of the first
90 traversal, those of the latter are the last ones of the last
91 traversal, behind the other GLOBAL tasks. Among the end-of-step tasks,
92 the dependencies decide the order. Why: The tasks act in
93 prepareTraversal() and unprepareTraversal() only, i.e. they have to be
94 the first and last thing that happens to the mesh in a step, and
95 fusing them into the existing traversals saves a mesh sweep. A start
96 task may not depend on any task. An end-of-step task which no task
97 depends on runs when everything else has finished. If another task
98 depends on an end-of-step task (@ref peano4.api.taskgraph.Graph.Graph.anchored_end_of_step_tasks()),
99 it cannot run at the very end. It is treated like a GLOBAL task
100 instead, i.e. it is appended to the traversal holding its last
101 dependency, and the dependent tasks start a traversal of their own
102 (constraint 5). If the first (last) traversal repeats,
103 the compiler places the tasks into a traversal of their own in front
104 of (behind) it, as they would otherwise run in every repetition.
107<div style="background-color: #fcc ; padding: 10px; border: 1px solid green;">
108A task does not tell the compiler if its action sets plug into touch-first or touch-last
109events. The compiler therefore assumes that a VERTEX (FACE) task works on its vertex
110(face) data within touchVertexFirstTime() (touchFaceFirstTime()), i.e. before any
111adjacent face or cell is entered. A VERTEX or FACE task which writes its data in
112touchVertexLastTime() or touchFaceLastTime() violates this assumption, and the
113compiler might fuse it with a subsequent task that then reads stale data. Conversely,
114a CELL task A might only write face data in touchFaceLastTime(), while its successor
115CELL task B reads this face data in touchCellFirstTime(). We could fuse A and B, but
116this option is hidden from the task compiler.
122 1. Split the graph into layers by dependency depth (a task without
123 dependencies has depth 0, every other task 1 + the deepest of its
124 dependencies - the same notion of depth Graph.visualise() uses).
125 Tasks within one layer can never depend on one another, i.e. they
126 can run in parallel. Within a layer, tasks keep the order in which
127 Graph.ordered_tasks() lists them.
128 2. The tasks of one layer are combined into intermediate nodes. A
129 repeating task forms a node of its own, placed in front of the
130 layer's remaining nodes. The remaining tasks are added one by one to
131 the layer's current node unless they have conflicting data with it
132 or form a non-fusable pair with one of its tasks (constraint 4). In
133 this case, they start a new node. Different to constraint 2, cell
134 data counts as conflicting data here, too: Tasks of one node may be
135 invoked concurrently on the same cell, i.e. they must not write
136 cell data which another task of the node reads or writes. A node
137 might work on several grid entities. A node is parallel if it holds
138 more than one task and each of these tasks holds exactly one action
139 set (@ref peano4.api.taskgraph.compiler.FuseSteps._is_parallel_node()).
140 The action sets of a parallel node are labelled as parallel (@ref
141 peano4.api.solversteps.ActionSet.ActionSet.parallel), i.e. they may
142 be invoked concurrently. All other action sets are labelled as not
143 parallel. A task with several action sets never is part of a
144 parallel node: Its action sets have to be invoked one after the
145 other, and the parallel flags of individual action sets can not
146 express that a sequence of action sets runs in parallel to another
148 3. The resulting sequence of nodes is fused greedily into traversals:
149 a node is appended to the current traversal if constraints 1 to 4
150 hold for the node and all tasks already in the traversal. Otherwise,
151 it starts a new traversal. The fusion never reorders nodes and never
156 The illustrations below are generated by
157 src/peano4/api/taskgraph/compiler/fuse-steps-illustrations.py. Each
158 shows the input task graph on top and the compiled sequence of
159 traversals underneath.
163 A chain of tasks working on a vertex, a face, a cell, a vertex and a
164 cell. The vertex, face and cell tasks are fused into one traversal.
165 The second vertex task has to start a new traversal, which also takes
166 the subsequent cell task.
168 @image html fuse-steps-entity-order.png
172 Two independent vertex tasks form one layer and hence one parallel
173 node. They are fused with the two independent cell tasks of the
174 subsequent layer. Action sets which may run in parallel share a number
175 and are told apart by letters, e.g. 1.a and 1.b.
177 @image html fuse-steps-parallel.png
179 ### Conflicting face data
181 The time step of an ExaHyPE 2 Finite Volume solver: the reconstruction
182 reads the face data that the projection eventually writes. Therefore,
183 the projection cannot be fused with the reconstruction and the update,
184 and starts a traversal of its own.
186 @image html fuse-steps-data-conflict.png
188 ### Face task before cell task
190 A FACE task sets boundary data on the faces, which the subsequent
191 reconstruction reads. As the face task is done with a face before
192 either adjacent cell is entered, all three tasks share one traversal
193 even though the first two share face data.
195 @image html fuse-steps-face-before-cell.png
197 ## Constructing the fused step
199 A fused step's name concatenates the names of its tasks, prefixed with
200 identifier. Its action sets are the tasks' action sets one after the
201 other, so the evaluation order of the tasks is preserved. We do not use
202 peano4.api.solversteps.Step.add_action_set() for this, as it reorders
203 the action sets according to their descend_invocation_order: a
204 reconstruction with a higher descend_invocation_order would then
205 overtake the update of the subsequent task. The descend_invocation_order
206 is applied (stably) only among the action sets of one task.
208 The generated observer spawns consecutive action sets which are labelled
209 as parallel as one task group
210 (@ref peano4.api.solversteps.SynchroniseActionSets.get_task_groups()).
211 If two parallel nodes follow each other directly within a step, their
212 groups would merge. We therefore insert a
213 @ref peano4.api.solversteps.SynchroniseActionSets.SynchroniseActionSets
214 between them - @ref peano4.api.taskgraph.compiler.FuseSteps._create_step().
216 A submodel used by several tasks of a fused step is declared once on
217 the step. Its qualifier is merged from the tasks' qualifiers: TEMPORARY
218 uses are ignored, the step loads the submodel if the first remaining
219 use reads it, and stores it if the last remaining use writes it -
220 @ref peano4.api.taskgraph.compiler.FuseSteps._merge_data_access().
222 propagate_use_statements() is not invoked here. It is a postprocessing
223 step called outside of the translation.
225 @param graph: peano4.api.taskgraph.Graph
226 The task graph to compile. Assumed to be acyclic.
228 @param identifier: str
229 Identifies which of the surrounding project's algorithmic phases this
230 graph belongs to (e.g. "SetupSimulation", "TimeStep", "Plot") and
231 prefixes every generated Observer's name.
233 @param peano_project: peano4.api.Project
234 Not used by this compiler. @ref peano4.api.taskgraph.compiler
236 @param non_fusable_task_pairs: [(peano4.api.taskgraph.Task, peano4.api.taskgraph.Task)]
237 Pairs of tasks of graph which must not end up in the same traversal.
238 The order within a pair does not matter. Defaults to none.
240 @return [peano4.api.solversteps.Step]
241 One Observer per fused group of tasks, in an order that respects
246 for first_task, second_task
in non_fusable_task_pairs
or []:
247 non_fusable.add((first_task, second_task))
248 non_fusable.add((second_task, first_task))
251 tasks: List[Task], further_tasks: List[Task], include_cell_data: bool =
False, respect_entity_order: bool =
False
253 """Constraints 2 and 4 between two lists of tasks, optionally taking cell data and the entity order into account"""
254 return not _have_conflicting_data(tasks, further_tasks, include_cell_data, respect_entity_order)
and not any(
255 (task, further_task)
in non_fusable
for task
in tasks
for further_task
in further_tasks
259 all_tasks = graph.ordered_tasks()
260 start_tasks = [task
for task
in all_tasks
if task.entity == Entity.GLOBAL_START_OF_STEP]
261 anchored_end_tasks = graph.anchored_end_of_step_tasks()
264 task
for task
in all_tasks
if task.entity == Entity.GLOBAL_END_OF_STEP
and task
not in anchored_end_tasks
268 task
for task
in all_tasks
if task.entity == Entity.GLOBAL
or task
in anchored_end_tasks
270 order = [task
for task
in all_tasks
if not task.entity.is_global]
271 for task
in start_tasks:
272 assert not task.dependencies, f
"Task {task.name} is GLOBAL_START_OF_STEP and hence may not depend on any task"
274 def depends_on_traversal_of(global_task: Task, tasks: List[Task]) -> bool:
275 """Does global_task end up in a traversal which holds one of the tasks, i.e. does it depend on one of them?"""
277 dependency
in tasks
or (dependency
in global_tasks
and depends_on_traversal_of(dependency, tasks))
278 for dependency
in global_task.dependencies
283 def depth(task: Task) -> int:
285 dependencies = [dependency
for dependency
in task.dependencies
if dependency
not in start_tasks]
286 if task
not in depth_of_task:
287 depth_of_task[task] = 0
if not dependencies
else 1 + max(depth(dependency)
for dependency
in dependencies)
288 return depth_of_task[task]
292 layers.setdefault(depth(task), []).append(task)
296 for layer
in sorted(layers.keys()):
297 tasks_in_layer = layers[layer]
298 for task
in tasks_in_layer:
299 if task.has_to_repeat:
302 for task
in tasks_in_layer:
303 if task.has_to_repeat:
305 if nodes_of_layer
and can_be_combined(nodes_of_layer[-1], [task], include_cell_data=
True):
306 nodes_of_layer[-1].append(task)
308 nodes_of_layer.append([task])
309 for node
in nodes_of_layer:
311 for action_set
in task.action_sets:
313 nodes += nodes_of_layer
318 highest_entity_of_current_group =
None
320 lowest_entity = min(task.entity.value
for task
in node)
321 highest_entity = max(task.entity.value
for task
in node)
322 is_repeating = len(node) == 1
and node[0].has_to_repeat
323 tasks_of_current_group = [task
for group_node
in current_group
or []
for task
in group_node]
325 waits_for_current_group = any(
326 depends_on_traversal_of(dependency, tasks_of_current_group)
328 for dependency
in task.dependencies
329 if dependency
in global_tasks
333 and current_group
is not None
334 and not waits_for_current_group
335 and lowest_entity >= highest_entity_of_current_group
336 and can_be_combined(tasks_of_current_group, node, respect_entity_order=
True)
338 current_group.append(node)
339 highest_entity_of_current_group = max(highest_entity_of_current_group, highest_entity)
341 current_group = [node]
342 highest_entity_of_current_group = highest_entity
343 groups.append(current_group)
348 for global_task
in global_tasks:
349 groups_with_dependency = [
351 for index, group
in enumerate(groups)
352 if any(dependency
in node
for node
in group
for dependency
in global_task.dependencies)
354 if groups_with_dependency:
355 groups[max(groups_with_dependency)].append([global_task])
357 groups[-1].append([global_task])
359 groups.append([[global_task]])
363 return any(task.has_to_repeat
for node
in group
for task
in node)
366 if not groups
or repeats(groups[0]):
368 groups[0] = [[task]
for task
in start_tasks] + groups[0]
370 if not groups
or repeats(groups[-1]):
372 groups[-1] += [[task]
for task
in end_tasks]
374 steps = [
_create_step(group, identifier)
for group
in groups]
377 report_compiled_step_sequence(steps, title=f
"Compiled task graph for {identifier}")
384 further_tasks: List[Task],
385 include_cell_data: bool =
False,
386 respect_entity_order: bool =
False,
390 Check whether two sets of tasks can not share one mesh traversal due to
391 their face or vertex data, or can not run in parallel
393 True if one of the tasks writes a face or vertex submodel (WRITE or
394 READ_AND_WRITE) which one of the further_tasks reads or writes
395 (READ_AND_DISCARD, WRITE or READ_AND_WRITE), or vice versa. TEMPORARY
396 uses are ignored. @ref peano4.api.taskgraph.compiler.FuseSteps.translate()
398 @param include_cell_data: bool
399 If False, cell data is ignored. This is the check whether tasks can
400 share one mesh traversal. If True, conflicting cell data counts,
401 too. This is the check whether tasks can run in parallel.
403 @param respect_entity_order: bool
404 If True, tasks precede further_tasks within one traversal, and a
405 conflict on a face (vertex) submodel is ignored if the involved task
406 of tasks is a FACE (VERTEX) task: Such a task has finished with a
407 face (vertex) before any subsequent task sees it. This is the
408 exception of constraint 2 in
409 @ref peano4.api.taskgraph.compiler.FuseSteps.translate(). If False,
410 tasks and further_tasks are treated symmetrically.
413 writing_accesses = (Task.DataAccess.WRITE, Task.DataAccess.READ_AND_WRITE)
414 using_accesses = (Task.DataAccess.READ_AND_DISCARD, Task.DataAccess.WRITE, Task.DataAccess.READ_AND_WRITE)
415 entity_of_kind = {
"face": Task.GridEntity.FACE,
"vertex": Task.GridEntity.VERTEX}
417 def submodels(task, accesses):
420 for kind, access_of_submodel
in (
421 ((
"cell", task.cell_data_access),)
if include_cell_data
else ()
422 ) + ((
"face", task.face_data_access), (
"vertex", task.vertex_data_access))
423 for submodel, access
in access_of_submodel.items()
424 if access
in accesses
428 for further_task
in further_tasks:
429 conflicts = (submodels(task, writing_accesses) & submodels(further_task, using_accesses)) | (
430 submodels(further_task, writing_accesses) & submodels(task, using_accesses)
432 if respect_entity_order:
433 conflicts = {(kind, submodel)
for kind, submodel
in conflicts
if entity_of_kind.get(kind) != task.entity}
457 Merge the qualifiers several fused tasks attach to one submodel into one
459 TEMPORARY uses are ignored. The fused step has to load the submodel if
460 the first remaining use reads it (READ_AND_DISCARD or READ_AND_WRITE),
461 and it has to store the submodel if the last remaining use writes it
462 (WRITE or READ_AND_WRITE):
464 | load | store | merged qualifier |
465 |------|-------|------------------|
466 | yes | yes | READ_AND_WRITE |
467 | yes | no | READ_AND_DISCARD |
469 | no | no | TEMPORARY |
471 A submodel produced by one fused task and consumed by a later one
472 (WRITE followed by READ_AND_DISCARD) hence becomes TEMPORARY. For a
473 single access, the merged qualifier equals the access itself.
476 relevant_accesses = [access
for access
in accesses
if access != Task.DataAccess.TEMPORARY]
477 if not relevant_accesses:
478 return Task.DataAccess.TEMPORARY
479 load = relevant_accesses[0]
in (Task.DataAccess.READ_AND_DISCARD, Task.DataAccess.READ_AND_WRITE)
480 store = relevant_accesses[-1]
in (Task.DataAccess.WRITE, Task.DataAccess.READ_AND_WRITE)
482 return Task.DataAccess.READ_AND_WRITE
484 return Task.DataAccess.READ_AND_DISCARD
486 return Task.DataAccess.WRITE
487 return Task.DataAccess.TEMPORARY
490def _create_step(nodes: List[List[Task]], identifier: str) ->
"peano4.api.solversteps.Step":
493 Create one step from a group of fused nodes. @ref peano4.api.taskgraph.compiler.FuseSteps.translate()
495 Every node is a list of tasks: either a single task, or several tasks
496 from one layer of the task graph which can run in parallel.
498 Whenever a parallel node directly follows another parallel node, we
500 @ref peano4.api.solversteps.SynchroniseActionSets.SynchroniseActionSets,
501 so the two nodes yield two task groups rather than one.
504 tasks = [task
for node
in nodes
for task
in node]
506 name=f
"{identifier}_" +
"__".join(
_task_name(task)
for task
in tasks),
507 add_user_defined_actions=
False,
511 repeating_tasks = [task
for task
in tasks
if task.has_to_repeat]
512 assert len(repeating_tasks) <= 1
513 step.has_to_repeat = repeating_tasks[0].has_to_repeat
if repeating_tasks
else None
515 for data_attribute, access_attribute, step_access, use
in (
516 (
"cell_data",
"cell_data_access", step.cell_data_access, step.use_cell),
517 (
"face_data",
"face_data_access", step.face_data_access, step.use_face),
518 (
"vertex_data",
"vertex_data_access", step.vertex_data_access, step.use_vertex),
520 accesses_of_submodel = {}
522 for submodel
in getattr(task, data_attribute):
523 accesses_of_submodel.setdefault(submodel, []).append(getattr(task, access_attribute)[submodel])
524 for submodel, accesses
in accesses_of_submodel.items():
528 previous_node_is_parallel =
False
531 if node_is_parallel
and previous_node_is_parallel:
534 for action_set
in sorted(task.action_sets, key=
lambda action_set: action_set.descend_invocation_order):
535 step.action_sets.append(action_set)
536 previous_node_is_parallel = node_is_parallel