tensorflow hub example throws an error when Float16 is enabled - tensorflow

I am trying to load a model from Tensorflowhub using example code. It works perfect with the FP32. As soon as I add the tf.keras.mixed_precision.set_global_policy('mixed_float16') to enable mixed float, it raises an error. Looks like the dimension issue but then it works perfect with FP32. Here is the reproducible code:
import tensorflow as tf
import tensorflow_hub as hub
IMAGE_SIZE = (224,224)
class_names = ['cat','dog']
#If you comment out the following line, the code works fine.
tf.keras.mixed_precision.set_global_policy('mixed_float16')
# --------
model_handle = "https://tfhub.dev/google/imagenet/resnet_v1_50/feature_vector/5"
do_fine_tuning = False
print("Building model with", model_handle)
model = tf.keras.Sequential([
tf.keras.layers.InputLayer(input_shape=IMAGE_SIZE + (3,)),
hub.KerasLayer(model_handle, trainable=do_fine_tuning),
tf.keras.layers.Dropout(rate=0.2),
tf.keras.layers.Dense(len(class_names),
kernel_regularizer=tf.keras.regularizers.l2(0.0001))
])
model.build((None,)+IMAGE_SIZE+(3,))
model.summary()
The following error is thrown:
Building model with https://tfhub.dev/google/imagenet/resnet_v1_50/feature_vector/5
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [8], in <cell line: 4>()
2 do_fine_tuning = False
3 print("Building model with", model_handle)
----> 4 model = tf.keras.Sequential([
5 tf.keras.layers.InputLayer(input_shape=IMAGE_SIZE + (3,)),
6 hub.KerasLayer(model_handle, trainable=do_fine_tuning),
7 tf.keras.layers.Dropout(rate=0.2),
8 tf.keras.layers.Dense(len(class_names),
9 kernel_regularizer=tf.keras.regularizers.l2(0.0001))
10 ])
11 model.build((None,)+IMAGE_SIZE+(3,))
12 model.summary()
File ~/miniconda3/envs/fahtx/lib/python3.8/site-packages/tensorflow/python/training/tracking/base.py:587, in no_automatic_dependency_tracking.<locals>._method_wrapper(self, *args, **kwargs)
585 self._self_setattr_tracking = False # pylint: disable=protected-access
586 try:
--> 587 result = method(self, *args, **kwargs)
588 finally:
589 self._self_setattr_tracking = previous_value # pylint: disable=protected-access
File ~/miniconda3/envs/fahtx/lib/python3.8/site-packages/keras/utils/traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs)
65 except Exception as e: # pylint: disable=broad-except
66 filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67 raise e.with_traceback(filtered_tb) from None
68 finally:
69 del filtered_tb
File /tmp/__autograph_generated_fileo7avm3_o.py:74, in outer_factory.<locals>.inner_factory.<locals>.tf__call(self, inputs, training)
72 result = ag__.converted_call(ag__.ld(smart_cond).smart_cond, (ag__.ld(training), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=True), fscope))), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=False), fscope)))), None, fscope)
73 result = ag__.Undefined('result')
---> 74 ag__.if_stmt(ag__.not_(ag__.ld(self)._has_training_argument), if_body_3, else_body_3, get_state_3, set_state_3, ('result', 'training'), 1)
76 def get_state_6():
77 return (result,)
File /tmp/__autograph_generated_fileo7avm3_o.py:72, in outer_factory.<locals>.inner_factory.<locals>.tf__call.<locals>.else_body_3()
70 training = False
71 ag__.if_stmt(ag__.ld(self).trainable, if_body_2, else_body_2, get_state_2, set_state_2, ('training',), 1)
---> 72 result = ag__.converted_call(ag__.ld(smart_cond).smart_cond, (ag__.ld(training), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=True), fscope))), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=False), fscope)))), None, fscope)
File /tmp/__autograph_generated_fileo7avm3_o.py:72, in outer_factory.<locals>.inner_factory.<locals>.tf__call.<locals>.else_body_3.<locals>.<lambda>()
70 training = False
71 ag__.if_stmt(ag__.ld(self).trainable, if_body_2, else_body_2, get_state_2, set_state_2, ('training',), 1)
---> 72 result = ag__.converted_call(ag__.ld(smart_cond).smart_cond, (ag__.ld(training), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=True), fscope))), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=False), fscope)))), None, fscope)
ValueError: Exception encountered when calling layer "keras_layer_3" (type KerasLayer).
in user code:
File "/root/miniconda3/envs/fahtx/lib/python3.8/site-packages/tensorflow_hub/keras_layer.py", line 237, in call *
result = smart_cond.smart_cond(training,
ValueError: Could not find matching concrete function to call loaded from the SavedModel. Got:
Positional arguments (4 total):
* <tf.Tensor 'inputs:0' shape=(None, 224, 224, 3) dtype=float16>
* False
* False
* 0.99
Keyword arguments: {}
Expected these arguments to match one of the following 4 option(s):
Option 1:
Positional arguments (4 total):
* TensorSpec(shape=(None, None, None, 3), dtype=tf.float32, name='inputs')
* True
* True
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 2:
Positional arguments (4 total):
* TensorSpec(shape=(None, None, None, 3), dtype=tf.float32, name='inputs')
* True
* False
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 3:
Positional arguments (4 total):
* TensorSpec(shape=(None, None, None, 3), dtype=tf.float32, name='inputs')
* False
* True
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 4:
Positional arguments (4 total):
* TensorSpec(shape=(None, None, None, 3), dtype=tf.float32, name='inputs')
* False
* False
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Call arguments received by layer "keras_layer_3" (type KerasLayer):
• inputs=tf.Tensor(shape=(None, 224, 224, 3), dtype=float16)
• training=False

It is about target 'dtype' when float16 is enabled as the variable rules it trying to use the float16 then you just need to specify float32 as the model input required. I like to include channel numbers as the image properties when switching colors to transforming. Some functions work without channels number but for those, you need a translation method. Sample Resize( ) -> img_to_array( ) -> Predict () OR Boundary Boxes working.
[ Sample ]:
import tensorflow as tf
import tensorflow_hub as hub
IMAGE_SIZE = ( 224,224,3 )
class_names = ['cat','dog']
tf.keras.mixed_precision.set_global_policy('mixed_float16')
model_handle = "https://tfhub.dev/google/imagenet/resnet_v1_50/feature_vector/5"
do_fine_tuning = False
print("Building model with", model_handle)
model = tf.keras.Sequential([
tf.keras.layers.InputLayer(input_shape=IMAGE_SIZE, dtype=tf.float32),
hub.KerasLayer(model_handle, trainable=do_fine_tuning , dtype=tf.float32),
tf.keras.layers.Dropout(rate=0.2),
tf.keras.layers.Dense(len(class_names),
kernel_regularizer=tf.keras.regularizers.l2(0.0001))
])
model.build((None,)+ IMAGE_SIZE)
model.summary()
[ Error ]:
ValueError: Could not find matching concrete function to call loaded from the SavedModel. Got:
Positional arguments (4 total):
* <tf.Tensor 'inputs:0' shape=(None, 224, 224, 3) dtype=float16>
* False
* False
* 0.99
Keyword arguments: {}
[ Output ]:
F:\temp\Python>python tf_test_mixed_float16.py
WARNING:tensorflow:Mixed precision compatibility check (mixed_float16): WARNING
Your GPU may run slowly with dtype policy mixed_float16 because it does not have compute capability of at least 7.0. Your GPU:
NVIDIA GeForce GTX 1060 6GB, compute capability 6.1
See https://developer.nvidia.com/cuda-gpus for a list of GPUs and their compute capabilities.
If you will use compatible GPU(s) not attached to this host, e.g. by running a multi-worker model, you can ignore this warning. This message will only be logged once
Building model with https://tfhub.dev/google/imagenet/resnet_v1_50/feature_vector/5
2022-06-17 15:02:41.319205: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-06-17 15:02:41.878364: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1532] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 4632 MB memory: -> device: 0, name: NVIDIA GeForce GTX 1060 6GB, pci bus id: 0000:01:00.0, compute capability: 6.1
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
keras_layer (KerasLayer) (None, 2048) 23561152
dropout (Dropout) (None, 2048) 0
dense (Dense) (None, 2) 4098
=================================================================
Total params: 23,565,250
Trainable params: 4,098
Non-trainable params: 23,561,152
_________________________________________________________________
F:\temp\Python>

Related

Tensorflow Recommender error on loaded ranking model predictions

I have a Ranking model made with Tensorflow Recommender.
When i make predictions with him it works ok.
If i save it and load it, when making predictions with the loaded model, i get an error. Please see below my model and the error i get
Ranking model:
class HMRankingModel(tfrs.Model):
def __init__(self):
super().__init__()
# Customer model
self.customer_input = tf.keras.Input(shape=(1,), dtype=tf.string, name='customer_input')
self.customer_sl = tf.keras.layers.StringLookup(vocabulary=unique_customer_ids, mask_token=None, name='customer_string_lookup')(self.customer_input)
self.customer_embedding = tf.squeeze(tf.keras.layers.Embedding(len(unique_customer_ids) + 1, embedding_dimension, name='customer_emb')(self.customer_sl), axis=1)
self.age_input = tf.keras.Input(shape=(1,), name='age_input')
self.age_discretization = tf.keras.layers.Discretization(age_buckets.tolist(), name='age_discretization')(self.age_input)
self.age_embedding = tf.squeeze(tf.keras.layers.Embedding(len(age_buckets) + 1, embedding_dimension, name='age_embedding')(self.age_discretization), axis=1)
self.customer_merged = tf.keras.layers.concatenate([self.customer_embedding, self.age_embedding], axis=-1, name='customer_merged')
self.customer_dense = tf.keras.layers.Dense(embedding_dimension, activation=activation, name='customer_dense')(self.customer_merged)
# Article model
self.article_input = tf.keras.Input(shape=(1,), dtype=tf.string, name='article_input')
self.article_sl = tf.keras.layers.StringLookup(vocabulary=unique_article_ids, name='article_string_lookup')(self.article_input)
self.article_final = tf.squeeze(tf.keras.layers.Embedding(len(unique_article_ids)+1, embedding_dimension, name='article_emb')(self.article_sl), axis=1)
self.article_dense = tf.keras.layers.Dense(embedding_dimension, activation=activation, name='article_dense')(self.article_final)
# Multiply model
self.towers_multiplied = tf.keras.layers.Multiply(name='towers_multiplied')([self.customer_dense, self.article_dense])
self.towers_dense = tf.keras.layers.Dense(dense_size, activation=activation, name='towers_dense1')(self.towers_multiplied)
self.output_node = tf.keras.layers.Dense(1, name='output_node')(self.towers_dense)
# Model definition
self.model = tf.keras.Model(inputs={'customer_id': self.customer_input,
'article_id': self.article_input,
'age': self.age_input,
},
outputs=self.output_node)
self.task = tfrs.tasks.Ranking(
loss = tf.keras.losses.MeanSquaredError(),
metrics=[tf.keras.metrics.RootMeanSquaredError()]
)
def call(self, features):
return self.model({'customer_id': features["customer_id"],
'article_id': features["article_id"],
'age': features["age"],
})
def compute_loss(self, features_dict, training=False):
labels = features_dict.pop("count")
predictions = self(features_dict)
return self.task(labels=labels, predictions=predictions)
ranking_model = HMRankingModel()
ranking_model.compile(optimizer=tf.keras.optimizers.Adagrad(learning_rate=0.1))
ranking_model.fit(cached_train, validation_data=cached_validation, epochs=epochs)
prediction with the original model
ranking_model({
'customer_id': np.array(["18b3a4767533c8f1f6ff274b57ca200939c9fda3992c5bb3b50b31dc6d6b1ee5"]),
'age': np.array([29]),
'article_id': np.array(['562245059'])
})
outputs:
<tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[1.3872527]], dtype=float32)>
I save the model
tf.saved_model.save(ranking_model, ranking_model_path)
On loading the model and making predictions i get an error
saved_ranking_model = tf.saved_model.load(ranking_model_path)
predictions = saved_ranking_model({
'customer_id': np.array(["18b3a4767533c8f1f6ff274b57ca200939c9fda3992c5bb3b50b31dc6d6b1ee5"]),
'age': np.array([29]),
'article_id': np.array(['141661025'])
})
output:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [31], in <cell line: 1>()
----> 1 predictions = saved_ranking_model({
2 'customer_id': np.array(["18b3a4767533c8f1f6ff274b57ca200939c9fda3992c5bb3b50b31dc6d6b1ee5"]),
3 'age': np.array([29]),
4 'article_id': np.array(['141661025'])
5 })
File ~/miniconda3/envs/tf/lib/python3.9/site-packages/tensorflow/python/saved_model/load.py:686, in _call_attribute(instance, *args, **kwargs)
685 def _call_attribute(instance, *args, **kwargs):
--> 686 return instance.__call__(*args, **kwargs)
File ~/miniconda3/envs/tf/lib/python3.9/site-packages/tensorflow/python/util/traceback_utils.py:153, in filter_traceback.<locals>.error_handler(*args, **kwargs)
151 except Exception as e:
152 filtered_tb = _process_traceback_frames(e.__traceback__)
--> 153 raise e.with_traceback(filtered_tb) from None
154 finally:
155 del filtered_tb
File ~/miniconda3/envs/tf/lib/python3.9/site-packages/tensorflow/python/saved_model/function_deserialization.py:286, in recreate_function.<locals>.restored_function_body(*args, **kwargs)
282 positional, keyword = concrete_function.structured_input_signature
283 signature_descriptions.append(
284 "Option {}:\n {}\n Keyword arguments: {}"
285 .format(index + 1, _pretty_format_positional(positional), keyword))
--> 286 raise ValueError(
287 "Could not find matching concrete function to call loaded from the "
288 f"SavedModel. Got:\n {_pretty_format_positional(args)}\n Keyword "
289 f"arguments: {kwargs}\n\n Expected these arguments to match one of the "
290 f"following {len(saved_function.concrete_functions)} option(s):\n\n"
291 f"{(chr(10)+chr(10)).join(signature_descriptions)}")
ValueError: Could not find matching concrete function to call loaded from the SavedModel. Got:
Positional arguments (2 total):
* {'age': <tf.Tensor 'features:0' shape=(1,) dtype=int64>,
'article_id': <tf.Tensor 'features_1:0' shape=(1,) dtype=string>,
'customer_id': <tf.Tensor 'features_2:0' shape=(1,) dtype=string>}
* False
Keyword arguments: {}
Expected these arguments to match one of the following 4 option(s):
Option 1:
Positional arguments (2 total):
* {'age': TensorSpec(shape=(None,), dtype=tf.float32, name='age'),
'article_id': TensorSpec(shape=(None,), dtype=tf.string, name='article_id'),
'customer_id': TensorSpec(shape=(None,), dtype=tf.string, name='customer_id')}
* False
Keyword arguments: {}
Option 2:
Positional arguments (2 total):
* {'age': TensorSpec(shape=(None,), dtype=tf.float32, name='features/age'),
'article_id': TensorSpec(shape=(None,), dtype=tf.string, name='features/article_id'),
'customer_id': TensorSpec(shape=(None,), dtype=tf.string, name='features/customer_id')}
* False
Keyword arguments: {}
Option 3:
Positional arguments (2 total):
* {'age': TensorSpec(shape=(None,), dtype=tf.float32, name='features/age'),
'article_id': TensorSpec(shape=(None,), dtype=tf.string, name='features/article_id'),
'customer_id': TensorSpec(shape=(None,), dtype=tf.string, name='features/customer_id')}
* True
Keyword arguments: {}
Option 4:
Positional arguments (2 total):
* {'age': TensorSpec(shape=(None,), dtype=tf.float32, name='age'),
'article_id': TensorSpec(shape=(None,), dtype=tf.string, name='article_id'),
'customer_id': TensorSpec(shape=(None,), dtype=tf.string, name='customer_id')}
* True
Keyword arguments: {}
If i remove the age data and all age related layers from the model, it works ok. I guess it may be a problem with the age layers but i can't figure it out
There is a problem with the data for the saved_model. The value for 'age' needs to be converted to float32.
predictions = saved_ranking_model({
'customer_id': np.array(["18b3a4767533c8f1f6ff274b57ca200939c9fda3992c5bb3b50b31dc6d6b1ee5"]),
'age': np.array([np.float32(29.0)]),
'article_id': np.array(['141661025'])
})

BERT Listwise Ranking

I am trying to make a listwise ranking model similar to the Tensorflow Listwise Ranking Tutorial, however, the only difference is changing how the embedding is done. I want to use the BERT embedding model shown in Tensorflow Hub.
Here is my code:
import tensorflow_hub as hub
import tensorflow_text as text
import tensorflow as tf
import tensorflow_datasets as tfds
import numpy as np
import tensorflow_ranking as tfr
import tensorflow_recommenders as tfrs
preprocessor = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3")
encoder = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4",trainable=True)
text_input = tf.keras.layers.Input(shape=(), dtype=tf.string)
encoder_inputs = preprocessor(text_input)
outputs = encoder(encoder_inputs)
pooled_output = outputs["pooled_output"]
embedding_model1 = tf.keras.Model({"user_id":text_input}, pooled_output)
text_input = tf.keras.layers.Input(shape=(), dtype=tf.string)
encoder_inputs = preprocessor(text_input)
outputs = encoder(encoder_inputs)
pooled_output = outputs["pooled_output"]
embedding_model2 = tf.keras.Model({"movie_title": text_input}, pooled_output)
ratings = tfds.load("movielens/100k-ratings", split="train")
movies = tfds.load("movielens/100k-movies", split="train")
ratings = ratings.map(lambda x: {
"movie_title": x["movie_title"],
"user_id": x["user_id"],
"user_rating": x["user_rating"],
})
movies = movies.map(lambda x: x["movie_title"])
unique_movie_titles = np.unique(np.concatenate(list(movies.batch(1000))))
unique_user_ids = np.unique(np.concatenate(list(ratings.batch(1_000).map(
lambda x: x["user_id"]))))
tf.random.set_seed(42)
# Split between train and tests sets, as before.
shuffled = ratings.shuffle(100_000, seed=42, reshuffle_each_iteration=False)
train = shuffled.take(80_000)
test = shuffled.skip(80_000).take(20_000)
# We sample 50 lists for each user for the training data. For each list we
# sample 5 movies from the movies the user rated.
train = tfrs.examples.movielens.sample_listwise(
train,
num_list_per_user=50,
num_examples_per_list=5,
seed=42
)
test = tfrs.examples.movielens.sample_listwise(
test,
num_list_per_user=1,
num_examples_per_list=5,
seed=42
)
epochs = 10
cached_train = train.shuffle(100_000).batch(32).cache()
cached_test = test.batch(16).cache()
class RankingModel(tfrs.Model):
def __init__(self, loss):
super().__init__()
# Compute embeddings for users.
self.user_embeddings = embedding_model1
# Compute embeddings for movies.
self.movie_embeddings = embedding_model2
# Compute predictions.
self.score_model = tf.keras.Sequential([
# Learn multiple dense layers.
tf.keras.layers.Dense(256, activation="relu"),
tf.keras.layers.Dense(64, activation="relu"),
# Make rating predictions in the final layer.
tf.keras.layers.Dense(1)
])
self.task = tfrs.tasks.Ranking(
loss=loss,
metrics=[
tfr.keras.metrics.NDCGMetric(name="ndcg_metric"),
tf.keras.metrics.RootMeanSquaredError()
]
)
def call(self, features):
# We first convert the id features into embeddings.
# User embeddings are a [batch_size, embedding_dim] tensor.
user_embeddings = self.user_embeddings(features["user_id"])
# Movie embeddings are a [batch_size, num_movies_in_list, embedding_dim]
# tensor.
movie_embeddings = self.movie_embeddings(features["movie_title"])
# We want to concatenate user embeddings with movie emebeddings to pass
# them into the ranking model. To do so, we need to reshape the user
# embeddings to match the shape of movie embeddings.
list_length = features["movie_title"].shape[1]
user_embedding_repeated = tf.repeat(
tf.expand_dims(user_embeddings, 1), [list_length], axis=1)
# Once reshaped, we concatenate and pass into the dense layers to generate
# predictions.
concatenated_embeddings = tf.concat(
[user_embedding_repeated, movie_embeddings], 2)
return self.score_model(concatenated_embeddings)
def compute_loss(self, features, training=False):
labels = features.pop("user_rating")
scores = self(features)
return self.task(
labels=labels,
predictions=tf.squeeze(scores, axis=-1),
)
mse_model = RankingModel(tf.keras.losses.MeanSquaredError())
mse_model.compile(optimizer=tf.keras.optimizers.Adagrad(0.1))
mse_model.fit(cached_train, epochs=1, verbose=False)
mse_model.summary()
I think the issue might be the fact that BERT from Tensorflow Hub can only take in 1D tensors like (N,). How can I change the code so I can make a listwise ranking model that uses BERT as the embedder? Here is the error message I get:
WARNING:tensorflow:Model was constructed with shape (None,) for input KerasTensor(type_spec=TensorSpec(shape=(None,), dtype=tf.string, name='input_39'), name='input_39', description="created by layer 'input_39'"), but it was called on an input with incompatible shape (None, 5).
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-117-f6e1e67627f1> in <module>
127 mse_model = RankingModel(tf.keras.losses.MeanSquaredError())
128 mse_model.compile(optimizer=tf.keras.optimizers.Adagrad(0.1))
--> 129 mse_model.fit(cached_train, epochs=1, verbose=False)
130 mse_model.summary()
7 frames
/usr/local/lib/python3.7/dist-packages/tensorflow_hub/keras_layer.py in <lambda>()
70 training = False
71 ag__.if_stmt(ag__.ld(self).trainable, if_body_2, else_body_2, get_state_2, set_state_2, ('training',), 1)
---> 72 result = ag__.converted_call(ag__.ld(smart_cond).smart_cond, (ag__.ld(training), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=True), fscope))), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=False), fscope)))), None, fscope)
73 result = ag__.Undefined('result')
74 ag__.if_stmt(ag__.not_(ag__.ld(self)._has_training_argument), if_body_3, else_body_3, get_state_3, set_state_3, ('result', 'training'), 1)
ValueError: in user code:
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1160, in train_function *
return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1146, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1135, in run_step **
outputs = model.train_step(data)
File "/usr/local/lib/python3.7/dist-packages/tensorflow_recommenders/models/base.py", line 68, in train_step
loss = self.compute_loss(inputs, training=True)
File "<ipython-input-117-f6e1e67627f1>", line 120, in compute_loss
scores = self(features)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/tmp/__autograph_generated_filedc6sn1ck.py", line 11, in tf__call
movie_embeddings = ag__.converted_call(ag__.ld(self).movie_embeddings, (ag__.ld(features)['movie_title'],), None, fscope)
File "/tmp/__autograph_generated_file6e8815fm.py", line 74, in tf__call
ag__.if_stmt(ag__.not_(ag__.ld(self)._has_training_argument), if_body_3, else_body_3, get_state_3, set_state_3, ('result', 'training'), 1)
File "/tmp/__autograph_generated_file6e8815fm.py", line 72, in else_body_3
result = ag__.converted_call(ag__.ld(smart_cond).smart_cond, (ag__.ld(training), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=True), fscope))), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=False), fscope)))), None, fscope)
File "/tmp/__autograph_generated_file6e8815fm.py", line 72, in <lambda>
result = ag__.converted_call(ag__.ld(smart_cond).smart_cond, (ag__.ld(training), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=True), fscope))), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=False), fscope)))), None, fscope)
ValueError: Exception encountered when calling layer "ranking_model_13" " f"(type RankingModel).
in user code:
File "<ipython-input-117-f6e1e67627f1>", line 101, in call *
movie_embeddings = self.movie_embeddings(features["movie_title"])
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 70, in error_handler **
raise e.with_traceback(filtered_tb) from None
File "/tmp/__autograph_generated_file6e8815fm.py", line 74, in tf__call
ag__.if_stmt(ag__.not_(ag__.ld(self)._has_training_argument), if_body_3, else_body_3, get_state_3, set_state_3, ('result', 'training'), 1)
File "/tmp/__autograph_generated_file6e8815fm.py", line 72, in else_body_3
result = ag__.converted_call(ag__.ld(smart_cond).smart_cond, (ag__.ld(training), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=True), fscope))), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=False), fscope)))), None, fscope)
File "/tmp/__autograph_generated_file6e8815fm.py", line 72, in <lambda>
result = ag__.converted_call(ag__.ld(smart_cond).smart_cond, (ag__.ld(training), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=True), fscope))), ag__.autograph_artifact((lambda : ag__.converted_call(ag__.ld(f), (), dict(training=False), fscope)))), None, fscope)
ValueError: Exception encountered when calling layer "keras_layer_8" " f"(type KerasLayer).
in user code:
File "/usr/local/lib/python3.7/dist-packages/tensorflow_hub/keras_layer.py", line 237, in call *
result = smart_cond.smart_cond(training,
ValueError: Could not find matching concrete function to call loaded from the SavedModel. Got:
Positional arguments (3 total):
* <tf.Tensor 'inputs:0' shape=(None, 5) dtype=string>
* False
* None
Keyword arguments: {}
Expected these arguments to match one of the following 4 option(s):
Option 1:
Positional arguments (3 total):
* TensorSpec(shape=(None,), dtype=tf.string, name='sentences')
* False
* None
Keyword arguments: {}
Option 2:
Positional arguments (3 total):
* TensorSpec(shape=(None,), dtype=tf.string, name='sentences')
* True
* None
Keyword arguments: {}
Option 3:
Positional arguments (3 total):
* TensorSpec(shape=(None,), dtype=tf.string, name='inputs')
* False
* None
Keyword arguments: {}
Option 4:
Positional arguments (3 total):
* TensorSpec(shape=(None,), dtype=tf.string, name='inputs')
* True
* None
Keyword arguments: {}
Call arguments received by layer "keras_layer_8" " f"(type KerasLayer):
• inputs=tf.Tensor(shape=(None, 5), dtype=string)
• training=False
Call arguments received by layer "ranking_model_13" " f"(type RankingModel):
• features={'user_id': 'tf.Tensor(shape=(None,), dtype=string)', 'movie_title': 'tf.Tensor(shape=(None, 5), dtype=string)'}

"ValueError: No gradients provided for any variable" when training a bijector

I'm training a bijector using tensorflow-probability.
I'm following a tutorial. The same codes from the tutorial can be found at (the relevant part starts from the line "Training the bijector"): https://rpubs.com/bacti/tensorflow-probabilistic
My code is slightly different to the above. But even if I copy the same code from the above, it still causes the same error.
My codes is here (runnable). It's basically the same to the relevant part in the tutorial's codes: https://colab.research.google.com/drive/1tlA5l2ZGRIiR19HM-LHGKs-G2Rjxk6zF?usp=sharing#scrollTo=BW9Kmg3z0dzC
The following is the training loop in my codes that caused the error:
# Train the bijector
num_epochs = 10
opt = tf.keras.optimizers.Adam(learning_rate=0.1)
train_losses = []
valid_losses = []
for epoch in range(num_epochs):
print(f'Epoch {epoch}...')
train_loss = tf.keras.metrics.Mean()
val_loss = tf.keras.metrics.Mean()
for train_batch in x_train:
with tf.GradientTape() as tape:
tape.watch(trainable_dist.trainable_variables)
loss = -tf.reduce_mean(trainable_dist.log_prob(train_batch))
print('loss', loss)
grads = tape.gradient(loss, trainable_dist.trainable_variables)
print('grads', grads)
opt.apply_gradients(zip(grads, trainable_dist.trainable_variables))
# print(loss)
print('loss', tf.shape(loss))
train_loss(loss)
train_losses.append(train_loss.result().numpy())
# Validation
for valid_batch in x_valid:
loss = -trainable_dist.log_prob(valid_batch)
val_loss(loss)
valid_losses.append(val_loss.result().numpy())
This is the error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-13-3bf0f105e1c4> in <module>()
18 grads = tape.gradient(loss, trainable_dist.trainable_variables)
19 print('grads', grads)
---> 20 opt.apply_gradients(zip(grads, trainable_dist.trainable_variables))
21
22 # print(loss)
1 frames
/usr/local/lib/python3.7/dist-packages/keras/optimizer_v2/utils.py in filter_empty_gradients(grads_and_vars)
71 if not filtered:
72 variable = ([v.name for _, v in grads_and_vars],)
---> 73 raise ValueError(f"No gradients provided for any variable: {variable}. "
74 f"Provided `grads_and_vars` is {grads_and_vars}.")
75 if vars_with_empty_grads:
ValueError: No gradients provided for any variable: (['a:0', 'b:0'],). Provided `grads_and_vars` is ((None, <tf.Variable 'a:0' shape=() dtype=float32, numpy=0.25>), (None, <tf.Variable 'b:0' shape=() dtype=float32, numpy=-0.1>)).
The loss was computed, but the grads can not be computed in the line grads = tape.gradient(loss, trainable_dist.trainable_variables). They are (None, None). Why?
What is the cause of it? I can't find any problem in my codes.

How to use model __call__ on list of various shaped numpy arrays?

I would like to use the Keras model() way of predicting. The model.predict() way works fine but I need a faster way of doing predictions with my trained model.
Here is the error when I do model(pred_emb) :
WARNING:tensorflow:Entity <tensorflow.python.saved_model.function_deserialization.RestoredFunction object at 0x7fd0147e5d30> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Could not find matching function to call loaded from the SavedModel. Got:
Positional arguments (4 total):
* Tensor("inputs:0", shape=(1000, 224, 224, 3), dtype=uint8)
* False
* False
* 0.99
Keyword arguments: {}
Expected these arguments to match one of the following 4 option(s):
Option 1:
Positional arguments (4 total):
* TensorSpec(shape=(?, 224, 224, 3), dtype=tf.float32, name='inputs')
* True
* False
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 2:
Positional arguments (4 total):
* TensorSpec(shape=(?, 224, 224, 3), dtype=tf.float32, name='inputs')
* True
* True
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 3:
Positional arguments (4 total):
* TensorSpec(shape=(?, 224, 224, 3), dtype=tf.float32, name='inputs')
* False
* True
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 4:
Positional arguments (4 total):
* TensorSpec(shape=(?, 224, 224, 3), dtype=tf.float32, name='inputs')
* False
* False
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
where pred_emb has the following properties:
What I've tried so far:
Trained another model without including pred_emb[3] so the input features were only pred_emb[0], pred_emb[1], and pred_emb[2]. The model() way of predicting worked. I think the pred_emb[3] which contains 1000 image numpy values of shape (224,224,3) causes the error when I do model(pred_emb). I already tried to reshape it and used ragged tensors to convert it into tensor shape to resolve the error but none of what I've attempted worked.
Thank you in advance for your guidance and help.

Getting 'ValueError: Could not find matching function to call loaded from the SavedModel.' on training a model

I'm using Tensorflow 2 and LaBSE pre-trained model on tf-hub (not much familiar with both). (https://tfhub.dev/google/LaBSE/2). I am trying to train a multi class classifier with a custom text data set. I am also following this example on BERT classifier(https://www.tensorflow.org/text/tutorials/classify_text_with_bert), to get the idea of how the model is built. This is to check only I can train and run the model. I am using data set objects for my input texts obtained from csv data which looks like this,
"Sentence","label"
"sentence sample1", 0
"sentence sample2", 3
and I split them into X, y sets as usual. However,
I get the above error when trying to train the model. Below is my code,
def build_classifier_model():
text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name='text')
preprocessing_layer = hub.KerasLayer(tfhub_handle_preprocess, name='preprocessing')
encoder_inputs = preprocessing_layer(text_input)
encoder = hub.KerasLayer(tfhub_handle_encoder, trainable=True, name='LaBSE_encoder')
outputs = encoder(encoder_inputs)
net = outputs['pooled_output']
activation= tf.keras.activations.softmax#None
net = tf.keras.layers.Dropout(0.1)(net)
net = tf.keras.layers.Dense(4, activation=activation, name='classifier')(net)
return tf.keras.Model(text_input, net)
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False)
metrics = tf.keras.metrics.SparseCategoricalAccuracy()
epochs = 5
optimizer=tf.keras.optimizers.Adam()
train_dataset = tf.data.Dataset.from_tensor_slices(( # convert to dataset objects
np.array(X_train),np.array(y_train,dtype='int32')
))
test_dataset = tf.data.Dataset.from_tensor_slices((
np.array(X_test),np.array(y_test,dtype='int32')
))
These dataset objects' specs are, <TensorSliceDataset shapes: ((), ()), types: (tf.string, tf.int32)>
classifier_model.compile(optimizer=optimizer,
loss=loss,
metrics=metrics)
his = classifier_model.fit(train_dataset, validation_data=test_dataset,
epochs=epochs, batch_size=8) #ignore that I'm using test dataset for validation dataset
The last step gives the error;
Epoch 1/5
WARNING:tensorflow:Model was constructed with shape (None,) for input KerasTensor(type_spec=TensorSpec(shape=(None,), dtype=tf.string, name='text'), name='text', description="created by layer 'text'"), but it was called on an input with incompatible shape ().
WARNING:tensorflow:Model was constructed with shape (None,) for input KerasTensor(type_spec=TensorSpec(shape=(None,), dtype=tf.string, name='text'), name='text', description="created by layer 'text'"), but it was called on an input with incompatible shape ().
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-141-3523a14b56f1> in <module>()
1 history = classifier_model.fit(train_dataset, validation_data=test_dataset,
----> 2 epochs=epochs, batch_size=8)
9 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
984 except Exception as e: # pylint:disable=broad-except
985 if hasattr(e, "ag_error_metadata"):
--> 986 raise e.ag_error_metadata.to_exception(e)
987 else:
988 raise
ValueError: in user code:
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:855 train_function *
return step_function(self, iterator)
/usr/local/lib/python3.7/dist-packages/tensorflow_hub/keras_layer.py:237 call *
result = smart_cond.smart_cond(training,
/usr/local/lib/python3.7/dist-packages/tensorflow/python/saved_model/load.py:670 _call_attribute **
return instance.__call__(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py:889 __call__
result = self._call(*args, **kwds)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py:924 _call
results = self._stateful_fn(*args, **kwds)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py:3022 __call__
filtered_flat_args) = self._maybe_define_function(args, kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py:3444 _maybe_define_function
graph_function = self._create_graph_function(args, kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py:3289 _create_graph_function
capture_by_value=self._capture_by_value),
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py:999 func_graph_from_py_func
func_outputs = python_func(*func_args, **func_kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py:672 wrapped_fn
out = weak_wrapped_fn().__wrapped__(*args, **kwds)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/saved_model/function_deserialization.py:291 restored_function_body
"\n\n".join(signature_descriptions)))
ValueError: Could not find matching function to call loaded from the SavedModel. Got:
Positional arguments (3 total):
* Tensor("inputs:0", shape=(), dtype=string)
* False
* None
Keyword arguments: {}
Expected these arguments to match one of the following 4 option(s):
Option 1:
Positional arguments (3 total):
* TensorSpec(shape=(None,), dtype=tf.string, name='inputs')
* True
* None
Keyword arguments: {}
Option 2:
Positional arguments (3 total):
* TensorSpec(shape=(None,), dtype=tf.string, name='inputs')
* False
* None
Keyword arguments: {}
Option 3:
Positional arguments (3 total):
* TensorSpec(shape=(None,), dtype=tf.string, name='sentences')
* True
* None
Keyword arguments: {}
Option 4:
Positional arguments (3 total):
* TensorSpec(shape=(None,), dtype=tf.string, name='sentences')
* False
* None
Keyword arguments: {}
I think this is an issue with the dataset object's specs provided to the input but, do not understand how to fix it or the exact reason. I do not get even though my dataset object has types of "tf.string" why it is incompatible with the input expected. I looked up in existing answers and since I'm not much familiar with TF, I want to know what is the reason and how could I fix this issue.