Embed Keras Preprocessing Layers Inside the SavedModel
Move normalization and vectorization into the SavedModel so raw input enters one artifact and training/serving skew stays out of the pipeline.
25 Mar 2026, 03:00 UTC

The problem: preprocessing drift between training and serving
When normalization, tokenization, or encoding happens outside the model, the training pipeline and the serving pipeline can drift apart. A feature scaled with training statistics in one place and serving statistics in another silently changes model inputs. Keras preprocessing layers such as Normalization and TextVectorization let you move those transformations inside the model graph so the SavedModel accepts raw input and applies the same learned statistics everywhere.
Useful takeaway: adapt preprocessing layers on training data only, bake them into the model with model.save() in SavedModel format, and treat the exported artifact as the single boundary between raw data and model logic.
Requirements
- Numeric features need consistent mean and variance at training and inference.
- Text features need a fixed vocabulary and out-of-vocabulary (OOV) handling.
- The exported model must run without a separate preprocessing script.
- Training statistics must never leak from validation or test data.
Smallest suitable design
Use one Normalization layer for numeric inputs and one TextVectorization layer for text inputs. Call adapt() once on the training split, then include both layers as the first layers of the model. Export with SavedModel format so the adapted weights travel with the model.
Trust and data boundaries
The trust boundary moves from "preprocessing script plus model" to "model only." Raw strings and raw numbers enter the SavedModel; the model applies normalization and vectorization internally. This removes a whole class of serving bugs where the application code transforms data differently than the training code did.
The layer state learned by adapt()—mean and variance for Normalization, vocabulary for TextVectorization—is part of the model weights. Anyone who can load the model can see those statistics, so treat training data summaries as part of the model artifact for access control and auditing.
Operational checks
Adapt only on training data
Never pass validation or test examples to adapt(). If you do, test statistics influence the transformation and leak information into the model input pipeline.
Confirm adapted state survives save and reload
After adapt(), inspect layer.get_weights(). For Normalization, expect arrays for mean and variance. For TextVectorization, expect the vocabulary tensor. After model.save() and tf.keras.models.load_model(), inspect the same layer again. If the weights are empty or the vocabulary is missing, the export format did not preserve the state.
Compare raw-input predictions against an external pipeline
Run model.predict() on raw strings and numbers. Separately, preprocess the same inputs with the adapted layers outside the model or with equivalent manual code, then run the core model. The outputs should match. Any difference indicates a serialization or vocabulary mismatch.
Failure modes
- Data leakage: adapt() sees validation or test data, so serving statistics reflect unseen examples.
- Vocabulary mismatch: new tokens at inference are routed to OOV buckets by TextVectorization, which changes the input distribution compared with training if OOV rates are high.
- Serialization loss: HDF5 format in TensorFlow older than 2.11 does not reliably store adapted preprocessing state. SavedModel is required for production.
- Shape errors: adapt() expects batched input. Passing unbatched examples raises a shape error.
- Memory pressure: very large vocabularies increase model size and adaptation time.
Conditions that change the design
- Dynamic vocabulary updates require an external lookup service; Keras preprocessing layers are frozen after export.
- Extremely large vocabularies may exceed memory; consider Hashing or subword tokenization outside Keras.
- Regulatory requirements for auditable preprocessing separate from model code argue for keeping transformations in a versioned pipeline rather than inside the SavedModel.
- Multi-worker training: call adapt() on one worker or a coordinated dataset; the adapted state is broadcast when the model is built.
Example configuration
The following example assumes TensorFlow 2.11 or later and tf.keras. It builds a tiny model, adapts preprocessing layers on training data only, exports to SavedModel, and reloads in a fresh process.
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# Placeholder data: replace with your own training splits.
train_texts = ["this is a training example", "another training sentence"]
train_numbers = [[1.0, 2.0], [3.0, 4.0]]
# 1. Create preprocessing layers.
text_vectorizer = layers.TextVectorization(max_tokens=1000, output_sequence_length=8)
normalizer = layers.Normalization()
# 2. Adapt on training data only. Batch the adaptation dataset.
text_vectorizer.adapt(tf.data.Dataset.from_tensor_slices(train_texts).batch(2))
normalizer.adapt(tf.data.Dataset.from_tensor_slices(train_numbers).batch(2))
# 3. Build a model that accepts raw input.
text_input = keras.Input(shape=(1,), dtype=tf.string, name="text")
number_input = keras.Input(shape=(2,), dtype=tf.float32, name="numbers")
text_features = text_vectorizer(text_input)
text_features = layers.Embedding(input_dim=1000 + 1, output_dim=4)(text_features)
text_features = layers.GlobalAveragePooling1D()(text_features)
number_features = normalizer(number_input)
merged = layers.Concatenate()([text_features, number_features])
output = layers.Dense(1)(merged)
model = keras.Model(inputs=[text_input, number_input], outputs=output)
model.compile(optimizer="adam", loss="mse")
# 4. Export as SavedModel. Do not use save_format="h5" for adapted state.
export_path = "/tmp/keras_preprocessing_model"
model.save(export_path) # SavedModel format by default in tf.keras
# 5. Reload in a new process and check state.
reloaded = keras.models.load_model(export_path)
reloaded_text_layer = reloaded.get_layer(name="text_vectorization") # name may vary
reloaded_normalizer = reloaded.get_layer(name="normalization") # name may vary
print(reloaded_text_layer.get_weights()) # expect non-empty vocabulary
print(reloaded_normalizer.get_weights()) # expect mean and variance arrays
Where to run: a local machine or training container with TensorFlow installed. Permissions: write access to export_path. Risks: overwriting an existing SavedModel at export_path; adapt() on unbatched data raises a shape error; adapting on validation data causes leakage. Expected check: layer.get_weights() is non-empty after adapt() and after reload.
Practical verification
- Create a minimal model with Normalization and TextVectorization layers.
- Adapt on a toy training dataset only.
- Save as SavedModel and reload in a fresh Python process.
- Assert predictions on raw input match a manual preprocessing plus model pipeline.
- Check layer.get_weights() before and after save/load to confirm adapted statistics persist.
Limitations
Preprocessing layers are frozen at export time. They do not update vocabulary or statistics from live traffic. TextVectorization handles unseen tokens with OOV buckets, but high OOV rates can degrade accuracy. Adapted state can be large for wide vocabularies, increasing SavedModel size. If you need preprocessing that is auditable separately from model weights, keep the transformation outside the model and accept the drift risk that comes with maintaining two pipelines.
Rollback
Saving to export_path changes filesystem state. If the SavedModel is corrupt or missing adapted state, delete the directory and re-run the adapt and export steps. There is no in-place rollback for a SavedModel; treat the directory as disposable and regenerate it from training code.