|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +# Copyright 2020 Google LLC |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +# |
| 17 | + |
| 18 | + |
| 19 | +import tensorflow as tf |
| 20 | +import numpy as np |
| 21 | + |
| 22 | +from google.cloud.aiplatform.explain.metadata.tf.v2 import saved_model_metadata_builder |
| 23 | + |
| 24 | + |
| 25 | +class SavedModelMetadataBuilderTest(tf.test.TestCase): |
| 26 | + def test_get_metadata_sequential(self): |
| 27 | + # Set up for the sequential. |
| 28 | + self.seq_model = tf.keras.models.Sequential() |
| 29 | + self.seq_model.add(tf.keras.layers.Dense(32, activation="relu", input_dim=10)) |
| 30 | + self.seq_model.add(tf.keras.layers.Dense(32, activation="relu")) |
| 31 | + self.seq_model.add(tf.keras.layers.Dense(1, activation="sigmoid")) |
| 32 | + self.saved_model_path = self.get_temp_dir() |
| 33 | + tf.saved_model.save(self.seq_model, self.saved_model_path) |
| 34 | + |
| 35 | + builder = saved_model_metadata_builder.SavedModelMetadataBuilder( |
| 36 | + self.saved_model_path |
| 37 | + ) |
| 38 | + generated_md = builder.get_metadata() |
| 39 | + expected_md = { |
| 40 | + "outputs": {"dense_2": {"outputTensorName": "dense_2"}}, |
| 41 | + "inputs": {"dense_input": {"inputTensorName": "dense_input"}}, |
| 42 | + } |
| 43 | + assert expected_md == generated_md |
| 44 | + |
| 45 | + def test_get_metadata_functional(self): |
| 46 | + inputs1 = tf.keras.Input(shape=(10,), name="model_input1") |
| 47 | + inputs2 = tf.keras.Input(shape=(10,), name="model_input2") |
| 48 | + x = tf.keras.layers.Dense(32, activation="relu")(inputs1) |
| 49 | + x = tf.keras.layers.Dense(32, activation="relu")(x) |
| 50 | + x = tf.keras.layers.concatenate([x, inputs2]) |
| 51 | + outputs = tf.keras.layers.Dense(1, activation="sigmoid")(x) |
| 52 | + fun_model = tf.keras.Model( |
| 53 | + inputs=[inputs1, inputs2], outputs=outputs, name="fun" |
| 54 | + ) |
| 55 | + model_dir = self.get_temp_dir() |
| 56 | + tf.saved_model.save(fun_model, model_dir) |
| 57 | + builder = saved_model_metadata_builder.SavedModelMetadataBuilder(model_dir) |
| 58 | + generated_md = builder.get_metadata() |
| 59 | + expected_md = { |
| 60 | + "inputs": { |
| 61 | + "model_input1": {"inputTensorName": "model_input1"}, |
| 62 | + "model_input2": {"inputTensorName": "model_input2"}, |
| 63 | + }, |
| 64 | + "outputs": {"dense_2": {"outputTensorName": "dense_2"}}, |
| 65 | + } |
| 66 | + assert expected_md == generated_md |
| 67 | + |
| 68 | + def test_get_metadata_subclassed_model(self): |
| 69 | + class MyModel(tf.keras.Model): |
| 70 | + def __init__(self, num_classes=2): |
| 71 | + super(MyModel, self).__init__(name="my_model") |
| 72 | + self.num_classes = num_classes |
| 73 | + self.dense_1 = tf.keras.layers.Dense(32, activation="relu") |
| 74 | + self.dense_2 = tf.keras.layers.Dense(num_classes, activation="sigmoid") |
| 75 | + |
| 76 | + def call(self, inputs): |
| 77 | + x = self.dense_1(inputs) |
| 78 | + return self.dense_2(x) |
| 79 | + |
| 80 | + subclassed_model = MyModel() |
| 81 | + subclassed_model.compile(loss="categorical_crossentropy") |
| 82 | + np.random.seed(0) |
| 83 | + x_train = np.random.random((1, 100)) |
| 84 | + y_train = np.random.randint(2, size=(1, 2)) |
| 85 | + subclassed_model.fit(x_train, y_train, batch_size=1, epochs=1) |
| 86 | + model_dir = self.get_temp_dir() |
| 87 | + tf.saved_model.save(subclassed_model, model_dir) |
| 88 | + |
| 89 | + builder = saved_model_metadata_builder.SavedModelMetadataBuilder(model_dir) |
| 90 | + generated_md = builder.get_metadata() |
| 91 | + expected_md = { |
| 92 | + "inputs": {"input_1": {"inputTensorName": "input_1"}}, |
| 93 | + "outputs": {"output_1": {"outputTensorName": "output_1"}}, |
| 94 | + } |
| 95 | + assert expected_md == generated_md |
| 96 | + |
| 97 | + def test_non_keras_model(self): |
| 98 | + class CustomModuleWithOutputName(tf.Module): |
| 99 | + def __init__(self): |
| 100 | + super(CustomModuleWithOutputName, self).__init__() |
| 101 | + self.v = tf.Variable(1.0) |
| 102 | + |
| 103 | + @tf.function(input_signature=[tf.TensorSpec([], tf.float32)]) |
| 104 | + def __call__(self, x): |
| 105 | + return {"custom_output_name": x * self.v} |
| 106 | + |
| 107 | + module_output = CustomModuleWithOutputName() |
| 108 | + call_output = module_output.__call__.get_concrete_function( |
| 109 | + tf.TensorSpec(None, tf.float32) |
| 110 | + ) |
| 111 | + model_dir = self.get_temp_dir() |
| 112 | + tf.saved_model.save( |
| 113 | + module_output, model_dir, signatures={"serving_default": call_output} |
| 114 | + ) |
| 115 | + |
| 116 | + builder = saved_model_metadata_builder.SavedModelMetadataBuilder(model_dir) |
| 117 | + generated_md = builder.get_metadata() |
| 118 | + expected_md = { |
| 119 | + "inputs": {"x": {"inputTensorName": "x"}}, |
| 120 | + "outputs": { |
| 121 | + "custom_output_name": {"outputTensorName": "custom_output_name"} |
| 122 | + }, |
| 123 | + } |
| 124 | + assert expected_md == generated_md |
| 125 | + |
| 126 | + def test_model_with_feature_column(self): |
| 127 | + feature_columns = [ |
| 128 | + tf.feature_column.embedding_column( |
| 129 | + tf.feature_column.categorical_column_with_vocabulary_list( |
| 130 | + "mode", ["fixed", "normal", "reversible"] |
| 131 | + ), |
| 132 | + dimension=8, |
| 133 | + ), |
| 134 | + tf.feature_column.numeric_column("age"), |
| 135 | + ] |
| 136 | + feature_layer = tf.keras.layers.DenseFeatures(feature_columns) |
| 137 | + |
| 138 | + model = tf.keras.Sequential( |
| 139 | + [ |
| 140 | + feature_layer, |
| 141 | + tf.keras.layers.Dense(128, activation="relu"), |
| 142 | + tf.keras.layers.Dense(1), |
| 143 | + ] |
| 144 | + ) |
| 145 | + |
| 146 | + model.compile( |
| 147 | + optimizer="adam", |
| 148 | + loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), |
| 149 | + metrics=["accuracy"], |
| 150 | + ) |
| 151 | + |
| 152 | + model.fit( |
| 153 | + {"age": np.array([20, 1]), "mode": np.array(["fixed", "normal"])}, |
| 154 | + np.array([0, 1]), |
| 155 | + ) |
| 156 | + model_dir = self.get_temp_dir() |
| 157 | + tf.saved_model.save(model, model_dir) |
| 158 | + builder = saved_model_metadata_builder.SavedModelMetadataBuilder(model_dir) |
| 159 | + generated_md = builder.get_metadata() |
| 160 | + expected_md = { |
| 161 | + "inputs": { |
| 162 | + "age": {"inputTensorName": "age", "modality": "categorical"}, |
| 163 | + "mode": {"inputTensorName": "mode", "modality": "categorical"}, |
| 164 | + }, |
| 165 | + "outputs": {"output_1": {"outputTensorName": "output_1"}}, |
| 166 | + } |
| 167 | + assert expected_md == generated_md |
0 commit comments