Peano
Loading...
Searching...
No Matches
kernels.py
Go to the documentation of this file.
1import exahype2.api.dslhype2 as dslhype
2from exahype2.api import Solver, Target, OutputLanguage, MemoryLayout, PDETerm
3import os
4from enum import Enum
5
6def generate_namespace(output_language: OutputLanguage, target: Target, memory_layout: MemoryLayout):
7 if output_language == OutputLanguage.MLIR:
8 function_namespace = ["mlir"]
9 else:
10 function_namespace = ["cpp"]
11
12 if memory_layout == MemoryLayout.AoS_AllNested:
13 function_namespace.append("nested")
14 elif memory_layout == MemoryLayout.AoS_CellDataNested_TemporariesFlattened:
15 function_namespace.append("cell_data_nested_temporaries_flattened")
16 elif memory_layout == MemoryLayout.AoS_CellDataFlattened_TemporariesNested:
17 function_namespace.append("cell_data_flattened_temporaries_nested")
18 else:
19 function_namespace.append("flattened")
20
21 return function_namespace
22
24 solver: Solver,
25 function,
26 dimensions: int,
27 function_map: dict[dslhype.Name, dslhype.TFunction],
28 external_variables,
29 pde_terms: list[PDETerm],
30 output_file_name: str,
31 target: Target,
32 stateless: bool,
33 output_language: OutputLanguage = OutputLanguage.CPP,
34 memory_layout: MemoryLayout = MemoryLayout.AoS_AllNested,
35 function_name: str | None = None,
36 output_directory: str = ".",
37):
38 """!
39 function_name: str
40 Name of the generated C++ function. Defaults to the name of the
41 Python DSL function passed in as function.
42
43 output_language: OutputLanguage
44 Language of the generated code. Defaults to C++, but can be MLIR.
45
46 output_directory: str
47 Directory the kernels/ subdirectory with the generated files is
48 created in, usually the Peano project's directory.
49
50 @remark Existing files are appended to, not overwritten
51 Several functions of one project end up in the same files
52 (kernels/{output_file_name}.h and .cpph/.cpp), so the translation appends.
53 Running a generator script a second time in the same directory therefore
54 duplicates the kernels, and the project does not compile
55 ("redefinition of ..."). Remove the kernels/ directory before you
56 regenerate.
57 @todo The generators should write every function into a file of its
58 own (and a thin header that includes them). Then each file can simply
59 be overwritten, and regenerating in place becomes safe.
60 """
61 if target == Target.Accelerator and stateless == False:
62 raise Exception("Accelerated kernels must be stateless")
63 if target == Target.Accelerator and memory_layout != MemoryLayout.AoS_AllFlattened:
64 raise Exception("Accelerated kernels must use flattened memory layout for all data")
65
66 reduced_functor_parameters: list[dslhype.Argument] = []
67 for functor_name, functor_type in function_map.items():
68 function_in_pde_terms = False
69 for pde_term in pde_terms:
70 if pde_term.NAME == functor_name.id:
71 function_in_pde_terms = True
72 if function_in_pde_terms:
73 reduced_functor_parameters.append(dslhype.Argument(functor_name, functor_type))
74
75 if memory_layout == MemoryLayout.AoS_AllFlattened or memory_layout == MemoryLayout.AoS_CellDataNested_TemporariesFlattened:
76 dslhype.TArray.flatten_temporaries = True
77 else:
78 dslhype.TArray.flatten_temporaries = False
79 # Name the type according to the C++ type, since MLIR uses !llvm.ptr for structs
80 # Add fields in the order specified by the MLIR type since only MLIR needs this information
81 if output_language == OutputLanguage.MLIR:
82 if memory_layout == MemoryLayout.AoS_CellDataFlattened_TemporariesNested or memory_layout == MemoryLayout.AoS_AllFlattened:
83 cell_data_type = dslhype.TStruct("::exahype2::MLIRCellDataFlattened&")
84 else:
85 cell_data_type = dslhype.TStruct("::exahype2::MLIRCellDataNested&")
86 elif target == Target.Accelerator:
87 cell_data_type = dslhype.TStruct("::exahype2::CopyCellDataGPU<double, double>&")
88 elif memory_layout == MemoryLayout.AoS_CellDataFlattened_TemporariesNested or memory_layout == MemoryLayout.AoS_AllFlattened:
89 cell_data_type = dslhype.TStruct("::exahype2::CellDataFlattened<double, double>&")
90 else:
91 cell_data_type = dslhype.TStruct("::exahype2::CellData<double, double>&")
92
93 if memory_layout == MemoryLayout.AoS_AllNested or memory_layout == MemoryLayout.AoS_CellDataNested_TemporariesFlattened:
94 cell_data_type.add_field("QIn", dslhype.TDataBlock(2, dslhype.TFloat(), flatten_array=False))
95 cell_data_type.add_field("QOut", dslhype.TDataBlock(2, dslhype.TFloat(), flatten_array=False))
96 else:
97 cell_data_type.add_field("QIn", dslhype.TDataBlock(2, dslhype.TFloat(), flatten_array=True))
98 cell_data_type.add_field("QOut", dslhype.TDataBlock(2, dslhype.TFloat(), flatten_array=True))
99
100 cell_data_type.add_field("cellCentre", dslhype.TDataBlock(1, dslhype.TVector(dslhype.TFloat(), dimensions), flatten_array=False))
101 cell_data_type.add_field("cellSize", dslhype.TDataBlock(1, dslhype.TVector(dslhype.TFloat(), dimensions), flatten_array=False))
102 cell_data_type.add_field("t", dslhype.TArray(dslhype.TFloat(), 1))
103 cell_data_type.add_field("dt", dslhype.TArray(dslhype.TFloat(), 1))
104 #cell_data_type.add_field("id", dslhype.TArray(dslhype.TInteger(), 1))
105 cell_data_type.add_field("maxEigenvalue", dslhype.TArray(dslhype.TFloat(), 1))
106 cell_data_type.add_field("numberOfCells", dslhype.TInteger())
107
108 #nested_cpu_cell_data_type = dslhype.TStruct("::exahype2::CellData<double, double>&")
109 #nested_cpu_cell_data_type.add_field("QIn", dslhype.TDataBlock(2, dslhype.TFloat(), flatten_array=False))
110 #nested_cpu_cell_data_type.add_field("QOut", dslhype.TDataBlock(2, dslhype.TFloat(), flatten_array=False))
111 #nested_cpu_cell_data_type.add_field("cellCentre", dslhype.TDataBlock(1, dslhype.TVector(dslhype.TFloat(), dimensions), flatten_array=False))
112 #nested_cpu_cell_data_type.add_field("cellSize", dslhype.TDataBlock(1, dslhype.TVector(dslhype.TFloat(), dimensions), flatten_array=False))
113 #nested_cpu_cell_data_type.add_field("t", dslhype.TArray(dslhype.TFloat(), 1))
114 #nested_cpu_cell_data_type.add_field("dt", dslhype.TArray(dslhype.TFloat(), 1))
115 #nested_cpu_cell_data_type.add_field("id", dslhype.TArray(dslhype.TInteger(), 1))
116 #nested_cpu_cell_data_type.add_field("maxEigenvalue", dslhype.TArray(dslhype.TFloat(), 1))
117 #nested_cpu_cell_data_type.add_field("numberOfCells", dslhype.TInteger())
118
119 #gpu_cell_data_type = dslhype.TStruct("::exahype2::CopyCellDataGPU<double, double>&")
120 #gpu_cell_data_type.add_field("QIn", dslhype.TDataBlock(2, dslhype.TFloat(), flatten_array=True))
121 #gpu_cell_data_type.add_field("QOut", dslhype.TDataBlock(2, dslhype.TFloat(), flatten_array=True))
122 #gpu_cell_data_type.add_field("cellCentre", dslhype.TDataBlock(1, dslhype.TVector(dslhype.TFloat(), dimensions), flatten_array=False))
123 #gpu_cell_data_type.add_field("cellSize", dslhype.TDataBlock(1, dslhype.TVector(dslhype.TFloat(), dimensions), flatten_array=False))
124 #gpu_cell_data_type.add_field("t", dslhype.TArray(dslhype.TFloat(), 1))
125 #gpu_cell_data_type.add_field("dt", dslhype.TArray(dslhype.TFloat(), 1))
126 #gpu_cell_data_type.add_field("id", dslhype.TArray(dslhype.TInteger(), 1))
127 #gpu_cell_data_type.add_field("maxEigenvalue", dslhype.TArray(dslhype.TFloat(), 1))
128 #gpu_cell_data_type.add_field("numberOfCells", dslhype.TInteger())
129
130 #mlir_cell_data_type = dslhype.TStruct("::exahype2::MLIRCellDataFlattened&")
131 #mlir_cell_data_type.add_field("QIn", dslhype.TDataBlock(2, dslhype.TFloat(), flatten_array=True))
132 #mlir_cell_data_type.add_field("QOut", dslhype.TDataBlock(2, dslhype.TFloat(), flatten_array=True))
133 #mlir_cell_data_type.add_field("cellCentre", dslhype.TDataBlock(1, dslhype.TVector(dslhype.TFloat(), dimensions), flatten_array=True))
134 #mlir_cell_data_type.add_field("cellSize", dslhype.TDataBlock(1, dslhype.TVector(dslhype.TFloat(), dimensions), flatten_array=True))
135 #mlir_cell_data_type.add_field("numberOfCells", dslhype.TInteger())
136
137 cpp_printer = dslhype.CPPPrinter(4)
138
139
140 if output_language == OutputLanguage.CPP:
141 if target == Target.Accelerator:
142 printer = dslhype.OMPTargetPrinter(4)
143 #dslhype.TArray.flatten_temporaries = True
144 arguments = [
146 dslhype.Argument(dslhype.Name("patchData"), cell_data_type)
147 ]
148 else:
149 printer = dslhype.CPPPrinter(4)
150 #dslhype.TArray.flatten_temporaries = False
151 arguments = [
152 dslhype.Argument(dslhype.Name("patchData"), cell_data_type)
153 ]
154 elif output_language == OutputLanguage.MLIR:
155 printer = dslhype.MLIRPrinter(4, internal_name=function_name + ("_stateless" if stateless else "") + "_" +memory_layout.name.lower())
156 if target == Target.Accelerator:
157 raise Exception("MLIR output is not supported for the accelerator target yet")
158 else:
159 arguments = [
160 dslhype.Argument(dslhype.Name("patchData"), cell_data_type)
161 ]
162
163
164 if not stateless and output_language == OutputLanguage.CPP:
165 arguments.extend(reduced_functor_parameters)
166
167 function_namespace = solver.numerical_scheme.kernel_namespace + generate_namespace(output_language, target, memory_layout)
168
169 parser = dslhype.Parser()
170 function = parser.parse(function, function_id=function_name + ("Stateless" if stateless else ""), function_namespace=function_namespace, function_arguments=arguments, function_map=function_map, external_variables=external_variables, enabled_pde_terms=pde_terms, stateless=stateless)
171
172
173 function_declaration = function.print_declaration(printer)
174 function_definition = function.print_definition(printer)
175 function_declaration_with_timer = function.print_declaration_with_timer(printer)
176 function_definition_with_timer = function.print_definition_with_timer(printer)
177
178 if output_language == OutputLanguage.CPP:
179 kernels_directory = os.path.join(output_directory, "kernels")
180 os.makedirs(kernels_directory, exist_ok=True)
181 file = open(os.path.join(kernels_directory, f"{output_file_name}.h"), "a")
182 file.write(function_declaration)
183 file.write(function_declaration_with_timer)
184
185 if stateless == True:
186 file = open(os.path.join(kernels_directory, f"{output_file_name}.cpph"), "a")
187 else:
188 file = open(os.path.join(kernels_directory, f"{output_file_name}.cpp"), "a")
189
190 file.write(function_definition)
191 file.write(function_definition_with_timer)
192 file.close()
193
194 elif output_language == OutputLanguage.MLIR:
195 function_bridge = printer.print_function_bridge(function)
196
197 kernels_directory = os.path.join(output_directory, "kernels")
198 os.makedirs(kernels_directory, exist_ok=True)
199
200 file = open(os.path.join(kernels_directory, f"{output_file_name}.h"), "a")
201 file.write(function_declaration)
202 file.write(function_declaration_with_timer)
203 file.close()
204
205 file = open(os.path.join(kernels_directory, f"{output_file_name}_{memory_layout.name.lower()}.mlir"), "w")
206 file.write(function_definition)
207 file.close()
208
209 file = open(os.path.join(kernels_directory, f"{output_file_name}.cpp"), "a")
210 file.write(function_bridge)
211 file.write(function_definition_with_timer)
212 file.close()
213
214
215def generate_mlir_function_call_bridges(solver: Solver, function_map: dict[dslhype.Name, dslhype.TFunction], pde_terms: list[PDETerm], stateless: bool, output_file_name: str, output_directory: str = "."):
216 cpp_printer = dslhype.CPPPrinter(4)
217 reduced_functor_parameters: list[dslhype.Argument] = []
218 for functor_name, functor_type in function_map.items():
219 function_in_pde_terms = False
220 for pde_term in pde_terms:
221 if pde_term.NAME == functor_name.id:
222 function_in_pde_terms = True
223 if function_in_pde_terms:
224 reduced_functor_parameters.append(dslhype.Argument(functor_name, functor_type))
225 # Generate PDE function calls
226 fully_qualified_solver_name = "::".join(solver.numerical_scheme.kernel_namespace + [f"Abstract{solver.name}"])
227
228 term_definitions = """#include <cstdint>
229extern "C" {
230"""
231 for pde_term_parameter in reduced_functor_parameters:
232 pde_term_name = pde_term_parameter.name
233 pde_term_type = pde_term_parameter.type
234 assert(isinstance(pde_term_type, dslhype.TFunction))
235 term_prints: list[str] = []
236 type_casts = []
237 for parameter_name, parameter_type in pde_term_type.argument_types.items():
238 if isinstance(parameter_type, dslhype.TArray):
239 element_type = parameter_type.element_type.print(cpp_printer)
240 term_prints.extend([
241 f"{element_type}* {parameter_name.id}_allocated",
242 f"{element_type}* {parameter_name.id}_aligned",
243 f"std::int64_t {parameter_name.id}_offset",
244 f"std::int64_t {parameter_name.id}_size",
245 f"std::int64_t {parameter_name.id}_stride",
246 ])
247 type_casts.append(
248 f"{element_type}* {parameter_name.id} = "
249 f"{parameter_name.id}_aligned + {parameter_name.id}_offset;"
250 )
251 elif isinstance(parameter_type, dslhype.TVector):
252 element_type = parameter_type.base_type.print(cpp_printer)
253 term_prints.extend([
254 f"{element_type}* {parameter_name.id}_allocated",
255 f"{element_type}* {parameter_name.id}_aligned",
256 f"std::int64_t {parameter_name.id}_offset",
257 f"std::int64_t {parameter_name.id}_size",
258 f"std::int64_t {parameter_name.id}_stride",
259 ])
260 type_casts.append(
261 f"tarch::la::Vector<{parameter_type.dimensions},{element_type}> "
262 f"{parameter_name.id} = "
263 f"{parameter_name.id}_aligned + {parameter_name.id}_offset;"
264 )
265 else:
266 term_prints.append(f"{parameter_type.print(cpp_printer)} {parameter_name.id}")
267
268 argument_prints = [argument.print(cpp_printer) for argument in pde_term_type.argument_types.keys()]
269
270 if stateless:
271 function_call = f"{fully_qualified_solver_name}::{pde_term_name.id}({", ".join(argument_prints)}, ::exahype2::Solver::Offloadable::Yes);"
272 else:
273 function_call = f"{"::".join(solver.numerical_scheme.kernel_namespace + ["repositories"])}::{solver.get_name_of_global_instance()}.{pde_term_name.id}({", ".join(argument_prints)});"
274 term_definitions += f"""void {pde_term_name.id}{"Stateless" if stateless else ""}({", ".join(term_prints)}){{
275{os.linesep.join(type_casts)}
276{function_call}
277}}
278"""
279 term_definitions += "}"
280
281 kernels_directory = os.path.join(output_directory, "kernels")
282 os.makedirs(kernels_directory, exist_ok=True)
283 file = open(os.path.join(kernels_directory, f"{output_file_name}.cpp"), "a")
284 file.write(term_definitions)
285 file.close()
#define assert(...)
Definition LinuxAMD.h:28
generate_mlir_function_call_bridges(Solver solver, dict[dslhype.Name, dslhype.TFunction] function_map, list[PDETerm] pde_terms, bool stateless, str output_file_name, str output_directory=".")
Definition kernels.py:215
generate_namespace(OutputLanguage output_language, Target target, MemoryLayout memory_layout)
Definition kernels.py:6
translate_dslhype_function(Solver solver, function, int dimensions, dict[dslhype.Name, dslhype.TFunction] function_map, external_variables, list[PDETerm] pde_terms, str output_file_name, Target target, bool stateless, OutputLanguage output_language=OutputLanguage.CPP, MemoryLayout memory_layout=MemoryLayout.AoS_AllNested, str|None function_name=None, str output_directory=".")
function_name: str Name of the generated C++ function.
Definition kernels.py:37