Quantization & Model Optimization
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Optimizing a trained model means trading a little accuracy for a lot less memory, download size or latency. In the TensorFlow world three different tool sets do this, and older tutorials mix them up: Keras 3 has built-in quantize() support, the LiteRT converter has post-training quantization options, and the separate TensorFlow Model Optimization Toolkit offers quantization-aware training, pruning and clustering for Keras 2 style models. This page explains what each does, shows the code, and says which to choose. The theory of quantization (scales, zero points, per-channel, calibration, QAT versus PTQ, pruning and distillation) is on Model Compression; this page does not repeat it. Deployment targets are on On-Device Inference with LiteRT and Serving with TensorFlow Serving; the reduced-precision training counterpart is Mixed Precision, and the PyTorch equivalent is Quantization and Sparsity.
It targets Python 3.13, TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is "upcoming" and not covered), and was checked against the official Keras, LiteRT and TensorFlow documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21, Keras 3.15, tf-keras 2.21.0 and tensorflow-model-optimization 0.8.1 (CPU) on 2026-10-31; the SavedModel read by the converter examples was a small float model with a (None, 10) input exported for the run. Speed-ups on accelerators, microcontrollers and Edge TPUs were not measured.
Choosing a tool
| Goal | Tool | Notes |
|---|---|---|
Smaller or faster Keras 3 model on a server or in research code, including LLMs from KerasHub |
|
int8, int4, float8 and GPTQ modes; works on supported layers; the state is saved with the model |
Smaller |
LiteRT converter options ( |
Dynamic range, full integer and float16, applied at conversion time |
Better accuracy than post-training quantization on a small model |
Quantization-aware training |
Provided by the TensorFlow Model Optimization Toolkit, see its status below |
Smaller compressed download |
Pruning or clustering |
Do not reduce on-disk or runtime size by themselves; they make the file compress better |
A sensible order, which follows the LiteRT model optimization page: check whether a pre-optimized hosted model already fits; otherwise start with post-training quantization because it needs no training; move to quantization-aware training only if accuracy or accelerator support demand it; consider pruning or clustering to reduce download size.
Keras 3 quantization with model.quantize
Keras 3 documents quantization as a built-in feature. You build or load a floating-point model with weights, call quantize with a mode, and then use or save the model normally.
import keras
import numpy as np
rng = np.random.default_rng(0)
x_train = rng.random((100, 10)).astype("float32")
y_train = rng.random((100, 1)).astype("float32")
model = keras.Sequential([
keras.Input(shape=(10,)),
keras.layers.Dense(32, activation="relu", name="dense_1"),
keras.layers.Dense(1, name="output_head"),
])
model.compile(optimizer="adam", loss="mean_squared_error")
model.fit(x_train, y_train, epochs=1, verbose=0)
# Quantize everything except the output head
model.quantize("int8", filters=lambda layer: layer.name != "output_head")
print(model.predict(x_train[:2], verbose=0)) # two predictions, shape (2, 1)
The modes described in the Keras guide:
| Mode | What it does |
|---|---|
|
Weights and activations; per-channel weight scales and dynamic AbsMax activation scales; about 4 times smaller parameters than float32 |
|
FP8 weights with dynamic scaling; useful mainly with fused FP8 kernels on supported hardware |
|
Weight-only 4-bit; two values packed per byte; symmetric per-output-channel scales; about 8 times smaller weights than float32; activations stay in int8 |
|
Weight-only 2, 3, 4 or 8 bits; second-order post-training method that needs a small calibration dataset |
Keras 3.15 also accepts an awq mode (its list of quantization modes is int8, float8, int4, gptq and awq); the guide covers it on a separate page, and it is not described here.
What the guide says about scope and behaviour:
-
The core supported layers are
Dense,EinsumDenseandEmbedding(plusReversibleEmbeddingin KerasHub); composite layers made of them, such asMultiHeadAttentionand transformer feed-forward blocks, inherit support. Convolutions are not listed, so for CNNs use the LiteRT converter route below. -
Quantization can be applied to one layer,
layer.quantize("int4"), andfilters=accepts a regular expression, a list of expressions or a callable that returns a boolean, which is how you keep sensitive layers (input embedding, output head, logits) in higher precision. -
Weights must exist before quantizing: call
build()or run a forward pass first. -
Quantization state (packed weights, scales) survives
model.save()and loading. Quantized models can also be exported to LiteRT through the separate Keras LiteRT export guide. -
Memory savings are immediate, but speedups need fused low-precision kernels on your backend and hardware; if kernels fall back to dequantized matrix multiplications you get smaller models without faster inference. Measure both memory and latency.
-
int4 is reported competitive on encoder-only models but can lose more accuracy on decoder-only models; validate on your evaluation set after each step.
-
Activation calibration uses AbsMax only at the time of writing; the guide says other methods may be added in future releases.
-
The guide does not list backend support. With Keras 3.15,
int8,float8andint4quantization of a smallDensemodel (with the output head filtered out) followed bypredictworks on the TensorFlow, JAX and PyTorch backends;gptqandawqneed a calibration dataset and were not tried. Test the mode you need on your backend and hardware.
from keras import layers
layer = layers.Dense(32, activation="relu")
layer.build((None, 10))
layer.quantize("int4") # per-layer form
Pre-trained models from KerasHub subclass keras.Model, so they accept the same call. Evaluate the quantized model with the metrics you use for the original (see compile, fit, evaluate and predict) before replacing it.
LiteRT post-training quantization
When the destination is a .tflite file, quantization is configured on the converter. All options start from a trained float model. First convert without any optimization; that proves operator compatibility and gives a baseline for debugging accuracy loss.
import tensorflow as tf
converter = tf.lite.TFLiteConverter.from_saved_model("models/my_model/1")
# 1. Dynamic range quantization: weights to 8 bit, no data needed
converter.optimizations = [tf.lite.Optimize.DEFAULT]
dynamic_range = converter.convert()
# 2. Float16 quantization: about half the size, GPU delegate friendly
converter = tf.lite.TFLiteConverter.from_saved_model("models/my_model/1")
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_types = [tf.float16]
float16 = converter.convert()
Full integer quantization calibrates activation ranges on a representative dataset of roughly 100 to 500 unlabelled samples drawn from the real input distribution:
import numpy as np
def representative_dataset():
for _ in range(200):
# replace with real preprocessed samples, one batch of size 1 at a time
yield [np.random.rand(1, 10).astype("float32")]
converter = tf.lite.TFLiteConverter.from_saved_model("models/my_model/1")
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_dataset
# Integer-only model for microcontrollers and Edge TPUs
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8
converter.inference_output_type = tf.int8
int8_model = converter.convert()
| Option | Data needed | Documented effect |
|---|---|---|
Dynamic range |
None |
Weights 8-bit, activations quantized at run time, float outputs; about 4 times smaller and 2-3 times faster on CPU |
Full integer, float fallback |
Representative dataset |
Float input and output kept; unsupported ops stay float; will not run on integer-only accelerators |
Full integer, integer only |
Representative dataset |
Required for 8-bit microcontrollers and Edge TPUs; set input and output types to |
Float16 |
None |
Up to about half the size; GPU delegate runs float16 directly, CPU dequantizes to float32 |
16x8 (experimental) |
Representative dataset |
16-bit activations, 8-bit weights; can help audio and super-resolution models but has slow reference kernels |
Notes and pitfalls:
-
Quantized tensors follow real_value = (int8_value minus zero_point) times scale. A model with integer input expects you to quantize the input with the scale and zero point reported in
get_input_details()(see On-Device Inference with LiteRT). -
The representative generator should yield a list of input arrays in the model order. For multiple signatures the LiteRT guide recommends signature-based datasets over input-tensor lists, because input ordering is easy to mix up.
-
Representative data must be preprocessed exactly as in production; calibrating on random numbers (as the snippet does for brevity) gives poor ranges.
-
Through Keras 3
model.export(..., format="litert")the same converter options are passed as keyword arguments on the TensorFlow backend:optimizations,representative_datasetand so on. -
Always check accuracy with the same validation set. The LiteRT page shows measurements where post-training quantization lost several points of accuracy on MobileNet while quantization-aware training kept it close to the original, which is why QAT exists.
Quantization-aware training, pruning and clustering
The TensorFlow Model Optimization Toolkit (tensorflow_model_optimization, imported as tfmot) is the long-standing library for these techniques: quantization-aware training, weight pruning (tfmot.sparsity.keras.prune_low_magnitude with a schedule such as PolynomialDecay), weight clustering and collaborative optimization.
Status, as far as the official pages show on 2026-10-30:
-
The toolkit page on tensorflow.org still describes the techniques above, and its Keras example imports
tf_kerasrather than Keras 3. That suggests the toolkit works with the Keras 2 packagetf_keras, not native Keras 3 models. -
Neither that page nor the GitHub README contains a maintenance or deprecation notice or a statement of Keras 3 support, and on 2026-10-30 the repository’s Releases section was empty.
-
With
tensorflow-model-optimization0.8.1, passing a Keras 3 model toprune_low_magnituderaisesValueError(it only acceptstf_kerasSequential and functional models and layers), while thetf_kerasexample below works. Treat it as legacy-compatible tooling: if you need it, check the repository issues and install guide first, and plan to work intf_keras(see Migrating from Keras 2 to Keras 3).
# Keras 2 style usage as shown on the toolkit page (requires the tf_keras package)
import tensorflow_model_optimization as tfmot
import tf_keras as keras
base = keras.Sequential([
keras.layers.Dense(64, activation="relu", input_shape=(10,)),
keras.layers.Dense(1),
])
pruned = tfmot.sparsity.keras.prune_low_magnitude(
base,
pruning_schedule=tfmot.sparsity.keras.PolynomialDecay(
initial_sparsity=0.0, final_sparsity=0.5, begin_step=0, end_step=1000
),
)
pruned.compile(optimizer="adam", loss="mse")
# train with callbacks=[tfmot.sparsity.keras.UpdatePruningStep()], then
# tfmot.sparsity.keras.strip_pruning(pruned) before export
prune_low_magnitude, PolynomialDecay and the 0 to 50 percent sparsity example come from the toolkit page. The UpdatePruningStep callback, strip_pruning and the keyword arguments shown above exist in version 0.8.1: the model trains with the callback and strip_pruning returns a plain tf_keras Sequential (API reference: https://www.tensorflow.org/model_optimization/api_docs/python/tfmot). With PolynomialDecay, weights are only pruned every frequency steps (100 by default) between begin_step and end_step, so a short run may show no zeros yet. Remember that pruning does not shrink the on-disk or runtime model by itself; the LiteRT page says it mainly helps download size because pruned weights compress better, and that latency gains for pruned models are planned for the future.
If you need quantization-aware training and prefer to avoid the toolkit, consider the PyTorch route (Quantization and Sparsity) or distillation (see Model Compression).
Practical guidance
-
Measure first: model size, latency and accuracy on the target hardware, so you know what optimization must achieve.
-
Start with the cheapest option for your target:
model.quantizefor Keras 3 transformer-style models, dynamic range or float16 for.tflite. -
Keep sensitive layers in higher precision (first layer, output head, normalization-heavy blocks) through
filtersor by choosing float fallback. -
Re-evaluate on a validation set, not on the calibration set.
-
Record the converter, runtime and library versions, since kernels and defaults change between releases.
References
-
Keras quantization overview: https://keras.io/guides/quantization_overview/
-
Keras
Model.export(): https://keras.io/api/models/model_saving_apis/export/ -
LiteRT model optimization: https://developers.google.com/edge/litert/models/model_optimization
-
LiteRT post-training quantization: https://developers.google.com/edge/litert/conversion/tensorflow/quantization/post_training_quantization
-
TensorFlow Model Optimization Toolkit: https://www.tensorflow.org/model_optimization
-
Toolkit repository: https://github.com/tensorflow/model-optimization