SavedModel & Signatures
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A SavedModel is TensorFlow’s language-neutral serialization of a program: the trained variables plus the computation (traced tf.function graphs) needed to run it, with no dependence on the Python code that built it. It is the format consumed by TF Serving, LiteRT conversion, TensorFlow.js converters and many hosting services. This page covers the on-disk layout, tf.saved_model.save and load for tf.Module objects, serving signatures, command-line inspection, and the pitfalls. How Keras 3 produces SavedModels (model.export) is on Saving Keras Models, variables-only snapshots are on Training Checkpoints, and the underlying tf.function tracing is explained in Graphs, tf.function, AutoGraph & Retracing and Modules. Serving is on Serving with TensorFlow Serving.
It targets Python 3.13 and TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is upcoming) and was checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21 and Keras 3.15 (CPU) on 2026-10-31, including the saved_model_cli commands.
Directory layout
export/mymodel/1/
|-- saved_model.pb the program: graphs, functions and named signatures
|-- variables/ a standard training checkpoint holding the variable values
|-- assets/ files the graph needs, such as vocabulary files
|-- assets.extra/ optional extras ignored by TensorFlow
`-- fingerprint.pb content hash (experimental)
The trailing 1/ is a TF Serving convention: each numeric subdirectory is a version, and the server watches for new ones. saved_model.pb is a protocol buffer, which is limited to 2 GB; for larger models tf.saved_model.SaveOptions(experimental_image_format=True) selects a split format.
Saving and loading a tf.Module
tf.saved_model.save accepts any trackable object: tf.Module, keras.Layer and keras.Model (Keras 3 models are tracked through the TensorFlow backend; for Keras prefer model.export). What is stored is every tf.Variable reachable through attributes, every tf.function (as its cache of concrete functions) and nested modules. Arbitrary Python attributes and functions are not stored: no Python code is saved.
import tensorflow as tf
class Scaler(tf.Module):
def __init__(self):
super().__init__()
self.scale = tf.Variable(2.0, name="scale")
@tf.function(input_signature=[tf.TensorSpec(shape=[None], dtype=tf.float32)])
def __call__(self, x):
return x * self.scale
@tf.function(input_signature=[tf.TensorSpec(shape=[], dtype=tf.float32)])
def set_scale(self, value):
self.scale.assign(value)
module = Scaler()
tf.saved_model.save(module, "export/scaler/1")
imported = tf.saved_model.load("export/scaler/1")
print(imported(tf.constant([1.0, 2.0])).numpy()) # [2. 4.]
imported.set_scale(tf.constant(10.0))
print(imported(tf.constant([1.0, 2.0])).numpy()) # [10. 20.]
What load returns is a restored object that has the same variables and callables, but it is not an instance of your original class: there are no other methods, no Python attributes and no isinstance relationship. Calling a restored tf.function with a shape or dtype that was never traced raises a ValueError ("Could not find matching concrete function to call loaded from the SavedModel"); with an input_signature, an incompatible input raises a TypeError ("Binding inputs to tf.function failed") instead. That is why giving each method a fixed input_signature (with None for dynamic dimensions) is the standard practice before saving.
Variables are restored as tf.Variable objects, so simple fine-tuning works: run the imported callable inside a tf.GradientTape and apply gradients to imported.trainable_variables. For reusable fine-tunable modules, the guide recommends exposing a training argument and the variables, trainable_variables and regularization_losses attributes.
Signatures
A signature is a named entry point with flat, named inputs and outputs, built for consumers that do not speak Python (TF Serving, the C++ API, the CLI). Keras models get signatures automatically; a plain tf.Module has none unless you request them.
module = Scaler()
call = module.__call__.get_concrete_function(tf.TensorSpec([None], tf.float32))
tf.saved_model.save(module, "export/scaler_sig/1", signatures=call) # becomes serving_default
# Several named signatures; this one returns a dict, so its output is named "scaled"
@tf.function(input_signature=[tf.TensorSpec([None], tf.float32)])
def scaled(x):
return {"scaled": module(x)}
signatures = {"serving_default": call, "named": scaled}
tf.saved_model.save(module, "export/scaler_multi/1", signatures=signatures)
loaded = tf.saved_model.load("export/scaler_multi/1")
infer = loaded.signatures["serving_default"]
out = infer(x=tf.constant([1.0, 2.0])) # keyword arguments only, returns a dict
print(out) # {'output_0': <tf.Tensor: shape=(2,), ... numpy=array([2., 4.], ...)>}
print(loaded.signatures["named"](x=tf.constant([1.0, 2.0]))) # {'scaled': <tf.Tensor: ...>}
Rules and details:
-
A single signature is stored under
serving_default(tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY), which is the key TF Serving uses when the client names none. -
Imported signatures take keyword arguments and always return a dictionary. The input names come from the Python argument names of the traced function.
-
Output names are generic (
output_0) unless the function returns a dict:return {"scaled": x * self.scale}yields an output calledscaled. Return named outputs to keep client code readable and stable. -
Signatures are required only for consumers outside Python and TF2. Python callers can use the restored functions directly.
-
A signature is a concrete function, so shapes and dtypes are fixed at export time apart from the dimensions you left as
None.
Inspecting with saved_model_cli
The saved_model_cli tool ships with the TensorFlow wheel. Use it to check what a client will see before deploying.
saved_model_cli show --dir export/scaler_multi/1 # tag-sets
saved_model_cli show --dir export/scaler_multi/1 --tag_set serve # signature keys
saved_model_cli show --dir export/scaler_multi/1 --tag_set serve --signature_def serving_default
saved_model_cli show --dir export/scaler_multi/1 --all # everything
saved_model_cli run --dir export/scaler_multi/1 --tag_set serve \
--signature_def serving_default --input_exprs 'x=[1.0, 2.0]' # prints: Result for output key output_0: [2. 4.]
run can feed inputs from .npy/.npz files (--inputs), from Python literals (--input_exprs) or from tf.train.Example literals (--input_examples), and write the outputs as .npy files with --outdir. In TensorFlow 2.21 --input_exprs parses each value with ast.literal_eval, so NumPy expressions such as 'x=np.array([1.0, 2.0])', which older tutorials show, fail with RuntimeError: Expression "np.array([1.0, 2.0])" is not a valid python literal.; write plain lists instead, or save arrays to .npy files for --inputs.
From Keras to SavedModel
In Keras 3 the supported route is model.export(path) or keras.export.ExportArchive, both described on Saving Keras Models. The TensorFlow guide marks the older “save a Keras object with tf.saved_model.save” route as deprecated in favour of the .keras format and export, while the low-level format itself remains supported. A Keras 3 model exported this way exposes an endpoint named serve, and a serving_default signature for TF Serving (loading the export with tf.saved_model.load shows both keys in signatures).
A SavedModel produced elsewhere can be used inside a Keras 3 model through keras.layers.TFSMLayer. Its constructor in Keras 3.15 is TFSMLayer(filepath, call_endpoint="serve", call_training_endpoint=None, trainable=True, name=None, dtype=None). call_endpoint names the endpoint or signature to call (serve or serving_default for a Keras export; a signature returns a dict such as {'output_0': ...}). The layer is meant for inference; to train through it the SavedModel must also provide a training endpoint, passed as call_training_endpoint.
Security and portability
The guide’s own warning applies: TensorFlow models are code. A SavedModel graph can contain operations that read or write files and perform other side effects, so load only models from trusted sources and treat third-party models like downloaded executables. Custom ops used in the graph must be available at load time (a custom op library has to be loaded before load), and a model that uses ops from tensorflow-text requires that package to be imported. The producer and consumer TensorFlow versions need to be compatible; newer versions load older SavedModels, but not necessarily the reverse.
For long-term archival or sharing across frameworks, consider ONNX (ONNX & Interoperability); for phones and embedded devices, LiteRT; for details on formats on model hubs, Model formats. The PyTorch counterpart is torch.export.
Common mistakes
-
Saving a
tf.functionmethod withoutinput_signatureand then calling the reloaded model with a new shape or dtype. -
Storing state in plain Python attributes (lists, counters), which is lost on reload; use
tf.Variableor tracked containers. -
Expecting
loadto give back the original class and its methods. -
Forgetting
signatures=for atf.Module, so TF Serving has noserving_default. -
Returning a bare tensor and getting an unhelpful
output_0name in the REST/gRPC response. -
Using the old TF1 SavedModel builders,
tf.compat.v1.saved_model, and session tags for new code; TF2 code usestf.saved_model.saveandload. -
Writing a new version into an existing numeric directory while a server is watching it, instead of writing to a fresh directory and renaming it into place.