-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_extra_mlflow_variants.py
More file actions
346 lines (265 loc) · 12.7 KB
/
Copy pathtest_extra_mlflow_variants.py
File metadata and controls
346 lines (265 loc) · 12.7 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
"""Broader end-to-end coverage for ``package_mlflow_model``.
Each test trains/saves a tiny deterministic MLflow model exercising a specific
input mode (json/custom dict output, tensor, passthrough, params), packages it
with the converter, loads via ``fnnx.Runtime``, and asserts a round-trip
behavior matching direct invocation through MLflow.
Models-from-code is used for the custom-PythonModel scenarios (json / params)
because the class must be loadable in a fresh process at warmup time without
relying on test-module import paths.
"""
from __future__ import annotations
import json
import os
import tarfile
import tempfile
import textwrap
import unittest
from unittest import mock
import pytest
pytest.importorskip("mlflow")
pytest.importorskip("sklearn")
pytest.importorskip("pandas")
# ---------------------------------------------------------------------------
# Custom PythonModel (json input_mode, dict output)
# ---------------------------------------------------------------------------
_DICT_MODEL_SCRIPT = textwrap.dedent(
"""
import mlflow
class DictModel(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input, params=None):
# model_input arrives as a list of records (pyfunc serialization).
if hasattr(model_input, "to_dict"):
records = model_input.to_dict(orient="records")
else:
records = model_input
first = records[0] if records else {}
items = first.get("items", []) if isinstance(first, dict) else []
return {"count": len(items), "items": list(items)}
mlflow.models.set_model(DictModel())
"""
).lstrip()
def _save_dict_model(tmp: str) -> str:
"""Save a custom PythonModel (models-from-code) with a nested ColSpec signature."""
import mlflow # type: ignore[import-not-found]
from mlflow.models import ModelSignature # type: ignore[import-not-found]
from mlflow.types import DataType # type: ignore[import-not-found]
from mlflow.types.schema import Array, ColSpec, Schema # type: ignore[import-not-found]
script_path = os.path.join(tmp, "dict_model_script.py")
with open(script_path, "w") as f:
f.write(_DICT_MODEL_SCRIPT)
signature = ModelSignature(
inputs=Schema([ColSpec(name="items", type=Array(DataType.string))]),
outputs=Schema([ColSpec(type=DataType.string)]),
)
model_dir = os.path.join(tmp, "dict_model")
mlflow.pyfunc.save_model( # type: ignore[attr-defined]
path=model_dir,
python_model=script_path,
signature=signature,
)
return model_dir
class TestCustomPythonModelJsonMode(unittest.TestCase):
"""Nested-ColSpec signature → json input_mode; dict output is normalized."""
def test_round_trip(self):
from fnnx.extras.mlflow import package_mlflow_model
from fnnx.runtime import Runtime
with tempfile.TemporaryDirectory() as tmp:
model_dir = _save_dict_model(tmp)
out = os.path.join(tmp, "dict.fnnx")
package_mlflow_model(model_dir, out)
with tarfile.open(out, "r") as tar:
variant_config = json.loads(
tar.extractfile("variant_config.json").read().decode() # type: ignore[union-attr]
)
manifest = json.loads(
tar.extractfile("manifest.json").read().decode() # type: ignore[union-attr]
)
cfg = variant_config["extra_values"]["fnnx_mlflow"]
self.assertEqual(cfg["input_mode"], "json")
self.assertEqual(len(manifest["inputs"]), 1)
self.assertEqual(manifest["inputs"][0]["name"], "data")
self.assertEqual(manifest["inputs"][0]["content_type"], "JSON")
self.assertEqual(manifest["inputs"][0]["dtype"], "ext::mlflow::input")
rt = Runtime(out)
records = [{"items": ["a", "b", "c"]}]
result = rt.compute({"data": records}, {})
self.assertIn("predictions", result)
predictions = result["predictions"]
self.assertEqual(predictions, {"count": 3, "items": ["a", "b", "c"]})
# ---------------------------------------------------------------------------
# TensorSpec signature → tensor input_mode
# ---------------------------------------------------------------------------
def _save_tensor_model(tmp: str):
"""Train a tiny regressor and save it with a single unnamed TensorSpec signature."""
import mlflow # type: ignore[import-not-found]
import numpy as np
from mlflow.models import ModelSignature # type: ignore[import-not-found]
from mlflow.types.schema import Schema, TensorSpec # type: ignore[import-not-found]
from sklearn.ensemble import RandomForestRegressor # type: ignore[import-not-found]
rng = np.random.default_rng(0)
X = rng.random((20, 4)).astype(np.float32)
y = rng.random(20).astype(np.float64)
model = RandomForestRegressor(n_estimators=3, random_state=0)
model.fit(X, y)
signature = ModelSignature(
inputs=Schema([TensorSpec(np.dtype("float32"), [-1, 4])]),
outputs=Schema([TensorSpec(np.dtype("float64"), [-1])]),
)
model_dir = os.path.join(tmp, "tensor_model")
mlflow.sklearn.save_model(model, model_dir, signature=signature) # type: ignore[attr-defined]
return model_dir, model, X
class TestTensorMode(unittest.TestCase):
def test_unnamed_tensor_round_trip(self):
from fnnx.extras.mlflow import package_mlflow_model
from fnnx.runtime import Runtime
with tempfile.TemporaryDirectory() as tmp:
model_dir, model, X = _save_tensor_model(tmp)
out = os.path.join(tmp, "tensor.fnnx")
package_mlflow_model(model_dir, out)
with tarfile.open(out, "r") as tar:
variant_config = json.loads(
tar.extractfile("variant_config.json").read().decode() # type: ignore[union-attr]
)
manifest = json.loads(
tar.extractfile("manifest.json").read().decode() # type: ignore[union-attr]
)
cfg = variant_config["extra_values"]["fnnx_mlflow"]
self.assertEqual(cfg["input_mode"], "tensor")
self.assertEqual(cfg["tensor_names"], ["__single__"])
self.assertEqual(len(manifest["inputs"]), 1)
spec = manifest["inputs"][0]
self.assertEqual(spec["name"], "input")
self.assertEqual(spec["content_type"], "NDJSON")
self.assertEqual(spec["dtype"], "Array[float32]")
self.assertEqual(spec["shape"], ["batch", 4])
rt = Runtime(out)
sample = X[:5]
result = rt.compute({"input": sample}, {})
self.assertIn("predictions", result)
expected = model.predict(sample).tolist()
self.assertEqual(result["predictions"], expected)
# ---------------------------------------------------------------------------
# No-signature model → passthrough input_mode (with warning)
# ---------------------------------------------------------------------------
def _save_no_signature_model(tmp: str):
import mlflow # type: ignore[import-not-found]
import pandas as pd
from sklearn.ensemble import RandomForestClassifier # type: ignore[import-not-found]
x = pd.DataFrame(
{
"a": [0.0, 1.0, 2.0, 3.0],
"b": [3.0, 2.0, 1.0, 0.0],
}
)
y = [0, 1, 0, 1]
model = RandomForestClassifier(n_estimators=3, random_state=0)
model.fit(x, y)
model_dir = os.path.join(tmp, "no_sig_model")
mlflow.sklearn.save_model(model, model_dir) # type: ignore[attr-defined]
return model_dir, model, x
class TestPassthroughMode(unittest.TestCase):
def test_round_trip_and_warning(self):
from fnnx.extras.mlflow import package_mlflow_model
from fnnx.runtime import Runtime
with tempfile.TemporaryDirectory() as tmp:
model_dir, model, x = _save_no_signature_model(tmp)
out = os.path.join(tmp, "passthrough.fnnx")
with mock.patch("fnnx.extras.mlflow.console.warn") as warn_mock:
package_mlflow_model(model_dir, out)
with tarfile.open(out, "r") as tar:
variant_config = json.loads(
tar.extractfile("variant_config.json").read().decode() # type: ignore[union-attr]
)
manifest = json.loads(
tar.extractfile("manifest.json").read().decode() # type: ignore[union-attr]
)
cfg = variant_config["extra_values"]["fnnx_mlflow"]
self.assertEqual(cfg["input_mode"], "passthrough")
self.assertEqual(len(manifest["inputs"]), 1)
self.assertEqual(manifest["inputs"][0]["name"], "data")
self.assertEqual(manifest["inputs"][0]["dtype"], "ext::mlflow::input")
warned = [c.args[0] for c in warn_mock.call_args_list]
self.assertTrue(
any("passthrough" in m for m in warned),
f"expected passthrough warning, got {warned!r}",
)
rt = Runtime(out)
# In passthrough mode the wrapper hands inputs["data"] straight to
# predict(); pyfunc accepts a DataFrame for sklearn models.
result = rt.compute({"data": x}, {})
self.assertIn("predictions", result)
self.assertEqual(result["predictions"], model.predict(x).tolist())
# ---------------------------------------------------------------------------
# Params schema → dynamic_attributes + predict(params=...)
# ---------------------------------------------------------------------------
_PARAMS_MODEL_SCRIPT = textwrap.dedent(
"""
import mlflow
class ParamsModel(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input, params=None):
params = params or {}
return {
"temperature_used": params.get("temperature", -1.0),
"max_tokens_used": params.get("max_tokens", -1),
}
mlflow.models.set_model(ParamsModel())
"""
).lstrip()
def _save_params_model(tmp: str) -> str:
import mlflow # type: ignore[import-not-found]
from mlflow.models import ModelSignature # type: ignore[import-not-found]
from mlflow.types import DataType # type: ignore[import-not-found]
from mlflow.types.schema import ColSpec, ParamSchema, ParamSpec, Schema # type: ignore[import-not-found]
script_path = os.path.join(tmp, "params_model_script.py")
with open(script_path, "w") as f:
f.write(_PARAMS_MODEL_SCRIPT)
signature = ModelSignature(
inputs=Schema([ColSpec(name="prompt", type=DataType.string)]),
outputs=Schema([ColSpec(type=DataType.string)]),
params=ParamSchema(
[
ParamSpec("temperature", DataType.double, 0.7),
ParamSpec("max_tokens", DataType.long, 256),
]
),
)
model_dir = os.path.join(tmp, "params_model")
mlflow.pyfunc.save_model( # type: ignore[attr-defined]
path=model_dir,
python_model=script_path,
signature=signature,
)
return model_dir
class TestParamsModeDynamicAttributes(unittest.TestCase):
"""Params schema → dynamic_attributes; values reach predict(..., params=...)."""
def test_manifest_and_round_trip(self):
from fnnx.extras.mlflow import package_mlflow_model
from fnnx.runtime import Runtime
with tempfile.TemporaryDirectory() as tmp:
model_dir = _save_params_model(tmp)
out = os.path.join(tmp, "params.fnnx")
package_mlflow_model(model_dir, out)
with tarfile.open(out, "r") as tar:
manifest = json.loads(
tar.extractfile("manifest.json").read().decode() # type: ignore[union-attr]
)
variant_config = json.loads(
tar.extractfile("variant_config.json").read().decode() # type: ignore[union-attr]
)
attrs = manifest["dynamic_attributes"]
attr_names = {a["name"] for a in attrs}
self.assertEqual(attr_names, {"temperature", "max_tokens"})
cfg = variant_config["extra_values"]["fnnx_mlflow"]
self.assertEqual(sorted(cfg["param_names"]), ["max_tokens", "temperature"])
rt = Runtime(out)
# Pass temperature, omit max_tokens (lets MLflow default apply).
result = rt.compute(
{"prompt": ["hello"]},
{"temperature": 0.1, "max_tokens": 42},
)
self.assertIn("predictions", result)
predictions = result["predictions"]
self.assertEqual(predictions["temperature_used"], 0.1)
self.assertEqual(predictions["max_tokens_used"], 42)
if __name__ == "__main__":
unittest.main()