-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_extra_mlflow_tensorflow.py
More file actions
130 lines (99 loc) · 4.75 KB
/
Copy pathtest_extra_mlflow_tensorflow.py
File metadata and controls
130 lines (99 loc) · 4.75 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
"""End-to-end test for the MLflow → FNNX converter on a Keras functional model
with two named inputs.
Exercises the named-tensor branch of ``_map_input_schema``: when the signature
carries multiple TensorSpecs with explicit names, ``input_mode="tensor"`` is
selected with ``tensor_names=["a", "b"]``, the manifest has one ``NDJSON``
input per named tensor, and the wrapper assembles a dict-of-arrays payload for
``predict``.
"""
from __future__ import annotations
import json
import os
import tarfile
import tempfile
import unittest
import pytest
pytest.importorskip("mlflow")
pytest.importorskip("tensorflow")
N_FEATURES_A = 3
N_FEATURES_B = 2
def _build_tiny_keras_model():
"""Build a deterministic two-input Keras functional model and a sample batch."""
import numpy as np
import tensorflow as tf # type: ignore[import-not-found]
tf.random.set_seed(0)
input_a = tf.keras.Input(shape=(N_FEATURES_A,), name="a", dtype=tf.float32)
input_b = tf.keras.Input(shape=(N_FEATURES_B,), name="b", dtype=tf.float32)
concat = tf.keras.layers.Concatenate()([input_a, input_b])
output = tf.keras.layers.Dense(2, activation="linear", name="out")(concat)
model = tf.keras.Model(inputs={"a": input_a, "b": input_b}, outputs=output)
rng = np.random.default_rng(0)
sample_a = rng.random((4, N_FEATURES_A)).astype(np.float32)
sample_b = rng.random((4, N_FEATURES_B)).astype(np.float32)
return model, sample_a, sample_b
def _save_keras_model(tmp: str):
"""Save the Keras model with a two-named 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]
model, sample_a, sample_b = _build_tiny_keras_model()
signature = ModelSignature(
inputs=Schema(
[
TensorSpec(np.dtype("float32"), [-1, N_FEATURES_A], name="a"),
TensorSpec(np.dtype("float32"), [-1, N_FEATURES_B], name="b"),
]
),
outputs=Schema([TensorSpec(np.dtype("float32"), [-1, 2])]),
)
model_dir = os.path.join(tmp, "keras_model")
mlflow.tensorflow.save_model(model, model_dir, signature=signature) # type: ignore[attr-defined]
return model_dir, model, sample_a, sample_b
class TestKerasNamedTensorRoundTrip(unittest.TestCase):
"""Named multi-input Keras model round-trips through FNNX losslessly."""
def test_round_trip_and_manifest(self):
import numpy as np
from fnnx.extras.mlflow import package_mlflow_model
from fnnx.runtime import Runtime
with tempfile.TemporaryDirectory() as tmp:
model_dir, model, sample_a, sample_b = _save_keras_model(tmp)
out = os.path.join(tmp, "keras.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",
f"expected tensor mode, got {cfg['input_mode']!r}",
)
self.assertEqual(cfg["tensor_names"], ["a", "b"])
# Manifest: one NDJSON input per named tensor.
self.assertEqual(len(manifest["inputs"]), 2)
specs_by_name = {s["name"]: s for s in manifest["inputs"]}
self.assertEqual(set(specs_by_name), {"a", "b"})
spec_a = specs_by_name["a"]
self.assertEqual(spec_a["content_type"], "NDJSON")
self.assertEqual(spec_a["dtype"], "Array[float32]")
self.assertEqual(spec_a["shape"], ["batch", N_FEATURES_A])
spec_b = specs_by_name["b"]
self.assertEqual(spec_b["content_type"], "NDJSON")
self.assertEqual(spec_b["dtype"], "Array[float32]")
self.assertEqual(spec_b["shape"], ["batch", N_FEATURES_B])
rt = Runtime(out)
result = rt.compute({"a": sample_a, "b": sample_b}, {})
self.assertIn("predictions", result)
expected = model.predict({"a": sample_a, "b": sample_b}, verbose=0) # type: ignore[arg-type]
actual = np.asarray(result["predictions"], dtype=np.float32)
self.assertTrue(
np.allclose(actual, expected, atol=1e-5),
f"predictions diverged: expected={expected!r}, actual={actual!r}",
)
if __name__ == "__main__":
unittest.main()