CHAPTER 3

Model Optimization for Edge

The Optimization Challenge

State-of-the-art neural networks often contain hundreds of millions or billions of parameters, requiring gigabytes of memory and massive computational resources. Edge devices, conversely, have strict constraints: limited RAM (1-8GB), modest computational power (10-100 TOPS), and tight power budgets (0.1-5W). Deploying cloud-scale models directly to edge devices is impossible.

Model optimization bridges this gap, transforming large, accurate models into compact, efficient versions suitable for edge deployment while preserving as much accuracy as possible. The goal: achieve 10-100x size reduction and 3-10x speed improvement with minimal accuracy loss (<1-3%).

Quantization

Understanding Numerical Precision

Neural networks traditionally use 32-bit floating-point (FP32) numbers for weights and activations. Each parameter requires 4 bytes of storage. Quantization reduces numerical precision to smaller data types:

Data Type Bits Range Size Reduction
FP32 32 ±3.4×10³⁸ Baseline (1x)
FP16 16 ±6.5×10⁴ 2x smaller
INT8 8 -128 to 127 4x smaller
INT4 4 -8 to 7 8x smaller

Post-Training Quantization (PTQ)

PTQ converts a trained FP32 model to lower precision without retraining. The process:

  1. Calibrate: Run representative data through the model to collect activation statistics
  2. Determine ranges: Calculate min/max values for each layer
  3. Map: Convert FP32 values to INT8 range
  4. Validate: Measure accuracy degradation
// TensorFlow Lite post-training INT8 quantization
import tensorflow as tf

converter = tf.lite.TFLiteConverter.from_saved_model('model/')
converter.optimizations = [tf.lite.Optimize.DEFAULT]

def representative_dataset():
    for data in calibration_samples:
        yield [data.astype(np.float32)]

converter.representative_dataset = representative_dataset
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8
converter.inference_output_type = tf.int8

quantized_model = converter.convert()
with open('model_int8.tflite', 'wb') as f:
    f.write(quantized_model)

Results: PTQ typically achieves 4x size reduction (FP32 → INT8) with 1-2% accuracy loss. No retraining required, fast conversion (minutes).

Quantization-Aware Training (QAT)

QAT simulates quantization during training, allowing the model to adapt to reduced precision. This minimizes accuracy loss compared to PTQ.

// PyTorch quantization-aware training
import torch.quantization as quant

model = YourModel()
model.qconfig = quant.get_default_qat_qconfig('fbgemm')
model_prepared = quant.prepare_qat(model)

# Train as normal with simulated quantization
for epoch in range(num_epochs):
    train(model_prepared, train_loader)

# Convert to quantized model
model_quantized = quant.convert(model_prepared)

Results: QAT achieves 4x size reduction with <0.5% accuracy loss. Requires retraining (hours to days), better accuracy preservation than PTQ.

Mixed-Precision Quantization

Not all layers tolerate quantization equally. Sensitive layers (first, last, attention) may use FP16, while middle layers use INT8. This balances size reduction and accuracy.

Pruning

Unstructured Pruning

Remove individual weights with small magnitudes. Weights near zero contribute minimally to model output and can be set to exactly zero.

// Simple magnitude-based pruning
import torch.nn.utils.prune as prune

# Prune 50% of weights in Conv layer
prune.l1_unstructured(model.conv1, name='weight', amount=0.5)

# Make pruning permanent
prune.remove(model.conv1, 'weight')

Pruning 50-90% of weights is common for large networks. The pruned model requires sparse matrix formats to actually reduce size (CSR, CSC).

Challenge: Sparse matrices aren't well-supported on many edge accelerators. Unstructured pruning may not improve inference speed without specialized hardware.

Structured Pruning

Remove entire channels, filters, or neurons rather than individual weights. This creates models that run efficiently on standard hardware.

// Channel pruning example
# Remove 30% of channels based on L1 norm
for layer in model.conv_layers:
    channel_importance = compute_channel_norms(layer)
    keep_channels = select_top_k(channel_importance, k=0.7)
    layer.weight = layer.weight[keep_channels, :, :, :]
    layer.bias = layer.bias[keep_channels]

Results: 30-50% parameter reduction with 2-5% accuracy loss. Actual speedup on edge hardware since model structure remains dense.

Iterative Pruning and Fine-Tuning

Best practice: prune gradually with fine-tuning between iterations.

  1. Prune 10-20% of parameters
  2. Fine-tune for 5-10 epochs to recover accuracy
  3. Repeat until target compression reached

Knowledge Distillation

Teacher-Student Framework

Train a small "student" model to mimic a large "teacher" model. The student learns from both ground truth labels and the teacher's soft predictions.

// Knowledge distillation loss
def distillation_loss(student_logits, teacher_logits, labels, temp=3.0, alpha=0.7):
    # Soft targets from teacher (smoothed probabilities)
    soft_targets = F.softmax(teacher_logits / temp, dim=1)
    soft_student = F.log_softmax(student_logits / temp, dim=1)
    distillation = F.kl_div(soft_student, soft_targets, reduction='batchmean')

    # Hard targets from ground truth
    hard_loss = F.cross_entropy(student_logits, labels)

    # Combined loss
    return alpha * (temp ** 2) * distillation + (1 - alpha) * hard_loss

# Training loop
for images, labels in dataloader:
    with torch.no_grad():
        teacher_logits = teacher_model(images)

    student_logits = student_model(images)
    loss = distillation_loss(student_logits, teacher_logits, labels)
    loss.backward()
    optimizer.step()

The teacher's soft predictions provide richer information than hard labels. For an image classified as "dog" with 95% confidence, the teacher also reveals it's 3% "wolf", 1% "cat"—structural knowledge the student can learn.

Choosing Student Architecture

Common approaches:

Results: 5-20x model size reduction while retaining 95-99% of teacher accuracy. Student often outperforms directly training the small architecture.

Neural Architecture Search (NAS)

Hardware-Aware NAS

Automatically discover neural architectures optimized for target edge hardware. The search objective balances:

Popular NAS methods:

AutoML for Edge

Tools like TensorFlow Model Optimization Toolkit and Neural Network Intelligence (NNI) automate the optimization process, applying quantization, pruning, and NAS systematically.

Operator Fusion and Graph Optimization

Layer Fusion

Combine sequential operations into single kernels to reduce memory traffic and overhead.

Common fusions:

// Before fusion (3 operations, 3 memory passes)
x = conv2d(input, weights)
x = batch_norm(x, bn_params)
output = relu(x)

// After fusion (1 operation, 1 memory pass)
output = fused_conv_bn_relu(input, weights, bn_params)

Fusion reduces latency by 20-40% by minimizing memory reads/writes.

Constant Folding

Pre-compute operations with constant inputs at compile time.

// Before: computed at runtime
scale = 0.5
output = input * scale * 2.0

// After constant folding: 0.5 * 2.0 = 1.0 pre-computed
output = input  // Multiplication eliminated entirely!

Dead Code Elimination

Remove unused outputs, unreachable operations, and redundant computations from the graph.

Low-Rank Factorization

Tensor Decomposition

Approximate weight matrices using low-rank decompositions. For a weight matrix W ∈ R^(m×n), decompose into W ≈ U × V where U ∈ R^(m×k), V ∈ R^(k×n), and k ≪ min(m,n).

// Singular Value Decomposition (SVD) for compression
U, S, V = torch.svd(weight_matrix)

# Keep only top k singular values
k = 64
U_reduced = U[:, :k]
S_reduced = S[:k]
V_reduced = V[:, :k]

# Approximate original weight
weight_approx = U_reduced @ torch.diag(S_reduced) @ V_reduced.t()

# Replace one large layer with two smaller layers
layer1.weight = U_reduced @ torch.diag(torch.sqrt(S_reduced))
layer2.weight = torch.diag(torch.sqrt(S_reduced)) @ V_reduced.t()

Results: 2-5x compression for fully connected layers with minimal accuracy loss.

Compression Pipelines

Combining Techniques

Maximum compression comes from combining multiple techniques:

  1. Pruning: Remove 50% of parameters (2x reduction)
  2. Quantization: FP32 → INT8 (4x reduction)
  3. Knowledge Distillation: Train efficient student (3x reduction)
  4. Total: 2 × 4 × 3 = 24x overall compression
// Complete optimization pipeline
// 1. Start with pre-trained model
model = load_pretrained_model()

// 2. Prune 60% of weights
model = iterative_prune(model, target_sparsity=0.6, epochs=10)

// 3. Knowledge distillation to efficient architecture
student = MobileNetV3()
student = distill(teacher=model, student=student, epochs=50)

// 4. Quantization-aware training
student = quantization_aware_train(student, epochs=20)

// 5. Convert to INT8
model_int8 = convert_to_int8(student)

// 6. Export for edge deployment
export_to_tflite(model_int8, 'optimized_model.tflite')

Accuracy-Efficiency Trade-offs

Pareto Frontier

Plot model variants on accuracy vs. latency/size. The Pareto frontier shows non-dominated models—those where you can't improve one metric without harming the other.

Model Variant Accuracy Latency Size
Original FP32 92.5% 120ms 98 MB
+ Pruning 50% 91.8% 100ms 50 MB
+ INT8 Quant 91.2% 35ms 12 MB
+ Distillation 89.5% 18ms 4 MB

Task-Specific Requirements

Choose optimization level based on application needs:

弘益人間 Optimization Principle:

Optimize models to run on the widest range of devices, making AI accessible to everyone regardless of their hardware. Every 10x size reduction brings AI to 10x more devices worldwide.

Tools and Frameworks

TensorFlow Model Optimization Toolkit

Comprehensive toolkit for quantization, pruning, and clustering. Supports post-training and training-time optimization.

PyTorch Quantization

Built-in support for PTQ and QAT. Integration with TorchScript for deployment.

ONNX Runtime

Graph optimization and quantization for ONNX models. Cross-framework compatibility.

Neural Network Compression Framework (NNCF)

Intel's toolkit for compression with minimal accuracy loss. Supports PyTorch and TensorFlow.

Measuring Optimization Impact

Before-After Comparison

// Benchmark original vs optimized model
Original Model:
- Size: 245 MB
- Latency: 178ms (CPU), 45ms (GPU)
- Accuracy: 94.2%
- Power: 2.8W

Optimized Model (INT8 + Pruning + Distillation):
- Size: 12 MB (20.4x smaller)
- Latency: 18ms (CPU), 8ms (NPU)
- Accuracy: 92.1% (-2.1%)
- Power: 0.4W (7x more efficient)

Result: 20x compression, 10x faster, 7x more power-efficient
Trade-off: 2.1% accuracy reduction (acceptable for most use cases)

Summary

Model optimization is essential for edge AI deployment. Key techniques include:

  • Quantization: Reduce numerical precision (FP32 → INT8) for 4x size reduction with minimal accuracy loss
  • Pruning: Remove unnecessary weights/channels for 2-10x parameter reduction
  • Knowledge Distillation: Train small models to mimic large ones, achieving 5-20x compression
  • NAS: Automatically discover hardware-optimized architectures
  • Graph Optimization: Fuse operations, eliminate dead code, fold constants

Combining techniques yields 10-100x total compression. The optimization pipeline: prune → distill → quantize → optimize graph. Trade-offs between accuracy, latency, size, and power are application-specific.

Modern frameworks (TensorFlow Lite, PyTorch, ONNX Runtime) provide robust tooling for automated optimization. Measure results on target hardware to validate real-world performance gains.

Review Questions

  1. What is the difference between post-training quantization (PTQ) and quantization-aware training (QAT)?
  2. How much size reduction does INT8 quantization achieve compared to FP32?
  3. Explain the difference between structured and unstructured pruning. Which is better for edge deployment?
  4. How does knowledge distillation work, and why does the student often outperform directly training a small model?
  5. What is Neural Architecture Search (NAS), and how does hardware-aware NAS differ from traditional NAS?
  6. Name three common operator fusions and explain how they improve performance.
  7. If you apply 50% pruning and INT8 quantization, what is the theoretical total compression ratio?
  8. What is the Pareto frontier in the context of model optimization?
  9. Describe a complete optimization pipeline combining multiple techniques.
  10. How do you choose the appropriate optimization level for a specific application?

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.