Almost every TensorFlow engagement we start in 2026 has at least one model in it that was not trained in TensorFlow. A data science team prototyped in PyTorch. A vendor shipped a Hugging Face checkpoint. An acquisition brought in a JAX codebase. Meanwhile the client's production stack - TF Serving, LiteRT on devices, TensorFlow.js in the browser, a TFX pipeline with lineage - is TensorFlow, and nobody wants to rebuild it around a second runtime.
The reflex answer, "rewrite the model in Keras and retrain", is usually the most expensive option on the table and the one most likely to silently change behaviour. This tutorial covers the cheaper paths: what actually converts cleanly between frameworks, how to do each conversion, and - the part teams skip - how to prove the converted model gives the same answers as the original before it goes anywhere near traffic.
Decide the path before you convert anything
Four questions settle the approach:
- Do you need to keep training the model, or only to serve it? Inference-only is far easier and is the majority of cases.
- Where does it have to run? A TF Serving container, a Kubernetes deployment, a phone, a browser, or inside an existing TFX pipeline - each has a different preferred artifact.
- Does the architecture exist in KerasHub? If so, loading the weights into a native Keras model beats any graph conversion.
- How exotic are the ops? Custom CUDA kernels, dynamic control flow, and ragged shapes are where converters break.
That gives you three realistic routes:
| Situation | Route | Resulting artifact |
|---|---|---|
| Architecture available in KerasHub (Gemma, BERT-family, ViT, many more) | Load the checkpoint natively with from_preset | .keras preset / SavedModel |
| Keep the model code, change only where it runs | Keras 3 on the PyTorch backend, or rewrite layers with keras.ops | .keras / SavedModel |
| Inference only, arbitrary PyTorch/HF model | Export to ONNX, serve ONNX Runtime, or convert ONNX to a SavedModel | .onnx or SavedModel |
There is no supported route for "convert an arbitrary PyTorch training loop into a TensorFlow training loop automatically". Do not promise one.
Route 1: load the checkpoint natively with KerasHub
This is the happiest path and it is underused. KerasHub ships presets for a long list of architectures and can load a number of them directly from Hugging Face Hub identifiers:
import os
os.environ["KERAS_BACKEND"] = "tensorflow"
import keras_hub
model = keras_hub.models.CausalLM.from_preset("hf://google/gemma-2-2b")
print(model.generate("A converted model should be verified because", max_length=64))
The task classes (CausalLM, TextClassifier, ImageClassifier, and friends) carry the tokenizer or image preprocessor with them, which removes the single most common source of post-conversion mismatch: subtly different preprocessing. Check the KerasHub model list before you reach for a converter - support has widened a lot, and a natively loaded model is a first-class Keras object you can fine-tune (see our Gemma LoRA tutorial), quantize, and export like any other.
When the architecture is supported but the exact checkpoint is not, you can often still build the Keras model and port weights by name. That is a day of work and a test harness, not a rewrite.
Route 2: keep the code, change the backend
If the team owns the model code and it is Keras-shaped, Keras 3 lets the same source run on TensorFlow, JAX, or PyTorch - train where the GPUs and the team's muscle memory are, export a TensorFlow SavedModel for serving. We covered the mechanics in One Model, Three Backends; the short version is: write layers with keras.ops, set KERAS_BACKEND explicitly in every container, and call model.export() on the TensorFlow backend when you need a SavedModel.
Keras 3 can also wrap native modules - a torch.nn.Module can be used inside a Keras model on the PyTorch backend. That is a useful bridge for incremental migration, but be clear-eyed: a model containing a Torch module cannot be exported to a TensorFlow SavedModel. It is a staging post, not a destination.
Route 3: ONNX as the interchange format
For inference-only work on an arbitrary model, ONNX is the practical lingua franca.
Export PyTorch to ONNX
import torch
model.eval()
example = torch.randn(1, 3, 224, 224)
torch.onnx.export(
model,
(example,),
"model.onnx",
dynamo=True, # TorchDynamo-based exporter
input_names=["pixel_values"],
output_names=["logits"],
dynamic_shapes={"pixel_values": {0: "batch"}},
opset_version=18,
)
Notes that save hours:
- Name your inputs and outputs. Serving configs, monitoring, and every debugging session depend on them.
- Make the batch dimension dynamic. A model exported with a hard-coded batch of 1 will embarrass you under load.
- Export in eval mode. Dropout and batch-norm in training mode are a classic source of "it scores differently in production".
- For Hugging Face transformer models, prefer
optimum-cli export onnx --model <id> out/, which handles the past-key-value plumbing for generative models that hand-rolled exports get wrong.
Then validate the graph itself:
import onnx
onnx.checker.check_model(onnx.load("model.onnx"))
Serve ONNX directly
Often you should just stop here. ONNX Runtime is fast, has mature CPU and CUDA/TensorRT execution providers, and both KServe and Triton serve ONNX natively - so a model in ONNX form drops into the Kubernetes setup from our KServe tutorial without a second conversion step. If the only reason you want a SavedModel is "our stack is TensorFlow", weigh that against running one extra runtime image.
import numpy as np, onnxruntime as ort
sess = ort.InferenceSession("model.onnx", providers=["CPUExecutionProvider"])
out = sess.run(["logits"], {"pixel_values": np.random.randn(1, 3, 224, 224).astype("float32")})
Convert ONNX to a TensorFlow SavedModel
When you genuinely need a SavedModel - TFX lineage, TF Serving version labels, LiteRT or TensorFlow.js downstream - convert with onnx2tf, which is maintained and, importantly, handles the NCHW-to-NHWC layout transposition that naive converters leave as a forest of transpose ops:
pip install onnx2tf onnx onnx_graphsurgeon sng4onnx
onnx2tf -i model.onnx -o saved_model/ -osd # -osd also writes a SavedModel dir
Then load and re-export with the signature you want, exactly as in Serving TensorFlow Models in Production:
import tensorflow as tf
loaded = tf.saved_model.load("saved_model")
infer = loaded.signatures["serving_default"]
print(infer.structured_input_signature)
print(infer.structured_outputs)
Two things go wrong here more than anything else. First, layout: PyTorch is channels-first, TensorFlow is channels-last, and if the converter did not fold the transposes you will see both a correctness risk and a serious throughput hit. Second, preprocessing: the normalisation constants, resize interpolation, and tokenizer from the source framework do not come along with the graph. Port them deliberately into Keras preprocessing layers or into the serving signature, and test them separately.
The part that is not optional: a parity harness
A conversion is not done when the file exists. It is done when you can show the new artifact matches the old one on data you care about. We write this harness before the conversion, and it is the deliverable clients remember.
import numpy as np
def max_abs_diff(a, b):
return float(np.max(np.abs(np.asarray(a) - np.asarray(b))))
# 1. Golden inputs: not random noise. Real samples, plus the nasty edge cases.
golden = np.load("golden_inputs.npy") # shape [N, 3, 224, 224]
src_out = np.load("golden_outputs_pytorch.npy") # captured from the original model
tf_out = np.stack([
infer(tf.constant(x[None].transpose(0, 2, 3, 1)))["logits"].numpy()[0]
for x in golden
])
d = max_abs_diff(src_out, tf_out)
print("max abs diff:", d)
assert d < 1e-4, "numerical parity failed"
# 2. Decision parity matters more than float parity.
assert (src_out.argmax(-1) == tf_out.argmax(-1)).mean() == 1.0
# 3. Task metric on a held-out set, both models, same preprocessing.
Guidance on thresholds, from doing this repeatedly:
- 1e-5 to 1e-4 max absolute difference on float32 logits is normal and fine.
- Anything above 1e-3 means a real difference - usually fused ops, an epsilon mismatch in normalisation layers, or different resize behaviour. Investigate; do not widen the tolerance.
- Argmax/top-k agreement should be 100% on your golden set. If it is 99.2%, find out which 0.8% and why before shipping.
- Compare the end task metric too. Numerical parity on logits with a different preprocessing path still gives you a worse model.
- Benchmark latency and throughput, both artifacts, same hardware, same batch sizes. Conversions can be slower as well as faster; a transpose-ridden graph is a common cause.
Wire this harness into CI as a golden test so a converter upgrade cannot quietly change behaviour - the pattern from our testing and CI tutorial.
Mobile and browser targets
If the destination is a phone or a browser, you do not necessarily need a SavedModel in the middle. LiteRT can ingest models originating from several frameworks, and ONNX Runtime has mobile and web builds of its own. Benchmark both paths on the actual device class before committing - see Migrating from TensorFlow Lite to LiteRT and our browser inference tutorial. Quantize after you have established parity in float, never before, or you will not know which step changed the numbers; our quantization guide covers the sequencing.
Treat the converted model as a supply-chain artifact
A .onnx or a SavedModel that arrived from outside your organisation deserves the same scrutiny as any third-party checkpoint: scan it, pin the producing toolchain, record the source commit and converter versions in your model registry, and sign the artifact. ONNX graphs are less dangerous than pickled weights, but "less dangerous" is not "trusted". Our model supply-chain tutorial has the mechanics.
Record, alongside every converted artifact: source framework and version, source checkpoint hash, converter and opset versions, the parity report, and the benchmark numbers. Six months later, when someone asks why production disagrees with the research notebook, that record is the whole answer.
When to stop converting and just retrain
Be willing to call it. Convert when the model is stable, inference-only, and built from standard ops. Retrain natively when the model needs continued fine-tuning in your stack, when it uses custom kernels or heavy dynamic control flow, when the conversion keeps failing parity, or when the architecture is simple enough that reproducing it in Keras 3 is a week's work with a better long-term outcome. A converted graph you cannot modify is technical debt with a timer on it.
Cross-framework migrations are a large slice of what our consultants are brought in for: an ML model that works in one ecosystem and a production platform that lives in another. If you have a PyTorch or Hugging Face model that needs to run in a TensorFlow stack - or you want an independent parity audit of a conversion somebody already did - get in touch, or read more about how we scope this work on our TensorFlow Modernization & Migration page.