kerncraft_interface.py 9.25 KB
Newer Older
Martin Bauer's avatar
Martin Bauer committed
1
import warnings
2
import fcntl
Martin Bauer's avatar
Martin Bauer committed
3
from collections import defaultdict
Martin Bauer's avatar
Martin Bauer committed
4
from tempfile import TemporaryDirectory
Martin Bauer's avatar
Martin Bauer committed
5
from typing import Optional
Martin Bauer's avatar
Martin Bauer committed
6

7
8
from jinja2 import Environment, PackageLoader, StrictUndefined

Martin Bauer's avatar
Martin Bauer committed
9
import kerncraft
Martin Bauer's avatar
Martin Bauer committed
10
import sympy as sp
11
from kerncraft.kerncraft import KernelCode
Julian Hammer's avatar
Julian Hammer committed
12
13
from kerncraft.machinemodel import MachineModel

Martin Bauer's avatar
Martin Bauer committed
14
15
from pystencils.astnodes import (
    KernelFunction, LoopOverCoordinate, ResolvedFieldAccess, SympyAssignment)
Martin Bauer's avatar
Martin Bauer committed
16
from pystencils.field import get_layout_from_strides
Martin Bauer's avatar
Martin Bauer committed
17
from pystencils.kerncraft_coupling.generate_benchmark import generate_benchmark
Martin Bauer's avatar
Martin Bauer committed
18
from pystencils.sympyextensions import count_operations_in_ast
19
from pystencils.transformations import filtered_tree_iteration
Martin Bauer's avatar
Martin Bauer committed
20
from pystencils.utils import DotDict
21
from pystencils.backends.cbackend import generate_c, get_headers
Martin Bauer's avatar
Martin Bauer committed
22
23


24
class PyStencilsKerncraftKernel(KernelCode):
Martin Bauer's avatar
Martin Bauer committed
25
26
27
28
    """
    Implementation of kerncraft's kernel interface for pystencils CPU kernels.
    Analyses a list of equations assuming they will be executed on a CPU
    """
Martin Bauer's avatar
Martin Bauer committed
29
30
    LIKWID_BASE = '/usr/local/likwid'

31
32
    def __init__(self, ast: KernelFunction, machine: Optional[MachineModel] = None,
                 assumed_layout='SoA', debug_print=False, filename=None):
Julian Hammer's avatar
Julian Hammer committed
33
34
35
36
37
        """Create a kerncraft kernel using a pystencils AST

        Args:
            ast: pystencils ast
            machine: kerncraft machine model - specify this if kernel needs to be compiled
38
39
40
            assumed_layout: either 'SoA' or 'AoS' - if fields have symbolic sizes the layout of the index
                    coordinates is not known. In this case either a structures of array (SoA) or
                    array of structures (AoS) layout is assumed
Julian Hammer's avatar
Julian Hammer committed
41
        """
Julian Hammer's avatar
Julian Hammer committed
42
        kerncraft.kernel.Kernel.__init__(self, machine)
Martin Bauer's avatar
Martin Bauer committed
43

Julian Hammer's avatar
Julian Hammer committed
44
45
        # Initialize state
        self.asm_block = None
46
        self._filename = filename
Julian Hammer's avatar
Julian Hammer committed
47
48

        self.kernel_ast = ast
Martin Bauer's avatar
Martin Bauer committed
49
        self.temporary_dir = TemporaryDirectory()
50
        self._keep_intermediates = debug_print
Martin Bauer's avatar
Martin Bauer committed
51
52

        # Loops
Markus Holzer's avatar
Markus Holzer committed
53
54
        inner_loops = [l for l in filtered_tree_iteration(ast, LoopOverCoordinate, stop_type=SympyAssignment)
                       if l.is_innermost_loop]
Martin Bauer's avatar
Martin Bauer committed
55
        if len(inner_loops) == 0:
Martin Bauer's avatar
Martin Bauer committed
56
57
            raise ValueError("No loop found in pystencils AST")
        else:
58
59
60
            if len(inner_loops) > 1:
                warnings.warn("pystencils AST contains multiple inner loops. "
                              "Only one can be analyzed - choosing first one")
Martin Bauer's avatar
Martin Bauer committed
61
            inner_loop = inner_loops[0]
Martin Bauer's avatar
Martin Bauer committed
62
63

        self._loop_stack = []
Martin Bauer's avatar
Martin Bauer committed
64
65
66
        cur_node = inner_loop
        while cur_node is not None:
            if isinstance(cur_node, LoopOverCoordinate):
Martin Bauer's avatar
Martin Bauer committed
67
                loop_counter_sym = cur_node.loop_counter_symbol
68
                loop_info = (loop_counter_sym.name, cur_node.start, cur_node.stop, 1)
Julian Hammer's avatar
Julian Hammer committed
69
70
                # If the correct step were to be provided, all access within that step length will
                # also need to be passed to kerncraft: cur_node.step)
Martin Bauer's avatar
Martin Bauer committed
71
                self._loop_stack.append(loop_info)
Martin Bauer's avatar
Martin Bauer committed
72
            cur_node = cur_node.parent
Martin Bauer's avatar
Martin Bauer committed
73
74
75
        self._loop_stack = list(reversed(self._loop_stack))

        # Data sources & destinations
76
77
        self.sources = defaultdict(list)
        self.destinations = defaultdict(list)
Martin Bauer's avatar
Martin Bauer committed
78

Julian Hammer's avatar
Julian Hammer committed
79
80
81
82
83
84
85
86
87
        def get_layout_tuple(f):
            if f.has_fixed_shape:
                return get_layout_from_strides(f.strides)
            else:
                layout_list = list(f.layout)
                for _ in range(f.index_dimensions):
                    layout_list.insert(0 if assumed_layout == 'SoA' else -1, max(layout_list) + 1)
                return layout_list

Martin Bauer's avatar
Martin Bauer committed
88
        reads, writes = search_resolved_field_accesses_in_ast(inner_loop)
Martin Bauer's avatar
Martin Bauer committed
89
        for accesses, target_dict in [(reads, self.sources), (writes, self.destinations)]:
Martin Bauer's avatar
Martin Bauer committed
90
            for fa in accesses:
Martin Bauer's avatar
Martin Bauer committed
91
                coord = [sp.Symbol(LoopOverCoordinate.get_loop_counter_name(i), positive=True, integer=True) + off
Martin Bauer's avatar
Martin Bauer committed
92
                         for i, off in enumerate(fa.offsets)]
Martin Bauer's avatar
Martin Bauer committed
93
                coord += list(fa.idx_coordinate_values)
Julian Hammer's avatar
Julian Hammer committed
94
95
                layout = get_layout_tuple(fa.field)
                permuted_coord = [sp.sympify(coord[i]) for i in layout]
Martin Bauer's avatar
Martin Bauer committed
96
                target_dict[fa.field.name].append(permuted_coord)
Martin Bauer's avatar
Martin Bauer committed
97
98

        # Variables (arrays)
Martin Bauer's avatar
Martin Bauer committed
99
100
        fields_accessed = ast.fields_accessed
        for field in fields_accessed:
Julian Hammer's avatar
Julian Hammer committed
101
            layout = get_layout_tuple(field)
Martin Bauer's avatar
Martin Bauer committed
102
            permuted_shape = list(field.shape[i] for i in layout)
103
            self.set_variable(field.name, tuple([str(field.dtype)]), tuple(permuted_shape))
Martin Bauer's avatar
Martin Bauer committed
104

105
106
107
108
109
        # Scalars may be safely ignored
        # for param in ast.get_parameters():
        #     if not param.is_field_parameter:
        #         # self.set_variable(param.symbol.name, str(param.symbol.dtype), None)
        #         self.sources[param.symbol.name] = [None]
Martin Bauer's avatar
Martin Bauer committed
110
111
112
113
114

        # data type
        self.datatype = list(self.variables.values())[0][0]

        # flops
Martin Bauer's avatar
Martin Bauer committed
115
        operation_count = count_operations_in_ast(inner_loop)
Martin Bauer's avatar
Martin Bauer committed
116
        self._flops = {
Martin Bauer's avatar
Martin Bauer committed
117
118
119
            '+': operation_count['adds'],
            '*': operation_count['muls'],
            '/': operation_count['divs'],
Martin Bauer's avatar
Martin Bauer committed
120
        }
Jan Hönig's avatar
Jan Hönig committed
121
122
        for k in [k for k, v in self._flops.items() if v == 0]:
            del self._flops[k]
Martin Bauer's avatar
Martin Bauer committed
123
124
        self.check()

125
126
127
128
129
130
131
132
133
134
135
        if debug_print:
            from pprint import pprint
            print("-----------------------------  Loop Stack --------------------------")
            pprint(self._loop_stack)
            print("-----------------------------  Sources -----------------------------")
            pprint(self.sources)
            print("-----------------------------  Destinations ------------------------")
            pprint(self.destinations)
            print("-----------------------------  FLOPS -------------------------------")
            pprint(self._flops)

136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
    def get_kernel_header(self, name='pystencils_kernel'):
        file_name = "pystencils_kernel.h"
        file_path = self.get_intermediate_location(file_name, machine_and_compiler_dependent=False)
        lock_mode, lock_fp = self.lock_intermediate(file_path)

        if lock_mode == fcntl.LOCK_SH:
            # use cache
            with open(file_path) as f:
                code = f.read()
        else:  # lock_mode == fcntl.LOCK_EX
            function_signature = generate_c(self.kernel_ast, dialect='c', signature_only=True)

            jinja_context = {
                'function_signature': function_signature,
            }

            env = Environment(loader=PackageLoader('pystencils.kerncraft_coupling'), undefined=StrictUndefined)
            file_header = env.get_template('kernel.h').render(**jinja_context)
            with open(file_path, 'w') as f:
                f.write(file_header)

            fcntl.flock(lock_fp, fcntl.LOCK_SH)  # degrade to shared lock

        return file_path, lock_fp

    def get_kernel_code(self, openmp=False, name='pystencils_kernl'):
Julian Hammer's avatar
Julian Hammer committed
162
163
164
        """
        Generate and return compilable source code.

165
166
167
        Args:
            type_: can be iaca or likwid.
            openmp: if true, openmp code will be generated
168
            as_filename: writes a file with the name as_filename
Julian Hammer's avatar
Julian Hammer committed
169
        """
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
        filename = 'pystencils_kernl'
        if openmp:
            filename += '-omp'
        filename += '.c'
        file_path = self.get_intermediate_location(filename, machine_and_compiler_dependent=False)
        lock_mode, lock_fp = self.lock_intermediate(file_path)

        if lock_mode == fcntl.LOCK_SH:
            # use cache
            with open(file_path) as f:
                code = f.read()
        else:  # lock_mode == fcntl.LOCK_EX
            header_list = get_headers(self.kernel_ast)
            includes = "\n".join(["#include %s" % (include_file,) for include_file in header_list])

            kernel_code = generate_c(self.kernel_ast, dialect='c')

            jinja_context = {
                'includes': includes,
                'kernel_code': kernel_code,
            }

            env = Environment(loader=PackageLoader('pystencils.kerncraft_coupling'), undefined=StrictUndefined)
            file_header = env.get_template('kernel.c').render(**jinja_context)
            with open(file_path, 'w') as f:
                f.write(file_header)

            fcntl.flock(lock_fp, fcntl.LOCK_SH)  # degrade to shared lock

        return file_path, lock_fp
200

Martin Bauer's avatar
Martin Bauer committed
201
202

class KerncraftParameters(DotDict):
Martin Bauer's avatar
Martin Bauer committed
203
204
    def __init__(self, **kwargs):
        super(KerncraftParameters, self).__init__(**kwargs)
Martin Bauer's avatar
Martin Bauer committed
205
206
207
208
209
        self['asm_block'] = 'auto'
        self['asm_increment'] = 0
        self['cores'] = 1
        self['cache_predictor'] = 'SIM'
        self['verbose'] = 0
Jan Hönig's avatar
Jan Hönig committed
210
        self['pointer_increment'] = 'auto'
Jan Hönig's avatar
Jan Hönig committed
211
        self['iterations'] = 10
Julian Hammer's avatar
Julian Hammer committed
212
213
        self['unit'] = 'cy/CL'
        self['ignore_warnings'] = True
214
        self['incore_model'] = 'OSACA'
Jan Hönig's avatar
Jan Hönig committed
215

Martin Bauer's avatar
Martin Bauer committed
216
217
218
219

# ------------------------------------------- Helper functions ---------------------------------------------------------


Martin Bauer's avatar
Martin Bauer committed
220
def search_resolved_field_accesses_in_ast(ast):
Martin Bauer's avatar
Martin Bauer committed
221
222
223
224
225
226
227
228
229
    def visit(node, reads, writes):
        if not isinstance(node, SympyAssignment):
            for a in node.args:
                visit(a, reads, writes)
            return

        for expr, accesses in [(node.lhs, writes), (node.rhs, reads)]:
            accesses.update(expr.atoms(ResolvedFieldAccess))

Martin Bauer's avatar
Martin Bauer committed
230
231
232
    read_accesses = set()
    write_accesses = set()
    visit(ast, read_accesses, write_accesses)
Martin Bauer's avatar
Martin Bauer committed
233
    return read_accesses, write_accesses