Chapter 2: Model Formats & Serialization

WIA-AI-008 Standard • Estimated reading time: 45 minutes

2.1 Understanding Model Serialization

Serialization is the process of converting a model's in-memory representation into a format that can be stored on disk or transmitted over a network. This fundamental operation enables model persistence, versioning, and distribution. Different frameworks approach serialization with varying philosophies and technical implementations.

What Gets Serialized?

A complete model serialization typically includes:

2.2 PyTorch Serialization Formats

PyTorch provides multiple serialization mechanisms, each suited for different use cases.

torch.save() and torch.load()

The most basic serialization uses Python's pickle protocol:

import torch

# Save entire model (architecture + weights)
torch.save(model, 'model.pth')

# Save only state dict (weights only)
torch.save(model.state_dict(), 'weights.pth')

# Save checkpoint with additional info
torch.save({
    'epoch': 100,
    'model_state_dict': model.state_dict(),
    'optimizer_state_dict': optimizer.state_dict(),
    'loss': 0.123,
    'accuracy': 0.956
}, 'checkpoint.pth')

# Loading
model = torch.load('model.pth')  # Full model
model.load_state_dict(torch.load('weights.pth'))  # Weights only
Best Practice: Save state_dict rather than the entire model. This provides more flexibility when model architecture changes slightly and avoids pickle-related compatibility issues.

TorchScript

TorchScript creates a serializable, optimizable representation that can run without Python:

import torch

# Tracing method (records operations)
example_input = torch.randn(1, 3, 224, 224)
traced_model = torch.jit.trace(model, example_input)
traced_model.save('model_traced.pt')

# Scripting method (analyzes code)
scripted_model = torch.jit.script(model)
scripted_model.save('model_scripted.pt')

# Load TorchScript model
loaded_model = torch.jit.load('model_traced.pt')

When to Use Each Format

Format Use Case Pros Cons
torch.save (full) Quick experiments Simplest to use Fragile to code changes
state_dict Production checkpoints Flexible, portable Requires architecture code
TorchScript C++ deployment, mobile No Python dependency Limited Python feature support

2.3 TensorFlow Serialization Formats

TensorFlow's serialization evolved significantly between TF 1.x and TF 2.x, with SavedModel becoming the standard format.

SavedModel Format

SavedModel is TensorFlow's universal serialization format:

import tensorflow as tf

# Save model
model = tf.keras.models.Sequential([...])
model.save('my_model')  # Creates directory with saved_model.pb

# Customize signatures
@tf.function(input_signature=[tf.TensorSpec(shape=[None, 224, 224, 3], dtype=tf.float32)])
def serve(x):
    return model(x)

tf.saved_model.save(model, 'my_model', signatures={'serving_default': serve})

# Load model
loaded_model = tf.saved_model.load('my_model')
# Or for Keras models:
loaded_model = tf.keras.models.load_model('my_model')

HDF5 Format (.h5)

Legacy Keras format, still widely used:

# Save to HDF5
model.save('model.h5')

# Save weights only
model.save_weights('weights.h5')

# Load
model = tf.keras.models.load_model('model.h5')

Checkpoint Format

For training checkpoints:

checkpoint = tf.train.Checkpoint(
    optimizer=optimizer,
    model=model
)

# Save checkpoint
checkpoint.save('checkpoints/ckpt')

# Restore
checkpoint.restore('checkpoints/ckpt-10')

2.4 JAX Model Serialization

JAX doesn't have built-in serialization since it's a functional framework. The community uses several approaches:

Using Pickle

import pickle
import jax.numpy as jnp

# Save parameters
params = {'w': jnp.array([1., 2., 3.]), 'b': jnp.array(0.5)}
with open('params.pkl', 'wb') as f:
    pickle.dump(params, f)

# Load parameters
with open('params.pkl', 'rb') as f:
    loaded_params = pickle.load(f)

Using MessagePack/Orbax

from flax import serialization

# Serialize to bytes
bytes_output = serialization.to_bytes(params)

# Save to file
with open('params.msgpack', 'wb') as f:
    f.write(bytes_output)

# Load
with open('params.msgpack', 'rb') as f:
    loaded_params = serialization.from_bytes(params, f.read())

2.5 ONNX Format Deep Dive

ONNX (Open Neural Network Exchange) is a framework-agnostic format that serves as a universal intermediate representation.

ONNX File Structure

An ONNX file (.onnx) contains:

import onnx

# Load and inspect ONNX model
model = onnx.load('model.onnx')

print(f"IR Version: {model.ir_version}")
print(f"Producer: {model.producer_name}")
print(f"Opset Version: {model.opset_import[0].version}")

# Check model validity
onnx.checker.check_model(model)

# Print graph info
graph = model.graph
print(f"Inputs: {[i.name for i in graph.input]}")
print(f"Outputs: {[o.name for o in graph.output]}")
print(f"Nodes: {len(graph.node)}")

Export to ONNX

From PyTorch:

import torch.onnx

dummy_input = torch.randn(1, 3, 224, 224)

torch.onnx.export(
    model,                          # Model
    dummy_input,                    # Example input
    "resnet50.onnx",               # Output file
    export_params=True,             # Store weights
    opset_version=14,              # ONNX version
    do_constant_folding=True,      # Optimize constant folding
    input_names=['input'],         # Input names
    output_names=['output'],       # Output names
    dynamic_axes={                  # Variable dimensions
        'input': {0: 'batch_size'},
        'output': {0: 'batch_size'}
    }
)

From TensorFlow:

import tf2onnx

# Convert SavedModel to ONNX
python -m tf2onnx.convert \
    --saved-model my_model \
    --output model.onnx \
    --opset 14

# Or programmatically
import tensorflow as tf
import tf2onnx

spec = (tf.TensorSpec((None, 224, 224, 3), tf.float32, name="input"),)
output_path = "model.onnx"

model_proto, _ = tf2onnx.convert.from_keras(model, input_signature=spec, opset=14)
with open(output_path, "wb") as f:
    f.write(model_proto.SerializeToString())

2.6 TensorFlow Lite Format

TensorFlow Lite (.tflite) is optimized for mobile and edge devices:

import tensorflow as tf

# Convert to TFLite
converter = tf.lite.TFLiteConverter.from_saved_model('my_model')

# Optimization options
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_types = [tf.float16]  # FP16 quantization

tflite_model = converter.convert()

# Save
with open('model.tflite', 'wb') as f:
    f.write(tflite_model)

# Inference
interpreter = tf.lite.Interpreter(model_path='model.tflite')
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])

2.7 CoreML Format

CoreML is Apple's format for iOS/macOS deployment:

import coremltools as ct

# Convert PyTorch to CoreML
example_input = torch.rand(1, 3, 224, 224)
traced_model = torch.jit.trace(model, example_input)

coreml_model = ct.convert(
    traced_model,
    inputs=[ct.TensorType(shape=(1, 3, 224, 224))]
)

coreml_model.save("MyModel.mlmodel")

# Add metadata
coreml_model.author = 'WIA Team'
coreml_model.license = 'Apache 2.0'
coreml_model.short_description = 'Image classification model'

2.8 Model Format Comparison

Format Framework File Ext Primary Use Size
PyTorch State Dict PyTorch .pth, .pt Training/checkpoints Medium
TorchScript PyTorch .pt Production/C++ Medium
SavedModel TensorFlow Directory Production/serving Large
HDF5 Keras .h5 Legacy Keras Small
ONNX Universal .onnx Interoperability Medium
TFLite TensorFlow .tflite Mobile/edge Very Small
CoreML Apple .mlmodel iOS/macOS Small

2.9 Versioning and Compatibility

Model formats evolve over time. Ensuring compatibility requires careful version management:

Semantic Versioning for Models

# Model version format: MAJOR.MINOR.PATCH
# Example: 2.1.3

# MAJOR: Incompatible API changes (input/output shape changes)
# MINOR: Backward-compatible functionality (new features, improved accuracy)
# PATCH: Backward-compatible bug fixes (numerical fixes, no architecture change)

metadata = {
    'model_name': 'sentiment-classifier',
    'version': '2.1.3',
    'framework': 'pytorch',
    'framework_version': '2.0.1',
    'onnx_opset': 14,
    'created_at': '2025-01-15T10:30:00Z'
}

2.10 Best Practices for Serialization

1. Always Save Metadata

# Bad: Only weights
torch.save(model.state_dict(), 'model.pth')

# Good: Include context
torch.save({
    'model_state_dict': model.state_dict(),
    'model_name': 'resnet50',
    'version': '1.0.0',
    'input_shape': [1, 3, 224, 224],
    'num_classes': 1000,
    'accuracy': 0.923,
    'framework_version': torch.__version__,
    'created_at': datetime.now().isoformat()
}, 'model_checkpoint.pth')

2. Use Framework-Agnostic Formats for Distribution

Prefer ONNX for sharing models that may be used in different frameworks or platforms.

3. Validate After Serialization

import numpy as np

# Generate test input
test_input = torch.randn(5, 3, 224, 224)

# Original model output
original_output = model(test_input)

# Save and load
torch.save(model.state_dict(), 'model.pth')
loaded_model = ResNet50()
loaded_model.load_state_dict(torch.load('model.pth'))
loaded_model.eval()

# Loaded model output
loaded_output = loaded_model(test_input)

# Validate numerical equivalence
assert torch.allclose(original_output, loaded_output, rtol=1e-5)
print("✓ Serialization validation passed")

4. Include Preprocessing Information

preprocessing_info = {
    'mean': [0.485, 0.456, 0.406],
    'std': [0.229, 0.224, 0.225],
    'resize': 256,
    'crop': 224,
    'normalization': 'imagenet'
}

Summary

Review Questions

  1. What are the five key components that should be serialized in a complete model checkpoint?
  2. Compare PyTorch's state_dict approach versus saving the entire model. When should each be used?
  3. What is TorchScript and what advantages does it provide over standard PyTorch serialization?
  4. Explain the difference between TensorFlow's SavedModel and HDF5 formats.
  5. Why doesn't JAX have a built-in serialization format? What approaches does the community use?
  6. Describe the structure of an ONNX file. What information does it contain?
  7. When would you choose TFLite over ONNX for model serialization?
  8. How should semantic versioning be applied to machine learning models?
  9. What metadata should always be included when saving a model checkpoint?
  10. Write code to validate that a model produces identical outputs before and after serialization.

Korea Standardization Infrastructure Mapping

Korea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ — totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology — 70+ Korean standardization-related laws.

Korea Digital Transformation Detailed Mapping

Korea operates digital transformation through a comprehensive governance system. Digital Government: Digital Platform Government Committee (established September 2022, under the President)·Ministry of the Interior and Safety Digital Government Bureau·e-Government Support Center·Gov.kr·National Citizen Service·KDIS (Korea Digital Information Society)·NIA (National Information Society Agency)·MOIS (Ministry of the Interior and Safety). K-DNS Infrastructure: Korea Internet & Security Agency (KISA) Korea Internet Center·KISA DNS Root Server·KRNIC (Korea Network Information Center)·BGP Korea·National Cyber Security Center (NCSC)·KCC (Korea Communications Commission)·MSIT (Ministry of Science and ICT)·NIA·NIPA. Korean Cloud Infrastructure: KT Cloud·NAVER Cloud (NCloud)·Samsung SDS Cloud·LG U+ Cloud·NHN Cloud·Kakao Enterprise Cloud·SK Telecom Cloud·KISA Cloud Security Assurance Program (CSAP)·KCMVP-validated cloud·ISMS-P (Information Security & Personal Information Management System). Korean Security Certifications: KISA ISMS-P certification·KCMVP (Korean Cryptographic Module Validation Program)·NIS (National Intelligence Service) "National Cryptographic Technology Operation Standards"·NCSC "National Cyber Security Strategy 2024-2028"·CC (Common Criteria) Korean evaluation bodies·EAL4·EAL5·KS X ISO/IEC 15408·19790·24759 Korean Profile. Korean Data Standards: NIA AI Hub·National Data Standardization Committee·Statistics Korea (KOSTAT)·MyData 4 Designated Combination Specialists (Samsung SDS, KICI, KOSTAT, KFTC)·National Institute of Korean Language·National Law Information Center·National Spatial Information Platform·National Spatial Data Center·Korean Spatial Information Standards. Finance and Fintech Standards: FSC (Financial Services Commission)·FSS (Financial Supervisory Service)·FIU (Financial Intelligence Unit)·BOK (Bank of Korea)·FSEC (Financial Security Institute)·KFTC (Korea Financial Telecommunications)·KSD (Korea Securities Depository)·KRX (Korea Exchange) 8-agency cooperation. 5G/6G Communications Infrastructure: 5G subscribers 35 million (2024)·5G base stations 350,000·6G commercialization target 2028·5G dedicated networks 16 operators·6G Acceleration Council (MSIT, 2024). K-Content: KOCCA (Korea Creative Content Agency)·MCST (Ministry of Culture, Sports and Tourism)·KCA (Korea Communications Agency)·Korea Culture Information Service Agency·Korean Film Archive·Korea Publishing Industry Promotion Agency. Data 3 Acts (Personal Information Protection Act·Credit Information Act·Telecommunications Network Act, 2020 enforcement)·Data Industry Act (2021)·Public Data Act (2013)·AI Framework Act (2026)·Digital Platform Government Framework Act (2024 proposed) — Korea digital transformation core legislation.