You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让TF2.3保存的SavedModel支持TF>=2.5下persistent=True的GradientTape

问题描述

我将ASTER项目的TF1版本模型转换为TF2格式,使用TensorFlow 2.3保存为SavedModel格式。根据相关公开issue说明,TensorFlow 2.5之前版本保存的SavedModel无法搭配tf.GradientTape(persistent=True)使用,而这正是我需要用到的功能。
请问是否有方法让该模型支持tf.GradientTape(persistent=True)调用?
补充说明:当时编写的全部模型转换代码已经丢失,无法重新生成模型。

代码示例

本次使用的模型可通过公开分享的谷歌云盘路径下载。

import tensorflow as tf
import tensorflow_addons as tfa

MODEL_FOLDER_PATH = ""
model = tf.saved_model.load(MODEL_FOLDER_PATH, tags="serve").signatures[
    "serving_default"
]
tfa.register_all(custom_kernels=False)  # 原模型用到了tensorflow addons,必须执行该行完成自定义算子注册

@tf.function
def without_persistent_gradient(model):
    with tf.GradientTape():
        model(tf.ones((1, 64, 256, 3)))

@tf.function
def with_persistent_gradient(model):
    with tf.GradientTape(persistent=True):
        model(tf.ones((1, 64, 256, 3)))

without_persistent_gradient(model)   # 可正常运行
with_persistent_gradient(model)  # 会抛出错误

运行后得到的报错信息如下:

ValueError: Internal error: Tried to take gradients (or similar) of a variable without handle data:
Tensor("Backward/Predictor/decoder/while:13", shape=(), dtype=resource)
已尝试的解决方案
  • 首先尝试使用TF2.8重新保存该模型,执行代码如下:
tf.saved_model.save(model, "my/path")

执行后抛出如下错误:

KeyError: "Failed to add concrete function 'b'__inference_pruned_12028'' to object-based SavedModel as it captures tensor <tf.Tensor: shape=(), dtype=resource, value=<Resource Tensor>> which is unsupported or not reachable from root. One reason could be that a stateful object or a variable that the function depends on is not assigned to an attribute of the serialized trackable object (see SaveTest.test_captures_unreachable_variable)."
  • 之后尝试通过tensorflow_hub库将其转换为Keras Model,但使用tf.GradientTape(persistent=True)时仍然会抛出相同错误,转换代码如下:
from tensorflow_hub import KerasLayer
input_layer = tf.keras.layers.Input((64, 256, 3))
model_layer = KerasLayer("my/path", tags="serve",signature="serving_default", signature_outputs_as_dict=True)
model = tf.keras.Model(input_layer, model_layer(input_layer))
运行环境配置
  • Python版本:3.9.12
  • 操作系统:Linux 18.04
  • 运行硬件:CPU
  • 依赖版本:tensorflow==2.8、tensorflow-addons==0.16

内容的提问来源于stack exchange,提问作者Noé Achache

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 10:42:22