/
test_frameworks.py
356 lines (269 loc) · 11.4 KB
/
test_frameworks.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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
from __future__ import annotations
import os
import types
import typing as t
import pytest
import bentoml
from bentoml.exceptions import NotFound
from bentoml._internal.models.model import ModelContext
from bentoml._internal.models.model import ModelSignature
from bentoml._internal.runner.runner import Runner
from bentoml._internal.runner.strategy import DefaultStrategy
from bentoml._internal.runner.runner_handle.local import LocalRunnerRef
from .models import FrameworkTestModel
@pytest.fixture(name="saved_model")
def fixture_saved_model(
framework: types.ModuleType, test_model: FrameworkTestModel
) -> bentoml.Model:
return framework.save_model(
test_model.name, test_model.model, **test_model.save_kwargs
)
def test_wrong_module_load_exc(framework: types.ModuleType):
with bentoml.models.create(
"wrong_module",
module=__name__,
context=ModelContext("wrong_module", {"wrong_module": "1.0.0"}),
signatures={},
) as ctx:
tag = ctx.tag
model = ctx
with pytest.raises(
NotFound, match=f"Model {tag} was saved with module {__name__}, "
):
framework.get(tag)
with pytest.raises(
NotFound, match=f"Model {tag} was saved with module {__name__}, "
):
framework.load_model(tag)
with pytest.raises(
NotFound, match=f"Model {tag} was saved with module {__name__}, "
):
framework.load_model(model)
def test_model_options_init(
framework: types.ModuleType, test_model: FrameworkTestModel
):
if not hasattr(framework, "ModelOptions"):
pytest.skip(f"No ModelOptions for framework '{framework.__name__}'")
ModelOptions = framework.ModelOptions
for configuration in test_model.configurations:
from_kwargs = ModelOptions(**configuration.load_kwargs)
from_with_options = from_kwargs.with_options(**configuration.load_kwargs)
assert from_kwargs == from_with_options
assert from_kwargs.to_dict() == from_with_options.to_dict()
from_dict = ModelOptions(**from_kwargs.to_dict())
assert from_dict == from_kwargs
def test_generic_arguments(framework: types.ModuleType, test_model: FrameworkTestModel):
# test that the generic save API works
from sklearn.preprocessing import StandardScaler # type: ignore (bad sklearn types)
scaler: StandardScaler = StandardScaler().fit( # type: ignore (bad sklearn types)
[[4], [3], [7], [8], [4], [3], [9], [6]]
)
assert scaler.mean_[0] == 5.5 # type: ignore (bad sklearn types)
assert scaler.var_[0] == 4.75 # type: ignore (bad sklearn types)
kwargs = test_model.save_kwargs.copy()
if test_model.model_signatures:
kwargs["signatures"] = test_model.model_signatures
meths = list(test_model.model_signatures.keys())
else:
default_meth = "pytest-signature-rjM5"
kwargs["signatures"] = {default_meth: {"batchable": True, "batch_dim": (1, 0)}}
meths = [default_meth]
kwargs["labels"] = {
"pytest-label-N4nr": "pytest-label-value-4mH7",
"pytest-label-7q72": "pytest-label-value-3mDd",
}
kwargs["custom_objects"] = {"pytest-custom-object-r7BU": scaler}
kwargs["metadata"] = {
"pytest-metadata-vSW4": [0, 9, 2],
"pytest-metadata-qJJ3": "Wy5M",
}
bento_model = framework.save_model(
test_model.name,
test_model.model,
**kwargs,
)
for meth in meths:
assert bento_model.info.signatures[meth] == ModelSignature.from_dict(kwargs["signatures"][meth]) # type: ignore
assert bento_model.info.labels == kwargs["labels"]
assert bento_model.custom_objects["pytest-custom-object-r7BU"].mean_[0] == 5.5
assert bento_model.custom_objects["pytest-custom-object-r7BU"].var_[0] == 4.75
assert bento_model.info.metadata == kwargs["metadata"]
def test_get(
framework: types.ModuleType,
test_model: FrameworkTestModel,
saved_model: bentoml.Model,
):
# test that the generic get API works
bento_model = framework.get(saved_model.tag)
assert bento_model == saved_model
assert bento_model.info.name == test_model.name
bento_model_from_str = framework.get(str(saved_model.tag))
assert bento_model == bento_model_from_str
def test_get_runnable(
framework: types.ModuleType,
saved_model: bentoml.Model,
):
runnable = framework.get_runnable(saved_model)
assert isinstance(
runnable, t.Type
), "get_runnable for {bento_model.info.name} does not return a type"
assert issubclass(
runnable, bentoml.Runnable
), "get_runnable for {bento_model.info.name} doesn't return a subclass of bentoml.Runnable"
assert (
len(runnable.bentoml_runnable_methods__) > 0
), "get_runnable for {bento_model.info.name} gives a runnable with no methods"
def test_load(
framework: types.ModuleType,
test_model: FrameworkTestModel,
saved_model: bentoml.Model,
):
for configuration in test_model.configurations:
model = framework.load_model(saved_model)
configuration.check_model(model, {})
def test_runnable(
test_model: FrameworkTestModel,
saved_model: bentoml.Model,
):
for config in test_model.configurations:
runner = saved_model.with_options(**config.load_kwargs).to_runner()
runner.init_local()
runner_handle = t.cast(LocalRunnerRef, runner._runner_handle)
runnable = runner_handle._runnable
config.check_runnable(runnable, {})
runner.destroy()
def test_runner_batching(
test_model: FrameworkTestModel,
saved_model: bentoml.Model,
):
from bentoml._internal.runner.utils import Params
from bentoml._internal.runner.utils import payload_paramss_to_batch_params
from bentoml._internal.runner.container import AutoContainer
ran_tests = False
for config in test_model.configurations:
runner = saved_model.with_options(**config.load_kwargs).to_runner()
runner.init_local()
for meth, inputs in config.test_inputs.items():
if not getattr(runner, meth).config.batchable:
continue
if len(inputs) < 2:
continue
ran_tests = True
batch_dim = getattr(runner, meth).config.batch_dim
paramss = [
Params(*inp.input_args, **inp.input_kwargs).map(
# pylint: disable=cell-var-from-loop # lambda used before loop continues
lambda arg: AutoContainer.to_payload(arg, batch_dim=batch_dim[0])
)
for inp in inputs
]
params, indices = payload_paramss_to_batch_params(paramss, batch_dim[0])
batch_res = getattr(runner, meth).run(*params.args, **params.kwargs)
outps = AutoContainer.batch_to_payloads(batch_res, indices, batch_dim[1])
for i, outp in enumerate(outps):
inputs[i].check_output(AutoContainer.from_payload(outp))
runner.destroy()
if not ran_tests:
pytest.skip(
"skipping batching tests because no configuration had multiple test inputs"
)
def test_runner_cpu_multi_threading(
framework: types.ModuleType,
test_model: FrameworkTestModel,
saved_model: bentoml.Model,
):
resource_cfg = {"cpu": 2.0}
ran_tests = False
for config in test_model.configurations:
model_with_options = saved_model.with_options(**config.load_kwargs)
runnable: t.Type[bentoml.Runnable] = framework.get_runnable(model_with_options)
if "cpu" not in runnable.SUPPORTED_RESOURCES:
continue
ran_tests = True
runner = Runner(runnable)
for meth, inputs in config.test_inputs.items():
strategy = DefaultStrategy()
os.environ.update(strategy.get_worker_env(runnable, resource_cfg, 0))
runner.init_local()
runner_handle = t.cast(LocalRunnerRef, runner._runner_handle)
runnable = runner_handle._runnable
config.check_runnable(runnable, resource_cfg)
if (
hasattr(runnable, "model") and runnable.model is not None
): # TODO: add a get_model to test models
config.check_model(runnable.model, resource_cfg)
for inp in inputs:
outp = getattr(runner, meth).run(*inp.input_args, **inp.input_kwargs)
inp.check_output(outp)
runner.destroy()
if not ran_tests:
pytest.skip(
f"no configurations for model '{test_model.name}' supported multiple CPU threads"
)
def test_runner_cpu(
framework: types.ModuleType,
test_model: FrameworkTestModel,
saved_model: bentoml.Model,
):
resource_cfg = {"cpu": 1.0}
ran_tests = False
for config in test_model.configurations:
model_with_options = saved_model.with_options(**config.load_kwargs)
runnable: t.Type[bentoml.Runnable] = framework.get_runnable(model_with_options)
if not runnable.SUPPORTS_CPU_MULTI_THREADING:
continue
ran_tests = True
runner = Runner(runnable)
for meth, inputs in config.test_inputs.items():
strategy = DefaultStrategy()
os.environ.update(strategy.get_worker_env(runnable, resource_cfg, 0))
runner.init_local()
runner_handle = t.cast(LocalRunnerRef, runner._runner_handle)
runnable = runner_handle._runnable
config.check_runnable(runnable, resource_cfg)
if (
hasattr(runnable, "model") and runnable.model is not None
): # TODO: add a get_model to test models
config.check_model(runnable.model, resource_cfg)
for inp in inputs:
outp = getattr(runner, meth).run(*inp.input_args, **inp.input_kwargs)
inp.check_output(outp)
runner.destroy()
if not ran_tests:
pytest.skip(
f"no configurations for model '{test_model.name}' supported multiple CPU threads"
)
@pytest.mark.requires_gpus
def test_runner_nvidia_gpu(
framework: types.ModuleType,
test_model: FrameworkTestModel,
saved_model: bentoml.Model,
):
resource_cfg = {"nvidia.com/gpu": 1}
ran_tests = False
for config in test_model.configurations:
model_with_options = saved_model.with_options(**config.load_kwargs)
runnable: t.Type[bentoml.Runnable] = framework.get_runnable(model_with_options)
if "nvidia.com/gpu" not in runnable.SUPPORTED_RESOURCES:
continue
ran_tests = True
runner = Runner(runnable)
for meth, inputs in config.test_inputs.items():
strategy = DefaultStrategy()
os.environ.update(strategy.get_worker_env(runnable, resource_cfg, 0))
runner.init_local()
runner_handle = t.cast(LocalRunnerRef, runner._runner_handle)
runnable = runner_handle._runnable
config.check_runnable(runnable, resource_cfg)
if (
hasattr(runnable, "model") and runnable.model is not None
): # TODO: add a get_model to test models
config.check_model(runnable.model, resource_cfg)
for inp in inputs:
outp = getattr(runner, meth).run(*inp.input_args, **inp.input_kwargs)
inp.check_output(outp)
runner.destroy()
if not ran_tests:
pytest.skip(
f"no configurations for model '{test_model.name}' supported running on Nvidia GPU"
)