forked from pybind/python_example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.py
More file actions
153 lines (117 loc) · 4.72 KB
/
Copy pathcore.py
File metadata and controls
153 lines (117 loc) · 4.72 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
# Copyright 2020 Yong Tang. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""foo"""
import os
import sys
import ast
import inspect
import textwrap
if "FOO_BINDIR" in os.environ:
path = os.path.abspath(
os.path.join(os.environ["FOO_BINDIR"], "foo", "core", "python", "pybind")
)
else:
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pybind")
sys.path.insert(0, path)
import pybind_mlir
check = pybind_mlir.check
class MLIRNodeVisitor(ast.NodeVisitor):
def __init__(self, builder):
self.builder = builder
def visit_FunctionDef(self, node: ast.FunctionDef):
location = self.builder.getFileLineColLoc("mlir", node.lineno, node.col_offset)
inputs = [arg.arg for arg in node.args.args]
function = pybind_mlir.FuncOp.create(
location,
node.name,
pybind_mlir.FunctionType.get(
[self.builder.getF64Type() for _ in inputs],
[],
self.builder.getContext(),
),
)
entry_block = function.addEntryBlock()
self.symbols = dict(zip(inputs, entry_block.getArguments()))
self.builder.setInsertionPointToStart(entry_block)
items = [self.visit(e) for e in node.body]
if len(items) == 0 or not isinstance(items[-1], pybind_mlir.ReturnOp):
self.builder.createReturnOp(location, [])
else:
return_op = items[-1]
function.setType(
pybind_mlir.FunctionType.get(
[self.builder.getF64Type() for _ in inputs],
return_op.getOperandTypes(),
self.builder.getContext(),
)
)
return function
def visit_Return(self, node: ast.Return):
location = self.builder.getFileLineColLoc("mlir", node.lineno, node.col_offset)
value = None if node.value is None else [self.visit(node.value)]
return self.builder.createReturnOp(location, value)
def visit_BinOp(self, node: ast.BinOp):
location = self.builder.getFileLineColLoc("mlir", node.lineno, node.col_offset)
assert type(node.op).__name__.lower() == "add"
right = self.visit(node.right) # .getOperation().getResults()[0]
left = self.visit(node.left) # .getOperation().getResults()[0]
return self.builder.createAddFOp(location, left, right)
def visit_Name(self, node: ast.Num):
location = self.builder.getFileLineColLoc("mlir", node.lineno, node.col_offset)
assert node.id in self.symbols
return self.symbols[node.id]
def visit_Num(self, node: ast.Num):
location = self.builder.getFileLineColLoc("mlir", node.lineno, node.col_offset)
return self.builder.createConstantOp(
location, self.builder.getF64FloatAttr(node.n)
)
class Function:
"""Function"""
def __init__(self, function, signature=None):
self._function = function
self._signature = signature
code = textwrap.dedent(inspect.getsource(function))
tree = ast.parse(code)
assert isinstance(tree, ast.Module)
assert len(tree.body) == 1
assert isinstance(tree.body[0], ast.FunctionDef)
node = tree.body[0]
context = pybind_mlir.MLIRContext()
builder = pybind_mlir.OpBuilder(context)
func = MLIRNodeVisitor(builder).visit(node)
module = pybind_mlir.ModuleOp.create(builder.getUnknownLoc())
module.push_back(func)
self._context = context
self._module = module
self._mlir = str(module)
module.emit(context)
def __call__(self, *args, **kwargs):
return self._module.run(self._function.__name__, [*args])
@property
def __doc__(self):
return self._function.__doc__
@property
def __name__(self):
return self._function.__name__
@property
def signature(self):
return self._signature
@property
def mlir(self):
return self._mlir
def jit(signature_or_function=None):
def _jit(function):
return Function(function)
return Function(signature_or_function) if callable(signature_or_function) else _jit