Debian Codegraph @

loki/transformations/temporaries/tests/test_hoist_variables.py

raw
1 # (C) Copyright 2018- ECMWF.
2 # This software is licensed under the terms of the Apache Licence Version 2.0
3 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 # In applying this licence, ECMWF does not waive the privileges and immunities
5 # granted to it by virtue of its status as an intergovernmental organisation
6 # nor does it submit to any jurisdiction.
7
8 """
9 A selection of tests for the (generic) hoist variables functionalities.
10 """
11 from pathlib import Path
12 import pytest
13 import numpy as np
14
15 from loki import (
16 Scheduler, SchedulerConfig, is_iterable, FindInlineCalls
17 )
18 from loki.jit_build import jit_compile_lib, Builder
19 from loki.frontend import available_frontends
20 from loki.ir import nodes as ir, FindNodes
21 from loki.transformations.temporaries.hoist_variables import (
22 HoistVariablesAnalysis, HoistVariablesTransformation,
23 HoistTemporaryArraysAnalysis, HoistTemporaryArraysTransformationAllocatable
24 )
25
26
27 @pytest.fixture(scope='module', name='here')
28 def fixture_here():
29 return Path(__file__).parent
30
31
32 @pytest.fixture(scope='module', name='testdir')
33 def fixture_testdir(here):
34 return here.parent.parent.parent/'tests'
35
36
37 @pytest.fixture(name='config')
38 def fixture_config():
39 """
40 Default configuration dict with basic options.
41 """
42 return {
43 'default': {
44 'mode': 'idem',
45 'role': 'kernel',
46 'expand': True,
47 'strict': True,
48 },
49 'routines': {
50 'driver': {
51 'role': 'driver',
52 'expand': True,
53 },
54 'another_driver': {
55 'role': 'driver',
56 'expand': True,
57 },
58 'yet_another_driver': {
59 'role': 'driver',
60 'expand': True,
61 },
62 'inline_driver': {
63 'role': 'driver',
64 'expand': True,
65 },
66 }
67 }
68
69
70 def compile_and_test(scheduler, path, a=(5,), frontend="", test_name="", items=None, inline=False):
71 """
72 Compile the source code and call the driver function in order to test the results for correctness.
73 """
74 assert is_iterable(a) and all(isinstance(_a, int) for _a in a)
75 path = Path(path)
76 if not items:
77 items = [scheduler["transformation_module_hoist#driver"], scheduler["subroutines_mod#kernel1"]]
78 for item in items:
79 suffix = '.F90'
80 item.source.path = (path/f"{item.source.path.stem}").with_suffix(suffix=suffix)
81 libname = f'lib_{test_name}_{frontend}'
82 builder = Builder(source_dirs=path, build_dir=path)
83 lib = jit_compile_lib([item.source for item in items], path=path, name=libname, builder=builder)
84 item = items[0]
85 for _a in a:
86 parameter_length = 3
87 b = np.zeros((_a,), dtype=np.int32, order='F')
88 c = np.zeros((_a, parameter_length), dtype=np.int32, order='F')
89 if inline:
90 lib.Transformation_Module_Hoist_Inline.inline_driver(_a, b, c)
91 else:
92 lib.Transformation_Module_Hoist.driver(_a, b, c)
93 assert (b == 42).all()
94 assert (c == 11).all()
95 builder.clean()
96
97
98 def check_arguments(scheduler, subroutine_arguments, call_arguments, call_kwarguments, driver_item=None,
99 driver_name=None, include_device_functions=False, include_another_driver=True,
100 subroutine_mod=None):
101 """
102 Check the subroutine and call arguments of each subroutine.
103 """
104 # driver
105 if not driver_item:
106 driver_item = scheduler['transformation_module_hoist#driver']
107 if not driver_name:
108 driver_name = "driver"
109
110 assert [arg.name for arg in driver_item.ir.arguments] == subroutine_arguments[driver_name]
111 for call in FindNodes(ir.CallStatement).visit(driver_item.ir.body):
112 if "kernel1" in call.name:
113 assert call.arguments == call_arguments["kernel1"]
114 assert call.kwarguments == call_kwarguments["kernel1"]
115 elif "kernel2" in call.name:
116 assert call.arguments == call_arguments["kernel2"]
117 assert call.kwarguments == call_kwarguments["kernel2"]
118 # another driver
119 if include_another_driver:
120 item = scheduler['transformation_module_hoist#another_driver']
121 assert [arg.name for arg in item.ir.arguments] == subroutine_arguments["another_driver"]
122 for call in FindNodes(ir.CallStatement).visit(item.ir.body):
123 if "kernel1" in call.name:
124 assert call.arguments == call_arguments["kernel1"]
125 assert call.kwarguments == call_kwarguments["kernel1"]
126 # kernel 1
127 if not subroutine_mod:
128 subroutine_mod = 'subroutines_mod'
129
130 item = scheduler[subroutine_mod + '#kernel1']
131 assert [arg.name for arg in item.ir.arguments] == subroutine_arguments["kernel1"]
132
133 for call in FindInlineCalls().visit(item.ir.body):
134 if 'func1' in call.name:
135 assert call.arguments == call_arguments["func1"]
136 assert call.kwarguments == call_kwarguments["func1"]
137
138 # kernel 2
139 item = scheduler[subroutine_mod + '#kernel2']
140 assert [arg.name for arg in item.ir.arguments] == subroutine_arguments["kernel2"]
141 for call in FindNodes(ir.CallStatement).visit(item.ir.body):
142 if "device1" in call.name:
143 assert call.arguments == call_arguments["device1"]
144 assert call.kwarguments == call_kwarguments["device1"]
145 elif "device2" in call.name:
146 assert call.arguments == call_arguments["device2"]
147 assert call.kwarguments == call_kwarguments["device2"]
148 if include_device_functions:
149 # device 1
150 item = scheduler[subroutine_mod + '#device1']
151 assert [arg.name for arg in item.ir.arguments] == subroutine_arguments["device1"]
152 for call in FindNodes(ir.CallStatement).visit(item.ir.body):
153 if "device2" in call.name:
154 assert call.arguments == call_arguments["device2"]
155 assert call.kwarguments == call_kwarguments["device2"]
156 # device 2
157 item = scheduler[subroutine_mod + '#device2']
158 assert [arg.name for arg in item.ir.arguments] == subroutine_arguments["device2"]
159
160 for call in FindInlineCalls().visit(item.ir.body):
161 if 'init_int' in call.name:
162 assert call.arguments == call_arguments["init_int"]
163 assert call.kwarguments == call_kwarguments["init_int"]
164
165
166 @pytest.mark.parametrize('frontend', available_frontends())
167 @pytest.mark.parametrize('as_kwarguments', [False, True])
168 def test_hoist(tmp_path, testdir, frontend, config, as_kwarguments):
169 """
170 Basic testing of the non-modified Hoist functionality, thus hoisting all (non-parameter) local variables.
171 """
172
173 proj = testdir/'sources/projHoist'
174 scheduler = Scheduler(
175 paths=[proj], config=config, seed_routines=['driver', 'another_driver'], frontend=frontend, xmods=[tmp_path]
176 )
177
178 # check correctness of original source code
179 compile_and_test(scheduler=scheduler, path=tmp_path, frontend=frontend, a=(5, 10, 100), test_name="source")
180
181 # Transformation: Analysis
182 scheduler.process(transformation=HoistVariablesAnalysis())
183 # Transformation: Synthesis
184 scheduler.process(transformation=HoistVariablesTransformation(as_kwarguments=as_kwarguments))
185
186 # check generated source code
187 subroutine_arguments = {
188 "driver": ['a', 'b', 'c'],
189 "another_driver": ['a', 'b', 'c'],
190 "kernel1": ['a', 'b', 'c', 'x', 'y', 'k1_tmp'],
191 "kernel2": ['a1', 'b', 'x', 'y', 'z', 'k2_tmp', 'device1_z', 'device1_d1_tmp', 'device2_z', 'device2_d2_tmp'],
192 "device1": ['a1', 'b', 'x', 'y', 'z', 'd1_tmp', 'device2_z', 'device2_d2_tmp'],
193 "device2": ['a2', 'b', 'x', 'z', 'd2_tmp'],
194 }
195
196 call_arguments = {
197 "kernel1": ('a', 'b', 'c'),
198 "kernel2": ('a', 'b'),
199 "device1": ('a1', 'b', 'x', 'k2_tmp'),
200 "device2": ('a1', 'b', 'x')
201 }
202 if not as_kwarguments:
203 call_arguments["kernel1"] += ('kernel1_x', 'kernel1_y', 'kernel1_k1_tmp')
204 call_arguments["kernel2"] += ('kernel2_x', 'kernel2_y', 'kernel2_z', 'kernel2_k2_tmp',
205 'device1_z', 'device1_d1_tmp', 'device2_z', 'device2_d2_tmp')
206 call_arguments["device1"] += ('device1_z', 'device1_d1_tmp', 'device2_z', 'device2_d2_tmp')
207 call_arguments["device2"] += ('device2_z', 'device2_d2_tmp')
208
209 call_kwarguments = {
210 "kernel1": (('x', 'kernel1_x'), ('y', 'kernel1_y'), ('k1_tmp', 'kernel1_k1_tmp')) if as_kwarguments else (),
211 "kernel2": (('x', 'kernel2_x'), ('y', 'kernel2_y'), ('z', 'kernel2_z'), ('k2_tmp', 'kernel2_k2_tmp'),
212 ('device1_z', 'device1_z'), ('device1_d1_tmp', 'device1_d1_tmp'),
213 ('device2_z', 'device2_z'), ('device2_d2_tmp', 'device2_d2_tmp')) if as_kwarguments else (),
214 "device1": (('z', 'device1_z'), ('d1_tmp', 'device1_d1_tmp'), ('device2_z', 'device2_z'),
215 ('device2_d2_tmp', 'device2_d2_tmp')) if as_kwarguments else (),
216 "device2": (('z', 'device2_z'), ('d2_tmp', 'device2_d2_tmp')) if as_kwarguments else ()
217 }
218
219 check_arguments(scheduler=scheduler, subroutine_arguments=subroutine_arguments, call_arguments=call_arguments,
220 call_kwarguments=call_kwarguments)
221 compile_and_test(scheduler=scheduler, path=tmp_path, a=(5, 10, 100), frontend=frontend, test_name="all_hoisted")
222
223
224 @pytest.mark.parametrize('frontend', available_frontends())
225 @pytest.mark.parametrize('as_kwarguments', [False, True])
226 def test_hoist_disable(tmp_path, testdir, frontend, config, as_kwarguments):
227 """
228 Basic testing of the non-modified Hoist functionality excluding/disabling some subroutines,
229 thus hoisting all (non-parameter) local variables for the non-disabled subroutines.
230 """
231
232 disable = ("device1", "device2")
233 config['routines']['kernel2'] = {'role': 'kernel', 'block': disable}
234 proj = testdir/'sources/projHoist'
235 scheduler = Scheduler(
236 paths=[proj], config=config, seed_routines=['driver', 'another_driver'], frontend=frontend, xmods=[tmp_path]
237 )
238
239 # Transformation: Analysis
240 scheduler.process(transformation=HoistVariablesAnalysis())
241 # Transformation: Synthesis
242 scheduler.process(transformation=HoistVariablesTransformation(as_kwarguments=as_kwarguments))
243
244 # check generated source code
245 subroutine_arguments = {
246 "driver": ['a', 'b', 'c'],
247 "another_driver": ['a', 'b', 'c'],
248 "kernel1": ['a', 'b', 'c', 'x', 'y', 'k1_tmp'],
249 "kernel2": ['a1', 'b', 'x', 'y', 'z', 'k2_tmp'],
250 "device1": ['a1', 'b', 'x', 'y'],
251 "device2": ['a2', 'b', 'x'],
252 }
253
254 call_arguments = {
255 "kernel1": ('a', 'b', 'c', 'kernel1_x', 'kernel1_y', 'kernel1_k1_tmp'),
256 "kernel2": ('a', 'b', 'kernel2_x', 'kernel2_y', 'kernel2_z', 'kernel2_k2_tmp'),
257 "device1": ('a1', 'b', 'x', 'k2_tmp'),
258 "device2": ('a1', 'b', 'x')
259 }
260
261 call_arguments = {
262 "kernel1": ('a', 'b', 'c'),
263 "kernel2": ('a', 'b'),
264 "device1": ('a1', 'b', 'x', 'k2_tmp'),
265 "device2": ('a1', 'b', 'x')
266 }
267 if not as_kwarguments:
268 call_arguments["kernel1"] += ('kernel1_x', 'kernel1_y', 'kernel1_k1_tmp')
269 call_arguments["kernel2"] += ('kernel2_x', 'kernel2_y', 'kernel2_z', 'kernel2_k2_tmp')
270
271 call_kwarguments = {
272 "kernel1": (('x', 'kernel1_x'), ('y', 'kernel1_y'), ('k1_tmp', 'kernel1_k1_tmp')) if as_kwarguments else (),
273 "kernel2": (('x', 'kernel2_x'), ('y', 'kernel2_y'), ('z', 'kernel2_z'),
274 ('k2_tmp', 'kernel2_k2_tmp')) if as_kwarguments else (),
275 "device1": (),
276 "device2": ()
277 }
278
279 check_arguments(
280 scheduler=scheduler, subroutine_arguments=subroutine_arguments,
281 call_arguments=call_arguments, call_kwarguments=call_kwarguments,
282 include_device_functions=False
283 )
284 compile_and_test(
285 scheduler=scheduler, path=tmp_path, a=(5, 10, 100),
286 frontend=frontend, test_name="all_hoisted_disable"
287 )
288
289 @pytest.mark.parametrize('frontend', available_frontends())
290 @pytest.mark.parametrize('as_kwarguments', [False, True])
291 def test_hoist_arrays_inline(tmp_path, testdir, frontend, config, as_kwarguments):
292 """
293 Testing hoist functionality for local arrays using the :class:`HoistTemporaryArraysAnalysis` for the *Analysis*
294 part. The hoisted kernel contains inline function calls.
295 """
296
297 proj = testdir/'sources/projHoist'
298 scheduler = Scheduler(
299 paths=[proj], config=config, seed_routines=['inline_driver',], frontend=frontend, xmods=[tmp_path]
300 )
301
302 # Transformation: Analysis
303 scheduler.process(transformation=HoistTemporaryArraysAnalysis())
304 # Transformation: Synthesis
305 scheduler.process(transformation=HoistVariablesTransformation(as_kwarguments=as_kwarguments))
306
307 # check generated source code
308 subroutine_arguments = {
309 "inline_driver": ['a', 'b', 'c'],
310 "kernel1": ['a', 'b', 'c', 'x', 'y', 'k1_tmp'],
311 "kernel2": ['a1', 'b', 'x', 'k2_tmp', 'device2_z', 'init_int_tmp0'],
312 "device1": ['a1', 'b', 'x', 'y', 'device2_z', 'init_int_tmp0'],
313 "device2": ['a2', 'b', 'x', 'z', 'init_int_tmp0'],
314 "init_int": ['a2', 'tmp0'],
315 "func1": ['a']
316 }
317
318 call_arguments = {
319 "kernel1": ('a', 'b', 'c'),
320 "kernel2": ('a', 'b'),
321 "device1": ('a1', 'b', 'x', 'k2_tmp'),
322 "device2": ('a1', 'b', 'x'),
323 "init_int": ('a2',),
324 "func1": ('a',)
325 }
326 if not as_kwarguments:
327 call_arguments["kernel1"] += ('kernel1_x', 'kernel1_y', 'kernel1_k1_tmp')
328 call_arguments["kernel2"] += ('kernel2_x', 'kernel2_k2_tmp', 'device2_z', 'init_int_tmp0')
329 call_arguments["device1"] += ('device2_z', 'init_int_tmp0')
330 call_arguments["device2"] += ('device2_z', 'init_int_tmp0')
331 call_arguments["init_int"] += ('init_int_tmp0',)
332
333 call_kwarguments = {
334 "kernel1": (('x', 'kernel1_x'), ('y', 'kernel1_y'), ('k1_tmp', 'kernel1_k1_tmp')) if as_kwarguments else (),
335 "kernel2": (('x', 'kernel2_x'), ('k2_tmp', 'kernel2_k2_tmp'),
336 ('device2_z', 'device2_z'), ('init_int_tmp0', 'init_int_tmp0')) if as_kwarguments else (),
337 "device1": (('device2_z', 'device2_z'), ('init_int_tmp0', 'init_int_tmp0')) if as_kwarguments else (),
338 "device2": (('z', 'device2_z'), ('init_int_tmp0', 'init_int_tmp0')) if as_kwarguments else (),
339 "init_int": (('tmp0', 'init_int_tmp0'),) if as_kwarguments else (),
340 "func1": ()
341 }
342
343 check_arguments(scheduler=scheduler, subroutine_arguments=subroutine_arguments, call_arguments=call_arguments,
344 call_kwarguments=call_kwarguments, driver_item=scheduler['transformation_module_hoist_inline#inline_driver'],
345 driver_name='inline_driver', include_another_driver=False, subroutine_mod='subroutines_inline_mod',
346 include_device_functions=True)
347 compile_and_test(scheduler=scheduler, path=tmp_path, a=(5, 10, 100), frontend=frontend,
348 test_name="hoisted_arrays_inline",
349 items=[scheduler["transformation_module_hoist_inline#inline_driver"],
350 scheduler["subroutines_inline_mod#kernel1"]], inline=True)
351
352 @pytest.mark.parametrize('frontend', available_frontends())
353 @pytest.mark.parametrize('as_kwarguments', [False, True])
354 def test_hoist_arrays(tmp_path, testdir, frontend, config, as_kwarguments):
355 """
356 Testing hoist functionality for local arrays using the :class:`HoistTemporaryArraysAnalysis` for the *Analysis*
357 part.
358 """
359
360 proj = testdir/'sources/projHoist'
361 scheduler = Scheduler(
362 paths=[proj], config=config, seed_routines=['driver', 'another_driver'], frontend=frontend, xmods=[tmp_path]
363 )
364
365 # Transformation: Analysis
366 scheduler.process(transformation=HoistTemporaryArraysAnalysis())
367 # Transformation: Synthesis
368 scheduler.process(transformation=HoistVariablesTransformation(as_kwarguments=as_kwarguments))
369
370 # check generated source code
371 subroutine_arguments = {
372 "driver": ['a', 'b', 'c'],
373 "another_driver": ['a', 'b', 'c'],
374 "kernel1": ['a', 'b', 'c', 'x', 'y', 'k1_tmp'],
375 "kernel2": ['a1', 'b', 'x', 'k2_tmp', 'device2_z'],
376 "device1": ['a1', 'b', 'x', 'y', 'device2_z'],
377 "device2": ['a2', 'b', 'x', 'z'],
378 }
379
380 call_arguments = {
381 "kernel1": ('a', 'b', 'c'),
382 "kernel2": ('a', 'b'),
383 "device1": ('a1', 'b', 'x', 'k2_tmp'),
384 "device2": ('a1', 'b', 'x')
385 }
386 if not as_kwarguments:
387 call_arguments["kernel1"] += ('kernel1_x', 'kernel1_y', 'kernel1_k1_tmp')
388 call_arguments["kernel2"] += ('kernel2_x', 'kernel2_k2_tmp', 'device2_z')
389 call_arguments["device1"] += ('device2_z',)
390 call_arguments["device2"] += ('device2_z',)
391
392 call_kwarguments = {
393 "kernel1": (('x', 'kernel1_x'), ('y', 'kernel1_y'), ('k1_tmp', 'kernel1_k1_tmp')) if as_kwarguments else (),
394 "kernel2": (('x', 'kernel2_x'), ('k2_tmp', 'kernel2_k2_tmp'),
395 ('device2_z', 'device2_z')) if as_kwarguments else (),
396 "device1": (('device2_z', 'device2_z'), ) if as_kwarguments else (),
397 "device2": (('z', 'device2_z'), ) if as_kwarguments else ()
398 }
399
400 check_arguments(scheduler=scheduler, subroutine_arguments=subroutine_arguments, call_arguments=call_arguments,
401 call_kwarguments=call_kwarguments)
402 compile_and_test(scheduler=scheduler, path=tmp_path, a=(5, 10, 100), frontend=frontend, test_name="hoisted_arrays")
403
404
405 @pytest.mark.parametrize('frontend', available_frontends())
406 @pytest.mark.parametrize('as_kwarguments', [False, True])
407 def test_hoist_specific_variables(tmp_path, testdir, frontend, config, as_kwarguments):
408 """
409 Testing hoist functionality for local arrays with variable ``a`` in the array dimensions using the
410 :class:`HoistTemporaryArraysAnalysis` for the *Analysis* part.
411 """
412
413 proj = testdir/'sources/projHoist'
414 scheduler = Scheduler(
415 paths=[proj], config=config, seed_routines=['driver', 'another_driver'], frontend=frontend, xmods=[tmp_path]
416 )
417
418 # Transformation: Analysis
419 scheduler.process(transformation=HoistTemporaryArraysAnalysis(dim_vars=('a', 'a1', 'a2')))
420 # Transformation: Synthesis
421 scheduler.process(transformation=HoistVariablesTransformation(as_kwarguments=as_kwarguments))
422
423 # check generated source code
424 subroutine_arguments = {
425 "driver": ['a', 'b', 'c'],
426 "another_driver": ['a', 'b', 'c'],
427 "kernel1": ['a', 'b', 'c', 'x', 'y', 'k1_tmp'],
428 "kernel2": ['a1', 'b', 'x', 'k2_tmp', 'device2_z'],
429 "device1": ['a1', 'b', 'x', 'y', 'device2_z'],
430 "device2": ['a2', 'b', 'x', 'z'],
431 }
432
433 call_arguments = {
434 "kernel1": ('a', 'b', 'c'),
435 "kernel2": ('a', 'b'),
436 "device1": ('a1', 'b', 'x', 'k2_tmp'),
437 "device2": ('a1', 'b', 'x')
438 }
439 if not as_kwarguments:
440 call_arguments["kernel1"] += ('kernel1_x', 'kernel1_y', 'kernel1_k1_tmp')
441 call_arguments["kernel2"] += ('kernel2_x', 'kernel2_k2_tmp', 'device2_z')
442 call_arguments["device1"] += ('device2_z',)
443 call_arguments["device2"] += ('device2_z',)
444
445 call_kwarguments = {
446 "kernel1": (('x', 'kernel1_x'), ('y', 'kernel1_y'), ('k1_tmp', 'kernel1_k1_tmp')) if as_kwarguments else (),
447 "kernel2": (('x', 'kernel2_x'), ('k2_tmp', 'kernel2_k2_tmp'),
448 ('device2_z', 'device2_z')) if as_kwarguments else (),
449 "device1": (('device2_z', 'device2_z'),) if as_kwarguments else (),
450 "device2": (('z', 'device2_z'),) if as_kwarguments else ()
451 }
452
453 check_arguments(scheduler=scheduler, subroutine_arguments=subroutine_arguments, call_arguments=call_arguments,
454 call_kwarguments=call_kwarguments)
455
456 compile_and_test(scheduler=scheduler, path=tmp_path, a=(5, 10, 100), frontend=frontend,
457 test_name="hoisted_specific_arrays")
458
459
460 def check_variable_declaration(item, key):
461 declarations = [_.symbols[0].name for _ in FindNodes(ir.VariableDeclaration).visit(item.ir.spec)]
462 allocations = [_.variables[0].name for _ in FindNodes(ir.Allocation).visit(item.ir.body)]
463 de_allocations = [_.variables[0].name for _ in FindNodes(ir.Deallocation).visit(item.ir.body)]
464 assert allocations
465 assert de_allocations
466 to_hoist_vars = [var.name for var in item.trafo_data[key]["to_hoist"]]
467 assert all(_ in declarations for _ in to_hoist_vars)
468 assert all(_ in to_hoist_vars for _ in allocations)
469 assert all(_ in to_hoist_vars for _ in de_allocations)
470
471
472 @pytest.mark.parametrize('frontend', available_frontends())
473 @pytest.mark.parametrize('as_kwarguments', [False, True])
474 def test_hoist_allocatable(tmp_path, testdir, frontend, config, as_kwarguments):
475 """
476 Testing hoist functionality for local arrays with variable ``a`` in the array dimensions using the
477 :class:`HoistTemporaryArraysAnalysis` for the *Analysis* part **and** a *Synthesis* implementation using declaring
478 hoisted arrays as *allocatable*, including allocation and de-allocation using
479 :class:`HoistTemporaryArraysTransformationAllocatable`.
480 """
481
482 proj = testdir/'sources/projHoist'
483 scheduler = Scheduler(
484 paths=[proj], config=config, seed_routines=['driver', 'another_driver'], frontend=frontend, xmods=[tmp_path]
485 )
486
487 key = "HoistVariablesTransformation"
488 # Transformation: Analysis
489 scheduler.process(
490 transformation=HoistTemporaryArraysAnalysis(dim_vars=('a', 'a1', 'a2'))
491 )
492 # Transformation: Synthesis
493 scheduler.process(
494 transformation=HoistTemporaryArraysTransformationAllocatable(
495 as_kwarguments=as_kwarguments
496 )
497 )
498
499 # check generated source code
500 for item in scheduler.items:
501 if "driver" in item.name and "another" not in item.name:
502 check_variable_declaration(item, key)
503 elif "another_driver" in item.name:
504 check_variable_declaration(item, key)
505
506 subroutine_arguments = {
507 "driver": ['a', 'b', 'c'],
508 "another_driver": ['a', 'b', 'c'],
509 "kernel1": ['a', 'b', 'c', 'x', 'y', 'k1_tmp'],
510 "kernel2": ['a1', 'b', 'x', 'k2_tmp', 'device2_z'],
511 "device1": ['a1', 'b', 'x', 'y', 'device2_z'],
512 "device2": ['a2', 'b', 'x', 'z'],
513 }
514
515 call_arguments = {
516 "kernel1": ('a', 'b', 'c', 'kernel1_x', 'kernel1_y', 'kernel1_k1_tmp'),
517 "kernel2": ('a', 'b', 'kernel2_x', 'kernel2_k2_tmp', 'device2_z'),
518 "device1": ('a1', 'b', 'x', 'k2_tmp', 'device2_z'),
519 "device2": ('a1', 'b', 'x', 'device2_z')
520 }
521
522 call_arguments = {
523 "kernel1": ('a', 'b', 'c'),
524 "kernel2": ('a', 'b'),
525 "device1": ('a1', 'b', 'x', 'k2_tmp'),
526 "device2": ('a1', 'b', 'x')
527 }
528 if not as_kwarguments:
529 call_arguments["kernel1"] += ('kernel1_x', 'kernel1_y', 'kernel1_k1_tmp')
530 call_arguments["kernel2"] += ('kernel2_x', 'kernel2_k2_tmp', 'device2_z')
531 call_arguments["device1"] += ('device2_z',)
532 call_arguments["device2"] += ('device2_z',)
533
534 call_kwarguments = {
535 "kernel1": (('x', 'kernel1_x'), ('y', 'kernel1_y'), ('k1_tmp', 'kernel1_k1_tmp')) if as_kwarguments else (),
536 "kernel2": (('x', 'kernel2_x'), ('k2_tmp', 'kernel2_k2_tmp'),
537 ('device2_z', 'device2_z')) if as_kwarguments else (),
538 "device1": (('device2_z', 'device2_z'),) if as_kwarguments else (),
539 "device2": (('z', 'device2_z'),) if as_kwarguments else ()
540 }
541
542 check_arguments(scheduler=scheduler, subroutine_arguments=subroutine_arguments, call_arguments=call_arguments,
543 call_kwarguments=call_kwarguments)
544 compile_and_test(scheduler=scheduler, path=tmp_path, a=(5, 10, 100), frontend=frontend, test_name="allocatable")
545
546
547 @pytest.mark.parametrize('frontend', available_frontends())
548 def test_hoist_mixed_variable_declarations(tmp_path, frontend, config):
549
550 fcode_driver = """
551 subroutine driver(NLON, NZ, NB, FIELD1, FIELD2)
552 use kernel_mod, only: kernel
553 implicit none
554 INTEGER, PARAMETER :: JPRB = SELECTED_REAL_KIND(13,300)
555 INTEGER, INTENT(IN) :: NLON, NZ, NB
556 integer :: b
557 real(kind=jprb), intent(inout) :: field1(nlon, nb)
558 real(kind=jprb), intent(inout) :: field2(nlon, nz, nb)
559 do b=1,nb
560 call KERNEL(1, nlon, nlon, nz, 2, field1(:,b), field2(:,:,b))
561 end do
562 end subroutine driver
563 """.strip()
564 fcode_kernel = """
565 module kernel_mod
566 implicit none
567 contains
568 subroutine kernel(start, end, klon, klev, nclv, field1, field2)
569 use, intrinsic :: iso_c_binding, only : c_size_t
570 implicit none
571 interface
572 subroutine another_kernel(klev)
573 integer, intent(in) :: klev
574 end subroutine another_kernel
575 end interface
576 integer, parameter :: jprb = selected_real_kind(13,300)
577 integer, intent(in) :: nclv
578 integer, intent(in) :: start, end, klon, klev
579 real(kind=jprb), intent(inout) :: field1(klon)
580 real(kind=jprb), intent(inout) :: field2(klon,klev)
581 real(kind=jprb) :: tmp1(klon)
582 real(kind=jprb) :: tmp2(klon, klev), tmp3(nclv)
583 real(kind=jprb) :: tmp4(2), tmp5(klon, nclv, klev)
584 integer :: jk, jl, jm
585
586 do jk=1,klev
587 tmp1(jl) = 0.0_jprb
588 do jl=start,end
589 tmp2(jl, jk) = field2(jl, jk)
590 tmp1(jl) = field2(jl, jk)
591 end do
592 field1(jl) = tmp1(jl)
593 end do
594
595 do jm=1,nclv
596 tmp3(jm) = 0._jprb
597 do jl=start,end
598 tmp5(jl, jm, :) = field1(jl)
599 enddo
600 enddo
601
602 call another_kernel(klev)
603 end subroutine kernel
604 end module kernel_mod
605 """.strip()
606 fcode_mod = """
607 module size_mod
608 implicit none
609 integer :: n
610 end module size_mod
611 """.strip()
612 fcode_another_kernel = """
613 subroutine another_kernel(klev)
614 use size_mod, only : n
615 implicit none
616 integer, intent(in) :: klev
617 real :: another_tmp(klev,n)
618 end subroutine another_kernel
619 """.strip()
620
621 (tmp_path/'driver.F90').write_text(fcode_driver)
622 (tmp_path/'kernel_mod.F90').write_text(fcode_kernel)
623 (tmp_path/'size_mod.F90').write_text(fcode_mod)
624 (tmp_path/'another_kernel.F90').write_text(fcode_another_kernel)
625
626 config = {
627 'default': {
628 'mode': 'idem',
629 'role': 'kernel',
630 'expand': True,
631 'strict': True,
632 'enable_imports': True
633 },
634 'routines': {
635 'driver': {'role': 'driver'}
636 }
637 }
638
639 scheduler = Scheduler(
640 paths=[tmp_path], config=SchedulerConfig.from_dict(config), frontend=frontend, xmods=[tmp_path]
641 )
642 scheduler.process(transformation=HoistTemporaryArraysAnalysis(dim_vars=('klev',)))
643 scheduler.process(transformation=HoistTemporaryArraysTransformationAllocatable())
644
645 driver_variables = (
646 'jprb', 'nlon', 'nz', 'nb', 'b',
647 'field1(nlon, nb)', 'field2(nlon, nz, nb)',
648 'kernel_tmp2(:,:)', 'kernel_tmp5(:,:,:)', 'another_kernel_another_tmp(:,:)'
649 )
650 kernel_arguments = (
651 'start', 'end', 'klon', 'klev', 'nclv',
652 'field1(klon)', 'field2(klon,klev)', 'tmp2(klon,klev)', 'tmp5(klon,nclv,klev)',
653 'another_kernel_another_tmp(klev,n)'
654 )
655
656 # Check hoisting and declaration in driver
657 assert scheduler['#driver'].ir.variables == driver_variables
658 assert scheduler['kernel_mod#kernel'].ir.arguments == kernel_arguments
659
660 # Check updated call signature
661 calls = FindNodes(ir.CallStatement).visit(scheduler['#driver'].ir.body)
662 assert len(calls) == 1
663 assert calls[0].arguments == (
664 '1', 'nlon', 'nlon', 'nz', '2', 'field1(:,b)', 'field2(:,:,b)',
665 'kernel_tmp2', 'kernel_tmp5', 'another_kernel_another_tmp'
666 )
667
668 # Check that fgen works
669 assert scheduler['kernel_mod#kernel'].source.to_fortran()
670
671 # Check that imports were updated
672 imports = FindNodes(ir.Import).visit(scheduler['kernel_mod#kernel'].ir.spec)
673 assert len(imports) == 2
674 assert 'n' in scheduler['kernel_mod#kernel'].ir.imported_symbols
675 assert imports[0].module.lower() == 'size_mod'
676
677 imports = FindNodes(ir.Import).visit(scheduler['#driver'].ir.spec)
678 assert len(imports) == 2
679 assert 'n' in scheduler['#driver'].ir.imported_symbols
680 assert imports[0].module.lower() == 'size_mod'
681
682
683 @pytest.mark.parametrize('frontend', available_frontends())
684 @pytest.mark.parametrize('remap_dimensions', (False, True))
685 def test_hoist_dim_mapping(tmp_path, frontend, config, remap_dimensions):
686
687 fcode_driver = """
688 subroutine driver(NLON, NB, FIELD1)
689 use kernel_mod, only: kernel
690 implicit none
691 INTEGER, INTENT(IN) :: NLON, NB
692 integer :: b
693 integer, intent(inout) :: field1(nlon, nb)
694 integer :: local_nlon
695 local_nlon = nlon
696 do b=1,nb
697 call KERNEL(local_nlon, field1(:,b))
698 end do
699 end subroutine driver
700 """.strip()
701 fcode_kernel = """
702 module kernel_mod
703 implicit none
704 contains
705 subroutine kernel(klon, field1)
706 implicit none
707 integer, intent(in) :: klon
708 integer, intent(inout) :: field1(klon)
709 integer :: tmp1(klon)
710 integer :: jl
711
712 do jl=1,klon
713 tmp1(jl) = 0
714 field1(jl) = tmp1(jl)
715 end do
716
717 end subroutine kernel
718 end module kernel_mod
719 """.strip()
720
721 (tmp_path/'driver.F90').write_text(fcode_driver)
722 (tmp_path/'kernel_mod.F90').write_text(fcode_kernel)
723
724 config = {
725 'default': {
726 'mode': 'idem',
727 'role': 'kernel',
728 'expand': True,
729 'strict': True,
730 'enable_imports': True
731 },
732 'routines': {
733 'driver': {'role': 'driver'}
734 }
735 }
736
737 scheduler = Scheduler(
738 paths=[tmp_path], config=SchedulerConfig.from_dict(config), frontend=frontend, xmods=[tmp_path]
739 )
740
741 scheduler.process(transformation=HoistTemporaryArraysAnalysis())
742 scheduler.process(transformation=HoistVariablesTransformation(remap_dimensions=remap_dimensions))
743
744 driver_var_map = scheduler['#driver'].ir.variable_map
745 assert 'kernel_tmp1' in driver_var_map
746 if remap_dimensions:
747 assert driver_var_map['kernel_tmp1'].dimensions == ('nlon',)
748 else:
749 assert driver_var_map['kernel_tmp1'].dimensions == ('local_nlon',)
750
751
752 @pytest.mark.parametrize('frontend', available_frontends())
753 def test_hoist_dim_alias(tmp_path, testdir, frontend, config):
754 """
755 Test that temporaries declared with an aliased dimension aren't repeated.
756 """
757
758 proj = testdir/'sources/projHoist'
759 scheduler = Scheduler(
760 paths=[proj], config=config, seed_routines=['yet_another_driver'], frontend=frontend, xmods=[tmp_path]
761 )
762
763 scheduler.process(transformation=HoistTemporaryArraysAnalysis())
764 scheduler.process(transformation=HoistVariablesTransformation())
765
766 kernel3 = scheduler['subroutines_mod#kernel3'].ir
767 device3 = scheduler['subroutines_mod#device3'].ir
768 driver = scheduler['transformation_module_hoist#yet_another_driver'].ir
769
770 # check temporary was hoisted
771 assert 'x' in device3._dummies
772 assert 'device3_x' in kernel3._dummies
773 assert len(kernel3.arguments) == 3
774 device3_temp = kernel3.variable_map['device3_x']
775 assert 'a1' in device3_temp.shape
776
777 # check call signatures for device3 were updated
778 calls = FindNodes(ir.CallStatement).visit(kernel3.body)
779 assert len(calls) == 2
780 assert 'device3_x' in calls[0].arguments
781 assert 'device3_x' in calls[1].arguments
782
783 # check driver layer
784 calls = FindNodes(ir.CallStatement).visit(driver.body)
785 assert len(calls[0].arguments) == 3
786 assert 'device3_x' in calls[0].arguments