CHAPTER 8

Production Deployment

Deploying Vision AI systems at scale

From Research to Production

Deploying Vision AI in production requires more than just a trained model. You need to consider performance, scalability, monitoring, reliability, and cost optimization.

Key Considerations

Model Optimization

Quantization

Reduce model size and inference time by using lower precision (INT8 instead of FP32).

import torch

# Post-training quantization
model_fp32 = YourModel()
model_fp32.load_state_dict(torch.load('model.pth'))
model_fp32.eval()

# Dynamic quantization
model_int8 = torch.quantization.quantize_dynamic(
    model_fp32,
    {torch.nn.Linear},
    dtype=torch.qint8
)

# Static quantization (requires calibration data)
model_fp32.qconfig = torch.quantization.get_default_qconfig('fbgemm')
model_prepared = torch.quantization.prepare(model_fp32)

# Calibrate with representative data
for data in calibration_data:
    model_prepared(data)

model_int8 = torch.quantization.convert(model_prepared)

# Compare model sizes
torch.save(model_fp32.state_dict(), 'model_fp32.pth')
torch.save(model_int8.state_dict(), 'model_int8.pth')
# INT8 model is typically 4x smaller

Pruning

Remove unnecessary weights to reduce model size.

import torch.nn.utils.prune as prune

# Prune 30% of weights in conv layer
module = model.conv1
prune.l1_unstructured(module, name='weight', amount=0.3)

# Remove pruning re-parametrization
prune.remove(module, 'weight')

# Global pruning across entire model
parameters_to_prune = []
for name, module in model.named_modules():
    if isinstance(module, torch.nn.Conv2d):
        parameters_to_prune.append((module, 'weight'))

prune.global_unstructured(
    parameters_to_prune,
    pruning_method=prune.L1Unstructured,
    amount=0.2,
)

Knowledge Distillation

Train a smaller student model to mimic a larger teacher model.

def distillation_loss(student_logits, teacher_logits, labels, T=3.0, alpha=0.7):
    """
    T: Temperature for softening distributions
    alpha: Weight between distillation and task loss
    """
    # Soft targets from teacher
    soft_targets = F.softmax(teacher_logits / T, dim=1)
    soft_student = F.log_softmax(student_logits / T, dim=1)
    distillation_loss = F.kl_div(soft_student, soft_targets, reduction='batchmean') * (T * T)

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

    # Combined loss
    return alpha * distillation_loss + (1 - alpha) * student_loss

# Training loop
teacher.eval()
student.train()

for images, labels in dataloader:
    with torch.no_grad():
        teacher_logits = teacher(images)

    student_logits = student(images)
    loss = distillation_loss(student_logits, teacher_logits, labels)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

Model Serving

ONNX Export

Export to ONNX for cross-framework compatibility.

import torch.onnx

# Export PyTorch model to ONNX
model = YourModel()
model.load_state_dict(torch.load('model.pth'))
model.eval()

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

torch.onnx.export(
    model,
    dummy_input,
    "model.onnx",
    export_params=True,
    opset_version=14,
    do_constant_folding=True,
    input_names=['input'],
    output_names=['output'],
    dynamic_axes={'input': {0: 'batch_size'},
                  'output': {0: 'batch_size'}}
)

# Verify ONNX model
import onnx
onnx_model = onnx.load("model.onnx")
onnx.checker.check_model(onnx_model)

# Run inference with ONNX Runtime
import onnxruntime as ort

ort_session = ort.InferenceSession("model.onnx")
outputs = ort_session.run(
    None,
    {"input": dummy_input.numpy()}
)

TensorRT Optimization

Optimize for NVIDIA GPUs with TensorRT.

# Convert ONNX to TensorRT
import tensorrt as trt

logger = trt.Logger(trt.Logger.WARNING)
builder = trt.Builder(logger)
network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
parser = trt.OnnxParser(network, logger)

with open('model.onnx', 'rb') as f:
    parser.parse(f.read())

config = builder.create_builder_config()
config.max_workspace_size = 1 << 30  # 1GB

# Enable FP16 for faster inference
if builder.platform_has_fast_fp16:
    config.set_flag(trt.BuilderFlag.FP16)

engine = builder.build_engine(network, config)

# Save engine
with open("model.trt", "wb") as f:
    f.write(engine.serialize())

TorchServe

Production-ready model serving for PyTorch models.

# Create model archive
torch-model-archiver \
    --model-name vision_model \
    --version 1.0 \
    --model-file model.py \
    --serialized-file model.pth \
    --handler image_classifier \
    --extra-files index_to_name.json

# Start TorchServe
torchserve --start --model-store model_store \
    --models vision_model=vision_model.mar

# Inference API
curl -X POST http://localhost:8080/predictions/vision_model \
    -T image.jpg

FastAPI Deployment

from fastapi import FastAPI, File, UploadFile
import torch
from PIL import Image
import io

app = FastAPI()

# Load model once at startup
model = YourModel()
model.load_state_dict(torch.load('model.pth'))
model.eval()

@app.post("/predict")
async def predict(file: UploadFile = File(...)):
    # Read image
    contents = await file.read()
    image = Image.open(io.BytesIO(contents))

    # Preprocess
    input_tensor = preprocess(image).unsqueeze(0)

    # Inference
    with torch.no_grad():
        output = model(input_tensor)
        predictions = torch.nn.functional.softmax(output[0], dim=0)

    # Return top-5 predictions
    top5_prob, top5_catid = torch.topk(predictions, 5)
    results = [
        {"class": int(top5_catid[i]), "probability": float(top5_prob[i])}
        for i in range(5)
    ]

    return {"predictions": results}

# Run with: uvicorn main:app --reload

Containerization with Docker

# Dockerfile
FROM pytorch/pytorch:2.0.0-cuda11.7-cudnn8-runtime

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

EXPOSE 8000

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
# Build and run
docker build -t vision-ai-service .
docker run -p 8000:8000 --gpus all vision-ai-service

Cloud Deployment

AWS SageMaker

import sagemaker
from sagemaker.pytorch import PyTorchModel

# Deploy model
pytorch_model = PyTorchModel(
    model_data='s3://bucket/model.tar.gz',
    role=role,
    entry_point='inference.py',
    framework_version='2.0.0',
    py_version='py39'
)

predictor = pytorch_model.deploy(
    initial_instance_count=1,
    instance_type='ml.g4dn.xlarge'
)

# Inference
result = predictor.predict(image_bytes)

Google Cloud AI Platform

# Deploy to Vertex AI
gcloud ai models upload \
    --region=us-central1 \
    --display-name=vision-model \
    --container-image-uri=gcr.io/project/vision-ai:latest

gcloud ai endpoints create \
    --region=us-central1 \
    --display-name=vision-endpoint

gcloud ai endpoints deploy-model ENDPOINT_ID \
    --region=us-central1 \
    --model=MODEL_ID \
    --machine-type=n1-standard-4 \
    --accelerator=type=nvidia-tesla-t4,count=1

Azure Machine Learning

from azureml.core import Workspace, Model
from azureml.core.webservice import AciWebservice, Webservice

ws = Workspace.from_config()

# Register model
model = Model.register(
    workspace=ws,
    model_path='model.pth',
    model_name='vision-model'
)

# Deploy
deployment_config = AciWebservice.deploy_configuration(
    cpu_cores=2,
    memory_gb=4,
    gpu_cores=1
)

service = Model.deploy(
    workspace=ws,
    name='vision-service',
    models=[model],
    inference_config=inference_config,
    deployment_config=deployment_config
)

Monitoring and Logging

Prometheus Metrics

from prometheus_client import Counter, Histogram, start_http_server
import time

# Define metrics
REQUEST_COUNT = Counter('requests_total', 'Total requests')
REQUEST_LATENCY = Histogram('request_latency_seconds', 'Request latency')
PREDICTION_COUNT = Counter('predictions_total', 'Total predictions', ['class'])

@app.post("/predict")
@REQUEST_LATENCY.time()
async def predict(file: UploadFile = File(...)):
    REQUEST_COUNT.inc()

    # ... inference code ...

    # Track prediction
    predicted_class = results[0]['class']
    PREDICTION_COUNT.labels(class=predicted_class).inc()

    return {"predictions": results}

# Start Prometheus metrics server
start_http_server(8001)

MLflow Tracking

import mlflow

# Log training run
with mlflow.start_run():
    mlflow.log_param("learning_rate", 0.001)
    mlflow.log_param("batch_size", 32)

    # Training loop
    for epoch in range(num_epochs):
        loss = train_epoch()
        accuracy = validate()

        mlflow.log_metric("loss", loss, step=epoch)
        mlflow.log_metric("accuracy", accuracy, step=epoch)

    # Log model
    mlflow.pytorch.log_model(model, "model")

# Load model for inference
model = mlflow.pytorch.load_model("runs:/RUN_ID/model")

Performance Optimization

Batch Processing

class BatchPredictor:
    def __init__(self, model, batch_size=32, max_wait=0.1):
        self.model = model
        self.batch_size = batch_size
        self.max_wait = max_wait
        self.queue = []
        self.results = {}

    async def predict(self, image_id, image):
        # Add to queue
        self.queue.append((image_id, image))

        # Process when batch is full or timeout
        if len(self.queue) >= self.batch_size:
            await self.process_batch()

        # Wait for result
        while image_id not in self.results:
            await asyncio.sleep(0.01)

        return self.results.pop(image_id)

    async def process_batch(self):
        if not self.queue:
            return

        # Create batch
        batch_ids, batch_images = zip(*self.queue[:self.batch_size])
        self.queue = self.queue[self.batch_size:]

        batch_tensor = torch.stack([preprocess(img) for img in batch_images])

        # Inference
        with torch.no_grad():
            outputs = self.model(batch_tensor)

        # Store results
        for i, image_id in enumerate(batch_ids):
            self.results[image_id] = outputs[i]

Model Caching

from functools import lru_cache
import hashlib

@lru_cache(maxsize=1000)
def predict_cached(image_hash):
    # This will be called only once per unique image
    return model(preprocess(image))

def predict_with_cache(image):
    # Compute image hash
    image_bytes = image.tobytes()
    image_hash = hashlib.md5(image_bytes).hexdigest()

    return predict_cached(image_hash)

A/B Testing

import random

def get_model_version(user_id):
    # Route 10% of traffic to new model
    if hash(user_id) % 100 < 10:
        return "model_v2"
    return "model_v1"

@app.post("/predict")
async def predict(file: UploadFile, user_id: str):
    model_version = get_model_version(user_id)
    model = models[model_version]

    # Log which model was used
    mlflow.log_param("model_version", model_version)

    # ... inference code ...

Security Best Practices

Input Validation

from PIL import Image
import magic

def validate_image(file_bytes):
    # Check file type
    file_type = magic.from_buffer(file_bytes, mime=True)
    if file_type not in ['image/jpeg', 'image/png', 'image/webp']:
        raise ValueError("Invalid image type")

    # Check image can be opened
    try:
        img = Image.open(io.BytesIO(file_bytes))
        img.verify()
    except:
        raise ValueError("Corrupted image")

    # Check image size
    if len(file_bytes) > 10 * 1024 * 1024:  # 10MB
        raise ValueError("Image too large")

    return img

Rate Limiting

from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address

limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

@app.post("/predict")
@limiter.limit("10/minute")
async def predict(request: Request, file: UploadFile):
    # ... inference code ...

Cost Optimization

Strategies

弘益人間 in Production

As you deploy Vision AI systems, remember the WIA-AI-021 principle of benefiting all humanity. Ensure your systems are:

  • Privacy-respecting - Minimize data collection and protect user information
  • Fair and unbiased - Monitor for and mitigate algorithmic bias
  • Transparent - Provide clear explanations of system decisions
  • Reliable - Build robust systems that fail gracefully
  • Sustainable - Optimize for energy efficiency and environmental impact

Summary

  • Production deployment requires optimizing for latency, throughput, cost, and reliability
  • Model optimization techniques include quantization, pruning, and knowledge distillation
  • ONNX and TensorRT enable cross-platform deployment and GPU acceleration
  • Containerization with Docker simplifies deployment and scaling
  • Cloud platforms (AWS, GCP, Azure) provide managed services for ML deployment
  • Monitoring with Prometheus and MLflow ensures system health and performance
  • Security best practices include input validation, rate limiting, and data encryption
  • Cost optimization through auto-scaling, model compression, and serverless architectures

Review Questions

  1. What are the key differences between INT8 quantization and FP16 precision?
  2. How does knowledge distillation reduce model size while maintaining accuracy?
  3. Why is ONNX useful for production deployment?
  4. What are the trade-offs between cloud deployment and edge deployment?
  5. How does batch processing improve inference throughput?
  6. What security considerations are important for Vision AI APIs?
  7. How can A/B testing help improve ML systems in production?
  8. What metrics should you monitor for a production Vision AI system?

Congratulations!

You've completed the WIA-AI-021 Vision AI Complete Guide. You now have the knowledge to build, train, and deploy sophisticated computer vision systems that benefit humanity.

弘益人間 · Benefit All Humanity

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.

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.