【发布时间】:2022-08-22 17:23:08
【问题描述】:
我有一个使用 TFRS 库的相对较大的 TF 检索模型。它为indexing the recommendations 使用ScaNN 层。当我尝试通过tf.saved_model.save() 方法保存此模型时,我遇到了系统主机内存问题。我在云中的虚拟机上运行带有 TFRS 的官方 TF 2.9.1 Docker 容器。我有 28 GB 的内存来尝试保存模型。
Here is the quickstart example:
基本上我们创建了第一个嵌入
user_model = tf.keras.Sequential([
tf.keras.layers.StringLookup(
vocabulary=unique_user_ids, mask_token=None),
# We add an additional embedding to account for unknown tokens.
tf.keras.layers.Embedding(len(unique_user_ids) + 1, embedding_dimension)
])
然后创建模型
class MovielensModel(tfrs.Model):
def __init__(self, user_model, movie_model):
super().__init__()
self.movie_model: tf.keras.Model = movie_model
self.user_model: tf.keras.Model = user_model
self.task: tf.keras.layers.Layer = task
def compute_loss(self, features: Dict[Text, tf.Tensor], training=False) -> tf.Tensor:
# We pick out the user features and pass them into the user model.
user_embeddings = self.user_model(features[\"user_id\"])
# And pick out the movie features and pass them into the movie model,
# getting embeddings back.
positive_movie_embeddings = self.movie_model(features[\"movie_title\"])
# The task computes the loss and the metrics.
return self.task(user_embeddings, positive_movie_embeddings)
接下来我们创建 ScaNN 索引层
scann_index = tfrs.layers.factorized_top_k.ScaNN(model.user_model)
scann_index.index_from_dataset(
tf.data.Dataset.zip((movies.batch(100), movies.batch(100).map(model.movie_model)))
)
# Get recommendations.
_, titles = scann_index(tf.constant([\"42\"]))
print(f\"Recommendations for user 42: {titles[0, :3]}\")
最后将模型发送出去保存
# Export the query model.
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, \"model\")
# Save the index.
tf.saved_model.save(
index,
path,
options=tf.saved_model.SaveOptions(namespace_whitelist=[\"Scann\"])
)
# Load it back; can also be done in TensorFlow Serving.
loaded = tf.saved_model.load(path)
# Pass a user id in, get top predicted movie titles back.
scores, titles = loaded([\"42\"])
print(f\"Recommendations: {titles[0][:3]}\")
这是问题行:
# Save the index.
tf.saved_model.save(
index,
path,
options=tf.saved_model.SaveOptions(namespace_whitelist=[\"Scann\"])
)
我不确定是否存在内存泄漏或什么,但是当我在 5M+ 记录上训练我的模型时......我可以看到主机系统内存达到 100% 并且进程被终止。如果我在较小的数据集上训练......没有问题,所以我知道代码没问题。
谁能建议在保存大型 ScaNN 检索模型时如何解决内存瓶颈,以便我最终可以将模型重新加载以进行推理?
标签: python tensorflow