Chapter 5: Cross-Framework Conversion

Bridging PyTorch, TensorFlow, and Beyond

弘益人間 · Benefit All Humanity

5.1 The Need for Cross-Framework Conversion

Modern AI development involves multiple frameworks - researchers might use PyTorch for experimentation, while production systems run TensorFlow Serving. Cross-framework conversion enables seamless model transfer, allowing teams to leverage the best tools for each stage of the ML lifecycle.

Common Conversion Scenarios

5.2 Conversion Pathways

ONNX serves as the central hub for most conversions:

Conversion Graph:

PyTorch ←→ ONNX ←→ TensorFlow
   ↓          ↓         ↓
TorchScript  ↓      SavedModel
   ↓          ↓         ↓
Mobile     TFLite   TF.js
   ↓          ↓         ↓
   └──────→ CoreML ←──┘

ONNX → TensorRT (NVIDIA)
ONNX → OpenVINO (Intel)
ONNX → ONNX.js (Web)

5.3 PyTorch to ONNX to TensorFlow

Step 1: PyTorch to ONNX

import torch
import torch.onnx

# PyTorch model
class ResNetBlock(torch.nn.Module):
    def __init__(self, channels):
        super().__init__()
        self.conv1 = torch.nn.Conv2d(channels, channels, 3, padding=1)
        self.bn1 = torch.nn.BatchNorm2d(channels)
        self.conv2 = torch.nn.Conv2d(channels, channels, 3, padding=1)
        self.bn2 = torch.nn.BatchNorm2d(channels)

    def forward(self, x):
        residual = x
        out = torch.nn.functional.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        return torch.nn.functional.relu(out + residual)

model = ResNetBlock(64)
dummy_input = torch.randn(1, 64, 56, 56)

# Export to ONNX
torch.onnx.export(
    model,
    dummy_input,
    "resnet_block.onnx",
    export_params=True,
    opset_version=17,
    do_constant_folding=True,
    input_names=['input'],
    output_names=['output'],
    dynamic_axes={'input': {0: 'batch'}, 'output': {0: 'batch'}}
)

Step 2: ONNX to TensorFlow

import onnx
from onnx_tf.backend import prepare

# Load ONNX model
onnx_model = onnx.load("resnet_block.onnx")

# Convert to TensorFlow
tf_rep = prepare(onnx_model)

# Export as SavedModel
tf_rep.export_graph("resnet_block_tf")

# Or use in Python directly
import numpy as np
output = tf_rep.run(np.random.randn(1, 64, 56, 56).astype(np.float32))
print(output)

5.4 TensorFlow to ONNX to PyTorch

TensorFlow to ONNX

import tensorflow as tf
import tf2onnx

# Create TensorFlow model
model = tf.keras.Sequential([
    tf.keras.layers.Conv2D(64, 3, padding='same', input_shape=(224, 224, 3)),
    tf.keras.layers.BatchNormalization(),
    tf.keras.layers.ReLU(),
    tf.keras.layers.GlobalAveragePooling2D(),
    tf.keras.layers.Dense(1000)
])

# Convert to ONNX
spec = (tf.TensorSpec((None, 224, 224, 3), tf.float32, name="input"),)
model_proto, _ = tf2onnx.convert.from_keras(
    model,
    input_signature=spec,
    opset=17,
    output_path="tf_model.onnx"
)

ONNX to PyTorch

import onnx
import torch
from onnx2pytorch import ConvertModel

# Load ONNX model
onnx_model = onnx.load("tf_model.onnx")

# Convert to PyTorch
pytorch_model = ConvertModel(onnx_model)

# Use the model
test_input = torch.randn(1, 3, 224, 224)
output = pytorch_model(test_input)
print(f"Output shape: {output.shape}")

5.5 Handling Conversion Challenges

Operator Compatibility

Not all operations have direct equivalents across frameworks:

PyTorch ONNX TensorFlow Notes
F.interpolate Resize tf.image.resize Alignment differs
torch.einsum Einsum tf.einsum Opset 12+
torch.nn.GELU Gelu tf.nn.gelu Approximation varies

Addressing Incompatibilities

import torch

# Before conversion: Replace unsupported ops
class ModelWithCompatibleOps(torch.nn.Module):
    def forward(self, x):
        # Instead of: x = torch.special.erf(x)
        # Use supported ops:
        x = 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))  # GELU approx
        return x

# Or use custom ONNX operator
@torch.onnx.symbolic_helper.parse_args('v', 'f')
def custom_op(g, input, scale):
    return g.op("CustomNamespace::CustomOp", input, scale_f=scale)

5.6 Data Layout Differences

PyTorch uses NCHW (batch, channels, height, width) while TensorFlow prefers NHWC:

import torch
import numpy as np

# PyTorch: NCHW
pytorch_tensor = torch.randn(1, 3, 224, 224)

# Convert to TensorFlow: NHWC
tf_tensor = pytorch_tensor.permute(0, 2, 3, 1)  # [1, 224, 224, 3]

# After TensorFlow processing, convert back
pytorch_result = tf_output.permute(0, 3, 1, 2)  # [1, 3, H, W]

# Automatic conversion in ONNX
torch.onnx.export(
    model,
    dummy_input,
    "model.onnx",
    input_names=['input'],
    output_names=['output']
)
# ONNX handles layout transformation automatically

5.7 Validation Framework

Always validate converted models to ensure numerical accuracy:

import torch
import numpy as np
import onnxruntime as ort

class ModelValidator:
    def __init__(self, original_model, onnx_path):
        self.pt_model = original_model
        self.ort_session = ort.InferenceSession(onnx_path)

    def validate(self, test_inputs, tolerance=1e-5):
        results = []

        for i, test_input in enumerate(test_inputs):
            # PyTorch inference
            self.pt_model.eval()
            with torch.no_grad():
                pt_output = self.pt_model(test_input).numpy()

            # ONNX inference
            ort_input = {self.ort_session.get_inputs()[0].name: test_input.numpy()}
            ort_output = self.ort_session.run(None, ort_input)[0]

            # Compare
            diff = np.abs(pt_output - ort_output)
            max_diff = diff.max()
            mean_diff = diff.mean()

            passed = max_diff < tolerance

            results.append({
                'test_id': i,
                'passed': passed,
                'max_diff': max_diff,
                'mean_diff': mean_diff
            })

            print(f"Test {i}: {'✓ PASS' if passed else '✗ FAIL'}")
            print(f"  Max diff: {max_diff:.2e}, Mean diff: {mean_diff:.2e}")

        return results

# Usage
validator = ModelValidator(pytorch_model, "model.onnx")
test_data = [torch.randn(1, 3, 224, 224) for _ in range(10)]
results = validator.validate(test_data)

5.8 Converting to Mobile Formats

To TensorFlow Lite

import tensorflow as tf

# From SavedModel
converter = tf.lite.TFLiteConverter.from_saved_model('model_tf')
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()

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

# From ONNX (via TensorFlow)
# 1. ONNX → TensorFlow
# 2. TensorFlow → TFLite (as above)

To CoreML

import coremltools as ct

# From ONNX
from onnx_coreml import convert

# Convert
coreml_model = convert(
    model='model.onnx',
    minimum_ios_deployment_target='13',
    preprocessing_args={
        'image_scale': 1.0/255.0,
        'red_bias': -0.485/0.229,
        'green_bias': -0.456/0.224,
        'blue_bias': -0.406/0.225
    }
)

# Save
coreml_model.save('model.mlmodel')

# From PyTorch (via ONNX)
# 1. PyTorch → ONNX
# 2. ONNX → CoreML (as above)

5.9 Automated Conversion Pipelines

from pathlib import Path
import torch
import onnx
import tf2onnx
import tensorflow as tf

class ModelConverter:
    def __init__(self, output_dir="converted_models"):
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(exist_ok=True)

    def pytorch_to_all(self, model, dummy_input, name="model"):
        """Convert PyTorch model to multiple formats"""
        results = {}

        # PyTorch → ONNX
        onnx_path = self.output_dir / f"{name}.onnx"
        torch.onnx.export(model, dummy_input, onnx_path, opset_version=17)
        results['onnx'] = onnx_path

        # ONNX → TensorFlow
        try:
            from onnx_tf.backend import prepare
            onnx_model = onnx.load(str(onnx_path))
            tf_path = self.output_dir / f"{name}_tf"
            tf_rep = prepare(onnx_model)
            tf_rep.export_graph(str(tf_path))
            results['tensorflow'] = tf_path
        except Exception as e:
            print(f"TensorFlow conversion failed: {e}")

        # ONNX → TFLite
        try:
            converter = tf.lite.TFLiteConverter.from_saved_model(str(tf_path))
            tflite_model = converter.convert()
            tflite_path = self.output_dir / f"{name}.tflite"
            with open(tflite_path, 'wb') as f:
                f.write(tflite_model)
            results['tflite'] = tflite_path
        except Exception as e:
            print(f"TFLite conversion failed: {e}")

        return results

# Usage
converter = ModelConverter()
results = converter.pytorch_to_all(
    pytorch_model,
    torch.randn(1, 3, 224, 224),
    name="resnet50"
)
print(f"Converted formats: {list(results.keys())}")

5.10 Best Practices

Conversion Checklist

  1. Simplify model: Remove training-specific code (dropout in eval mode)
  2. Use standard operations: Avoid custom ops when possible
  3. Test extensively: Validate with diverse inputs
  4. Check operator support: Verify all ops are supported in target format
  5. Handle dynamic shapes: Specify dynamic axes in ONNX export
  6. Monitor numerical precision: Track fp32 vs fp16 differences
  7. Document conversions: Record conversion steps and parameters
  8. Version control: Keep original and converted models versioned

Chapter Summary

Review Questions

  1. Why is ONNX often used as an intermediate format for cross-framework conversion?
  2. Write code to convert a PyTorch model to ONNX and then to TensorFlow.
  3. What is the difference between NCHW and NHWC data layouts?
  4. How would you validate a converted model's numerical accuracy?
  5. Describe three common operator compatibility challenges and solutions.
  6. Write a pipeline to convert a PyTorch model to TFLite.
  7. When would you use CoreML instead of TFLite for mobile deployment?
  8. What preprocessing steps should you take before converting a model?
  9. How do you handle custom operations during conversion?
  10. Describe best practices for maintaining converted model versions.
弘益人間 (Hongik Ingan) · Benefit All Humanity

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.

Korea Industrial, Research, Education Infrastructure Mapping

Korea operates its industrial ecosystem and standardization system through the following core infrastructure. Korea Top 5 Groups: Samsung, Hyundai Motor, LG, SK, Lotte. Each group operates standardization committees and ISO/IEC TC Korean secretariats. Samsung Electronics (semiconductors, displays, home appliances, telecom)·Hyundai Motor (automobiles, mobility)·LG Electronics (home appliances, displays, OLED)·SK hynix (memory)·LG Energy Solution·Samsung SDI (batteries)·POSCO Future M (materials)·Hyundai Mobis (parts). Korean IT Big Tech: NAVER (search, cloud, AI HyperCLOVA)·Kakao (messenger, payment, mobility, banking)·Coupang (e-commerce, logistics)·Karrot Market·Toss·Woowa Brothers. Korea Telcos: SK Telecom·KT·LG U+. 5G·5G dedicated networks·B2B cloud·AI businesses operating. Korea Top 7 Research Universities: Seoul National University·KAIST·POSTECH·Yonsei University·Korea University·UNIST·DGIST·GIST. All serve as standardization R&D bases and ISO/IEC/IEEE Korean chairs. Korea Government-affiliated National Research Institutes (26): KIST, KAERI, KIMM, KIER, KFRI, KRICT, KRIBB, KARI, KASI, KIGAM, KICT, KISTI, KETI, ETRI, NIMS, KIMS, KISDI, KOTRA, STEPI, KOEN, KICCE, KIET, KIPF, KIHASA, KICJ, KLRI. Korea Industrial Complexes / Tech Valleys: Pangyo Techno Valley·Dongtan·Gwanggyo·Songdo IBD·Yeouido·Gangnam·Sihwa·Banwol·Gumi·Ulsan·Changwon·Geoje·Yeosu·Onsan·Cheongju·Iksan·Gwangyang·POSCO Gwangyang Steel Mill·Asan Bay·Seosan·Songdo·Incheon Airport·Sejong·Cheongna·Geomdan. Korea Trade and Finance Infrastructure: Korea International Trade Association (KITA)·Korea Trade-Investment Promotion Agency (KOTRA)·Export-Import Bank of Korea (KEXIM)·Bank of Korea·Kookmin Bank·Shinhan·Hana·Woori·NH Nonghyup·IBK Industrial Bank·SC First Bank·Citi Bank Korea·HSBC Korea·DBS Korea — 14 Korean major banks and foreign banks. Korea K-POP / K-Content: HYBE·SM·YG·JYP 4 major entertainment companies·CJ ENM·tvN·MBC·KBS·SBS·EBS·YTN·Yonhap News TV·JTBC Korean broadcasting·NETFLIX Korea·Disney Plus·TVING·Wavve·Watcha·Coupang Play. Korea Gaming Industry: Nexon·NCsoft·Krafton·Netmarble·Kakao Games·Pearl Abyss·Com2uS·Gamevil·NHN·Smilegate·Webzen. Korea Automotive / Battery: Hyundai Motor·Kia·Genesis·LG Energy Solution·Samsung SDI·SK On·POSCO Future M·EcoPro·L&F battery cathode material suppliers. Korea Semiconductor: Samsung Electronics (HBM3E·HBM4)·SK hynix (HBM3E 12-Hi)·DB HiTek·SK siltron·SK Enpulse·Dongjin Semichem·Seoul Semiconductor·Simmtech·Samsung Display·LG Display.

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.