-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathloopy.py
More file actions
228 lines (170 loc) · 7.31 KB
/
loopy.py
File metadata and controls
228 lines (170 loc) · 7.31 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
"""
.. currentmodule:: arraycontext
.. autofunction:: make_loopy_program
References
----------
.. class:: InstructionBase
See :class:`loopy.InstructionBase`.
.. class:: SubstitutionRule
See :class:`loopy.SubstitutionRule`.
.. class:: ValueArg
See :class:`loopy.ValueArg`.
.. class:: ArrayArg
See :class:`loopy.ArrayArg`.
.. class:: TemporaryVariable
See :class:`loopy.TemporaryVariable`.
.. class:: EllipsisType
See :data:`types.EllipsisType`.
"""
from __future__ import annotations
__copyright__ = """
Copyright (C) 2020-1 University of Illinois Board of Trustees
"""
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from abc import ABC
from typing import TYPE_CHECKING, ClassVar, cast
import numpy as np
import loopy as lp
from loopy.version import MOST_RECENT_LANGUAGE_VERSION
from pytools import memoize_in
from arraycontext.container.traversal import multimapped_over_array_containers
from arraycontext.fake_numpy import BaseFakeNumpyNamespace
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
from types import EllipsisType
import islpy as isl
from loopy.kernel.data import (
ArrayArg,
SubstitutionRule,
TemporaryVariable,
ValueArg,
)
from loopy.kernel.instruction import InstructionBase
from pytools.tag import ToTagSetConvertible
from arraycontext import ArrayContext
from arraycontext.typing import ArrayOrScalar, ScalarLike
# {{{ loopy
_DEFAULT_LOOPY_OPTIONS = lp.Options(
no_numpy=True,
return_dict=True)
def make_loopy_program(
domains: str | Sequence[str | isl.BasicSet],
statements: str | Sequence[InstructionBase | SubstitutionRule | str],
kernel_data: Sequence[
ValueArg | ArrayArg | TemporaryVariable | EllipsisType | str
] | None = None,
name: str = "mm_actx_kernel",
tags: ToTagSetConvertible = None):
"""Return a :class:`loopy.LoopKernel` suitable for use with
:meth:`ArrayContext.call_loopy`.
"""
if kernel_data is None:
kernel_data = ["..."]
return lp.make_kernel(
domains,
statements,
kernel_data=kernel_data,
options=_DEFAULT_LOOPY_OPTIONS,
default_offset=lp.auto,
name=name,
lang_version=MOST_RECENT_LANGUAGE_VERSION,
tags=tags)
def get_default_entrypoint(t_unit: lp.TranslationUnit) -> lp.LoopKernel:
try:
# main and "kernel callables" branch
return t_unit.default_entrypoint
except AttributeError:
try:
return t_unit.root_kernel
except AttributeError as err:
raise TypeError("unable to find default entry point for loopy "
"translation unit") from err
def _get_scalar_func_loopy_program(
actx: ArrayContext, c_name: str, nargs: int, naxes: int,
) -> lp.TranslationUnit:
@memoize_in(actx, _get_scalar_func_loopy_program)
def get(c_name: str, nargs: int, naxes: int) -> lp.TranslationUnit:
from pymbolic.primitives import Subscript, Variable
var_names = [f"i{i}" for i in range(naxes)]
size_names = [f"n{i}" for i in range(naxes)]
subscript = tuple(Variable(vname) for vname in var_names)
from islpy import make_zero_and_vars
v = make_zero_and_vars(var_names, params=size_names)
domain = v[0].domain()
for vname, sname in zip(var_names, size_names, strict=True):
domain = domain & v[0].le_set(v[vname]) & v[vname].lt_set(v[sname])
domain_bset, = domain.get_basic_sets()
import loopy as lp
from arraycontext.transform_metadata import ElementwiseMapKernelTag
def sub(name: str) -> Variable | Subscript:
return Subscript(Variable(name), subscript) if subscript else Variable(name)
return make_loopy_program(
[domain_bset], [
lp.Assignment(
sub("out"),
Variable(c_name)(*[sub(f"inp{i}") for i in range(nargs)]))
], [
lp.GlobalArg("out", dtype=None, shape=lp.auto, offset=lp.auto)
] + [
lp.GlobalArg(f"inp{i}", dtype=None, shape=lp.auto, offset=lp.auto)
for i in range(nargs)
] + [...],
name=f"actx_special_{c_name}",
tags=(ElementwiseMapKernelTag(),))
return get(c_name, nargs, naxes)
class LoopyBasedFakeNumpyNamespace(BaseFakeNumpyNamespace, ABC):
_numpy_to_c_arc_functions: ClassVar[Mapping[str, str]] = {
"arcsin": "asin",
"arccos": "acos",
"arctan": "atan",
"arctan2": "atan2",
"arcsinh": "asinh",
"arccosh": "acosh",
"arctanh": "atanh",
}
_c_to_numpy_arc_functions: ClassVar[Mapping[str, str]] = {c_name: numpy_name
for numpy_name, c_name in _numpy_to_c_arc_functions.items()}
def __getattr__(self, name: str):
def loopy_implemented_elwise_func(*args: ArrayOrScalar) -> ArrayOrScalar:
if all(np.isscalar(ary) for ary in args):
result = getattr(
np, self._c_to_numpy_arc_functions.get(name, name)
)(*args)
return cast("ScalarLike", result)
actx = self._array_context
prg = _get_scalar_func_loopy_program(actx,
c_name, nargs=len(args), naxes=len(args[0].shape))
outputs = actx.call_loopy(prg,
**{f"inp{i}": arg for i, arg in enumerate(args)})
return outputs["out"]
if name in self._c_to_numpy_arc_functions:
raise RuntimeError(f"'{name}' in ArrayContext.np has been removed: "
f"use '{self._c_to_numpy_arc_functions[name]}' (as in numpy)")
# normalize to C names anyway
c_name = self._numpy_to_c_arc_functions.get(name, name)
# limit which functions we try to hand off to loopy
if (name in self._numpy_math_functions
or name in self._c_to_numpy_arc_functions):
return multimapped_over_array_containers(loopy_implemented_elwise_func)
else:
raise AttributeError(
f"'{type(self._array_context).__name__}.np' object "
f"has no attribute '{name}'")
# }}}
# vim: foldmethod=marker