forked from ivy-llc/ivy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
multiversion_frontend_test.py
287 lines (248 loc) · 9.09 KB
/
multiversion_frontend_test.py
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
from ivy_tests import config
from ivy_tests.test_ivy.helpers.structs import FrontendMethodData
import sys
import jsonpickle
import importlib
from ivy_tests.test_ivy.helpers.testing_helpers import (
_import_fn,
_get_supported_devices_dtypes,
)
def available_frameworks():
available_frameworks_lis = ["numpy", "jax", "tensorflow", "torch"]
try:
import jax
assert jax, "jax is imported to see if the user has it installed"
except ImportError:
available_frameworks_lis.remove("jax")
try:
import tensorflow as tf
assert tf, "tensorflow is imported to see if the user has it installed"
except ImportError:
available_frameworks_lis.remove("tensorflow")
try:
import torch
assert torch, "torch is imported to see if the user has it installed"
except ImportError:
available_frameworks_lis.remove("torch")
return available_frameworks_lis
def convtrue(argument):
"""Convert NativeClass in argument to true framework counter part"""
if isinstance(argument, NativeClass):
return argument._native_class
return argument
class NativeClass:
"""
An empty class to represent a class that only exist in a specific framework.
Attributes
----------
_native_class : class reference
A reference to the framework-specific class.
"""
def __init__(self, native_class):
"""
Constructs the native class object.
Parameters
----------
native_class : class reference
A reperence to the framework-specific class being represented.
"""
self._native_class = native_class
def _get_fn_dtypes(framework, fn_tree, device=None, kind="valid"):
callable_fn, fn_name, fn_mod = _import_fn(fn_tree)
supported_device_dtypes = _get_supported_devices_dtypes(fn_name, fn_mod)
return supported_device_dtypes[framework][device][kind]
def _get_type_dict(framework, fn_tree, device=None, kind="valid"):
if kind == "valid":
return framework.valid_dtypes
elif kind == "numeric":
return framework.valid_numeric_dtypes
elif kind == "integer":
return framework.valid_int_dtypes
elif kind == "float":
return framework.valid_float_dtypes
elif kind == "unsigned":
return framework.valid_int_dtypes
elif kind == "signed_integer":
return tuple(
set(framework.valid_int_dtypes).difference(framework.valid_uint_dtypes)
)
elif kind == "complex":
return framework.valid_complex_dtypes
elif kind == "real_and_complex":
return tuple(
set(framework.valid_numeric_dtypes).union(framework.valid_complex_dtypes)
)
elif kind == "float_and_complex":
return tuple(
set(framework.valid_float_dtypes).union(framework.valid_complex_dtypes)
)
elif kind == "bool":
return tuple(
set(framework.valid_dtypes).difference(framework.valid_numeric_dtypes)
)
else:
raise RuntimeError("{} is an unknown kind!".format(kind))
def dtype_handler(framework):
z = input()
retrieval_fn = globals()[z]
z = input()
kind = z
z = input()
device = z
z = input()
fn_tree = z
if retrieval_fn.__name__ == "_get_type_dict":
framework = importlib.import_module("ivy.functional.backends." + framework)
dtypes = retrieval_fn(framework, fn_tree, device, kind)
dtypes = jsonpickle.dumps(dtypes)
print(dtypes)
def test_frontend_method():
z = input()
pickle_dict = jsonpickle.loads(z)
z = pickle_dict
(
args_constructor_np,
kwargs_constructor_np,
args_method_np,
kwargs_method_np,
frontend_method_data,
) = (z["a"], z["b"], z["c"], z["d"], z["e"])
frontend_method_data = FrontendMethodData(
ivy_init_module=frontend_method_data.ivy_init_module,
framework_init_module=importlib.import_module(
frontend_method_data.framework_init_module
),
init_name=frontend_method_data.init_name,
method_name=frontend_method_data.method_name,
)
args_constructor_frontend = ivy.nested_map(
args_constructor_np,
lambda x: ivy.native_array(x) if isinstance(x, numpy.ndarray) else x,
shallow=False,
)
kwargs_constructor_frontend = ivy.nested_map(
kwargs_constructor_np,
lambda x: ivy.native_array(x) if isinstance(x, numpy.ndarray) else x,
shallow=False,
)
args_method_frontend = ivy.nested_map(
args_method_np,
lambda x: ivy.native_array(x)
if isinstance(x, numpy.ndarray)
else ivy.as_native_dtype(x)
if isinstance(x, ivy.Dtype)
else ivy.as_native_dev(x)
if isinstance(x, ivy.Device)
else x,
shallow=False,
)
kwargs_method_frontend = ivy.nested_map(
kwargs_method_np,
lambda x: ivy.native_array(x) if isinstance(x, numpy.ndarray) else x,
shallow=False,
)
# change ivy dtypes to native dtypes
if "dtype" in kwargs_method_frontend:
kwargs_method_frontend["dtype"] = ivy.as_native_dtype(
kwargs_method_frontend["dtype"]
)
# change ivy device to native devices
if "device" in kwargs_method_frontend:
kwargs_method_frontend["device"] = ivy.as_native_dev(
kwargs_method_frontend["device"]
)
frontend_creation_fn = getattr(
frontend_method_data.framework_init_module, frontend_method_data.init_name
)
ins_gt = frontend_creation_fn(
*args_constructor_frontend, **kwargs_constructor_frontend
)
frontend_ret = ins_gt.__getattribute__(frontend_method_data.method_name)(
*args_method_frontend, **kwargs_method_frontend
)
try:
tensorflow = importlib.import_module("tensorflow")
except:
tensorflow = None
if ivy.current_backend_str() == "tensorflow" and isinstance(
frontend_ret, getattr(tensorflow, "TensorShape", None)
):
frontend_ret_np_flat = [numpy.asarray(frontend_ret, dtype=numpy.int32)]
ret = jsonpickle.dumps({"a": 0, "b": frontend_ret_np_flat})
print(ret)
elif ivy.isscalar(frontend_ret):
frontend_ret_np_flat = [numpy.asarray(frontend_ret)]
ret = jsonpickle.dumps({"a": 0, "b": frontend_ret_np_flat})
print(ret)
else:
ret = jsonpickle.dumps({"a": 1, "b": ivy.to_numpy(frontend_ret)})
print(ret)
if __name__ == "__main__":
arg_lis = sys.argv
fw_lis = []
for i in arg_lis[1:]:
if i.split("/")[0] == "jax":
fw_lis.append(i.split("/")[0] + "/" + i.split("/")[1])
fw_lis.append(i.split("/")[2] + "/" + i.split("/")[3])
else:
fw_lis.append(i)
config.allow_global_framework_imports(fw=fw_lis)
j = 1
import ivy
# ivy.bfloat16
ivy.set_backend(arg_lis[2].split("/")[0])
import numpy
while j:
try:
z = input()
if z == "1":
dtype_handler(arg_lis[2].split("/")[0])
continue
if z == "2":
test_frontend_method()
continue
pickle_dict = jsonpickle.loads(z)
frontend_fw = input()
frontend_fw = importlib.import_module(frontend_fw)
func = input()
args_np, kwargs_np = pickle_dict["a"], pickle_dict["b"]
args_frontend = ivy.nested_map(
args_np,
lambda x: ivy.native_array(x)
if isinstance(x, numpy.ndarray)
else ivy.as_native_dtype(x)
if isinstance(x, ivy.Dtype)
else x,
shallow=False,
)
kwargs_frontend = ivy.nested_map(
kwargs_np,
lambda x: ivy.native_array(x) if isinstance(x, numpy.ndarray) else x,
shallow=False,
)
# change ivy dtypes to native dtypes
if "dtype" in kwargs_frontend:
kwargs_frontend["dtype"] = ivy.as_native_dtype(kwargs_frontend["dtype"])
# change ivy device to native devices
if "device" in kwargs_frontend:
kwargs_frontend["device"] = ivy.as_native_dev(kwargs_frontend["device"])
# check and replace the NativeClass objects in arguments
# with true counterparts
args_frontend = ivy.nested_map(
args_frontend, fn=convtrue, include_derived=True, max_depth=10
)
kwargs_frontend = ivy.nested_map(
kwargs_frontend, fn=convtrue, include_derived=True, max_depth=10
)
frontend_ret = frontend_fw.__dict__[func](*args_frontend, **kwargs_frontend)
if isinstance(frontend_ret, tuple) or isinstance(frontend_ret, list):
frontend_ret = ivy.nested_map(frontend_ret, ivy.to_numpy)
else:
frontend_ret = ivy.to_numpy(frontend_ret)
frontend_ret = jsonpickle.dumps(frontend_ret)
print(frontend_ret)
except EOFError:
continue
except Exception as e:
print(frontend_ret.shape)
raise e