Skip to main content

Converting TensorFlow Models to ONNX

TensorFlow models can be converted to ONNX format using the tf2onnx library, which provides robust conversion capabilities for both TensorFlow and Keras models.

Prerequisites

Basic Conversion

Converting a Keras Model

Converting from SavedModel

Converting HuggingFace Transformers (TensorFlow)

Example workflow for converting BERT models from TensorFlow:

Handling Encoder-Decoder Models

For sequence-to-sequence models like T5:

Large Model Conversion

For models larger than 2GB, use the large model format:

Command Line Conversion

From SavedModel

From Checkpoint

From Frozen Graph

Validating TensorFlow to ONNX Conversion

Handling Special Cases

Models with Custom Layers

For models with custom layers, you may need to register custom operators:

Fixing Pad Token Issues

CPU Affinity for Performance

When loading TensorFlow models, you may need to manage CPU affinity:

Best Practices

  1. Disable training mode: Set training=False when running the model
  2. Disable caching: Set use_cache=False for models that support it
  3. Use dynamic shapes: Specify None for batch and sequence dimensions
  4. Validate conversion: Always compare TensorFlow and ONNX outputs
  5. Handle special tokens: Configure tokenizer properly before conversion
  6. Set opset version: Use opset 14 or higher for better compatibility
  7. Test edge cases: Validate with various input sizes

Troubleshooting

Common Errors

“Op type not supported”: Update tf2onnx or use a different opset version
Shape inference issues: Provide explicit input shapes in the spec Memory errors: Use large_model=True for models > 2GB

Next Steps