-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathequation.py
More file actions
329 lines (258 loc) · 10.5 KB
/
equation.py
File metadata and controls
329 lines (258 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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
162
163
164
165
166
167
168
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
from functools import cached_property
import numpy as np
import sympy
from devito.ir.equations.algorithms import dimension_sort, lower_exprs
from devito.finite_differences.differentiable import diff2sympy
from devito.ir.support import (GuardFactor, Interval, IntervalGroup, IterationSpace,
Stencil, detect_io, detect_accesses)
from devito.symbolics import IntDiv, limits_mapper, uxreplace
from devito.tools import Pickable, Tag, frozendict
from devito.types import (Eq, Inc, ReduceMax, ReduceMin,
relational_min)
from devito.types.equation import PetscEq
__all__ = ['LoweredEq', 'ClusterizedEq', 'DummyEq', 'OpInc', 'OpMin', 'OpMax',
'identity_mapper', 'OpPetsc']
class IREq(sympy.Eq, Pickable):
__rargs__ = ('lhs', 'rhs')
__rkwargs__ = ('ispace', 'conditionals', 'implicit_dims', 'operation')
@property
def is_Scalar(self):
return self.lhs.is_Symbol
is_scalar = is_Scalar
@property
def ispace(self):
return self._ispace
@cached_property
def dimensions(self):
return set(self.ispace.dimensions)
@property
def implicit_dims(self):
return self._implicit_dims
@cached_property
def conditionals(self):
return self._conditionals or frozendict()
@property
def directions(self):
return self.ispace.directions
@property
def dtype(self):
return self.lhs.dtype
@property
def state(self):
return {i: getattr(self, i) for i in self.__rkwargs__}
@property
def operation(self):
return self._operation
@property
def is_Reduction(self):
return self.operation in (OpInc, OpMin, OpMax)
@property
def is_Increment(self):
return self.operation is OpInc
def apply(self, func):
"""
Apply a callable to `self` and each expr-like attribute carried by `self`,
thus triggering a reconstruction.
"""
args = [func(self.lhs), func(self.rhs)]
kwargs = dict(self.state)
conditionals = {k: func(v) for k, v in self.conditionals.items()}
kwargs['conditionals'] = frozendict(conditionals)
return self.func(*args, **kwargs)
def __repr__(self):
if not self.is_Reduction:
return super().__repr__()
elif self.operation is OpInc:
return '%s += %s' % (self.lhs, self.rhs)
else:
return '%s = %s(%s)' % (self.lhs, self.operation, self.rhs)
# Pickling support
__reduce_ex__ = Pickable.__reduce_ex__
class Operation(Tag):
"""
Special operation performed by an Eq.
"""
@classmethod
def detect(cls, expr):
reduction_mapper = {
Inc: OpInc,
ReduceMax: OpMax,
ReduceMin: OpMin,
PetscEq: OpPetsc
}
for expr_type, op in reduction_mapper.items():
if isinstance(expr, expr_type):
return op
# NOTE: in the future we might want to track down other kinds
# of operations here (e.g., memcpy). However, we don't care for
# now, since they would remain unexploited inside the compiler
return None
OpInc = Operation('+')
OpMax = Operation('max')
OpMin = Operation('min')
OpPetsc = Operation('solve')
identity_mapper = {
np.int32: {OpInc: sympy.S.Zero,
OpMax: limits_mapper[np.int32].min,
OpMin: limits_mapper[np.int32].max},
np.int64: {OpInc: sympy.S.Zero,
OpMax: limits_mapper[np.int64].min,
OpMin: limits_mapper[np.int64].max},
np.float32: {OpInc: sympy.S.Zero,
OpMax: limits_mapper[np.float32].min,
OpMin: limits_mapper[np.float32].max},
np.float64: {OpInc: sympy.S.Zero,
OpMax: limits_mapper[np.float64].min,
OpMin: limits_mapper[np.float64].max},
}
class LoweredEq(IREq):
"""
LoweredEq(devito.Eq)
LoweredEq(devito.LoweredEq, **kwargs)
LoweredEq(lhs, rhs, **kwargs)
A SymPy equation enriched with metadata such as an IterationSpace.
When created as `LoweredEq(devito.Eq)`, the iteration space is automatically
derived from analysis of `expr`.
When created as `LoweredEq(devito.LoweredEq, **kwargs)`, the keyword
arguments can be anything that appears in `LoweredEq.__rkwargs__`
(e.g., ispace).
When created as `LoweredEq(lhs, rhs, **kwargs)`, *all* keywords in
`LoweredEq.__rkwargs__` must appear in `kwargs`.
"""
__rkwargs__ = IREq.__rkwargs__ + ('reads', 'writes')
def __new__(cls, *args, **kwargs):
if len(args) == 1 and isinstance(args[0], LoweredEq):
# origin: LoweredEq(devito.LoweredEq, **kwargs)
input_expr = args[0]
expr = sympy.Eq.__new__(cls, *input_expr.args, evaluate=False)
for i in cls.__rkwargs__:
setattr(expr, '_%s' % i, kwargs.get(i) or getattr(input_expr, i))
return expr
elif len(args) == 1 and isinstance(args[0], Eq):
# origin: LoweredEq(devito.Eq)
input_expr = expr = args[0]
elif len(args) == 2:
expr = sympy.Eq.__new__(cls, *args, evaluate=False)
for i in cls.__rkwargs__:
setattr(expr, '_%s' % i, kwargs.pop(i))
return expr
else:
raise ValueError("Cannot construct LoweredEq from args=%s "
"and kwargs=%s" % (str(args), str(kwargs)))
# Well-defined dimension ordering
ordering = dimension_sort(expr)
# Analyze the expression
accesses = detect_accesses(expr)
dimensions = Stencil.union(*accesses.values())
# Separate out the SubIterators from the main iteration Dimensions, that
# is those which define an actual iteration space
iterators = {}
for d in dimensions:
if d.is_SubIterator:
iterators.setdefault(d.root, set()).add(d)
elif d.is_Conditional:
# Use `parent`, and `root`, because a ConditionalDimension may
# have a SubDimension as parent
iterators.setdefault(d.parent, set())
elif not d.is_Stencil:
iterators.setdefault(d, set())
# Construct the IterationSpace
intervals = IntervalGroup([Interval(d) for d in iterators],
relations=ordering.relations, mode='partial')
ispace = IterationSpace(intervals, iterators)
# Construct the conditionals and replace the ConditionalDimensions in `expr`
conditionals = {}
for d in ordering:
if not d.is_Conditional:
continue
if d.condition is None:
conditionals[d] = GuardFactor(d)
else:
cond = diff2sympy(lower_exprs(d.condition))
if d._factor is not None:
cond = sympy.And(cond, GuardFactor(d))
conditionals[d] = cond
# Replace dimension with index
index = d.index
if d.condition is not None and d in expr.free_symbols:
index = index - relational_min(d.condition, d.parent)
expr = uxreplace(expr, {d: IntDiv(index, d.symbolic_factor)})
conditionals = frozendict(conditionals)
# Lower all Differentiable operations into SymPy operations
rhs = diff2sympy(expr.rhs)
# Finally create the LoweredEq with all metadata attached
expr = super().__new__(cls, expr.lhs, rhs, evaluate=False)
expr._ispace = ispace
expr._conditionals = conditionals
expr._reads, expr._writes = detect_io(expr)
expr._implicit_dims = input_expr.implicit_dims
expr._operation = Operation.detect(input_expr)
return expr
@property
def reads(self):
return self._reads
@property
def writes(self):
return self._writes
def xreplace(self, rules):
return LoweredEq(self.lhs.xreplace(rules), self.rhs.xreplace(rules), **self.state)
def func(self, *args):
return self._rebuild(*args, evaluate=False)
class ClusterizedEq(IREq):
"""
ClusterizedEq(devito.IREq, **kwargs)
ClusterizedEq(lhs, rhs, **kwargs)
A SymPy equation enriched with metadata such as an IterationSpace.
There are two main differences between a LoweredEq and a
ClusterizedEq:
* To construct a ClusterizedEq, the IterationSpace must be provided
by the caller, whie in a LoweredEq the IterationSpace is derived
by analysis of the input.
* A ClusterizedEq is "frozen", meaning that any call to e.g. `xreplace`
will not trigger re-evaluation (e.g., mathematical simplification)
of the expression.
These two properties make a ClusterizedEq suitable for use in a Cluster.
"""
def __new__(cls, *args, **kwargs):
if len(args) == 1:
# origin: ClusterizedEq(expr, **kwargs)
input_expr = args[0]
expr = sympy.Eq.__new__(cls, *input_expr.args, evaluate=False)
if isinstance(input_expr, IREq):
for i in cls.__rkwargs__:
try:
v = kwargs[i]
except KeyError:
v = getattr(input_expr, i, None)
setattr(expr, '_%s' % i, v)
else:
expr._ispace = kwargs['ispace']
expr._conditionals = kwargs.get('conditionals', frozendict())
expr._implicit_dims = input_expr.implicit_dims
expr._operation = Operation.detect(input_expr)
elif len(args) == 2:
# origin: ClusterizedEq(lhs, rhs, **kwargs)
expr = sympy.Eq.__new__(cls, *args, evaluate=False)
for i in cls.__rkwargs__:
setattr(expr, '_%s' % i, kwargs.pop(i))
else:
raise ValueError("Cannot construct ClusterizedEq from args=%s "
"and kwargs=%s" % (str(args), str(kwargs)))
return expr
func = IREq._rebuild
class DummyEq(ClusterizedEq):
"""
DummyEq(expr)
DummyEq(lhs, rhs)
A special ClusterizedEq with a void iteration space.
"""
def __new__(cls, *args, **kwargs):
if len(args) == 1:
input_expr = args[0]
assert isinstance(input_expr, Eq)
obj = LoweredEq(input_expr)
elif len(args) == 2:
obj = LoweredEq(Eq(*args, evaluate=False))
else:
raise ValueError("Cannot construct DummyEq from args=%s" % str(args))
return ClusterizedEq.__new__(cls, obj, ispace=obj.ispace)