'part_to_model') hit "Called a function referencing variables which have been deleted."

I am trying to follow Google video to create a Q&A system with Vertex AI. (Building a question answering system with Vertex AI - YouTube)

But it is suck that the video didn’t come with any source code or github repo. So, I typed the codes by myself and I am newbie to Python and TF :slight_smile:

Here is my code:

import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow import keras

class CustomModel(keras.Model):
    def __init__(self):
        super(CustomModel, self).__init__()
        module = hub.load('')
        self.encoder = module.signatures['question_encoder']
        self.built = True

    def call(self, inputs):
        return self.encoder(input=inputs)['outputs']

model = CustomModel()

model(tf.constant(["this is hello world"]))'path_to_my_model')

And the error happened at

AssertionError: Called a function referencing variables which have been deleted. This likely means that function-local variables were created and not referenced elsewhere in the program. This is generally a mistake; consider storing variables in an object attribute on first call.

Anyone can help?


Welcome to the Tensorflow Forum!

This can happen if you create function-local variables inside the __init__ method of your custom model and those variables are not stored in an object attribute

You can try storing the module and encoder objects as object attributes as shown below

    self.module = hub.load('')
    self.encoder = self.module.signatures['question_encoder']

Please refer to the working gist.

Thank you!