🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Project 3: Deep Learning Model Deployment, End to End

Module 16: Deployment ProjectđŸŸĸ Free Lesson
Module 16: Deployment Project

Six phases, one running endpoint, and numbers you can defend

At the end of this project you will have a versioned container image, a live prediction API, and a latency report that shows p95 under one hundred milliseconds on a modest instance.

16 min readđŸ”ŦAdvanced

Prerequisites

  • !PyTorch tensors, autograd, and training loops
  • !CNN building blocks: convolution, pooling, and batch normalization
  • !FastAPI and Docker fundamentals from the model deployment lesson

What You'll Learn

  • 1Fine-tune a pretrained CNN with a frozen backbone and a validation loop
  • 2Export trained weights to TorchScript and ONNX with dynamic batch axes
  • 3Serve images through a typed API that owns its own preprocessing
  • 4Build a multi-stage Docker image that ships weights without the training stack
  • 5Define measurable exit criteria for a deployment and check them automatically

Project brief: what you are building and why

The deliverable is a ten-class image classifier that runs behind an HTTP API, packaged so that anyone with container tooling can reproduce the deployment. The dataset is deliberately ordinary: ten thousand three-channel images at two hundred twenty-four pixels square, split seventy-thirty into train and validation. Familiar data keeps the focus on the parts that are genuinely new, which are export, containerization, and verification.

A useful discipline for the whole project is to name the exit criteria before writing code. Accuracy alone is not a deployment criterion, because a model can be accurate and still be unusable: a five-second response time, a two-gigabyte image, or a service that cannot tell a liveness probe from a dead process each invalidates the work. The targets below are modest on purpose, so you can hit them on a laptop and then exceed them in the cloud.

CriterionTargetHow it is measuredWhy it matters
Validation accuracyAt least 85 percentHeld-out split, single passModel is worth serving
p95 latencyUnder 100 milliseconds500 timed requests, batch of oneUsers perceive delay above 200 ms
Sustained throughput20 requests per secondLoad test, one containerCapacity planning baseline
Image sizeUnder 1.2 GBDocker image inspectionFaster pulls, cheaper deploys
Cold startUnder 15 secondsFresh container to first 200Autoscaling viability
Health reliabilityZero false positives over 100 probesOrchestrator probe logAvoids flapping restarts

Keep the evaluation harness separate from the model code. A script that loads the exported artifact and reports accuracy, p50, p95, and p99 latency is the same script you will rerun after every change, and it is what turns vague confidence into evidence.

Phase 1: fine-tuning the classifier

Start from a pretrained ResNet-18 backbone. Freezing everything except the classification head trains in minutes on a single GPU and usually beats a from-scratch network on a small dataset, because the early convolutional layers already encode generic edge and texture detectors that you would otherwise need tens of thousands of images to learn.

python
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, random_split
from torchvision import datasets, models, transforms

NUM_CLASSES = 10
BATCH_SIZE = 64

train_transform = transforms.Compose([
    transforms.RandomResizedCrop(224),
    transforms.RandomHorizontalFlip(),
    transforms.ColorJitter(brightness=0.2, contrast=0.2),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225]),
])

eval_transform = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225]),
])

class ImageClassifier(nn.Module):
    def __init__(self, num_classes: int = NUM_CLASSES, freeze_backbone: bool = True):
        super().__init__()
        self.backbone = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
        if freeze_backbone:
            for param in self.backbone.parameters():
                param.requires_grad = False
        in_features = self.backbone.fc.in_features
        self.backbone.fc = nn.Sequential(
            nn.Dropout(0.2),
            nn.Linear(in_features, num_classes),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.backbone(x)

def train_one_epoch(model, loader, optimizer, criterion, device):
    model.train()
    running, correct, total = 0.0, 0, 0
    for images, labels in loader:
        images, labels = images.to(device), labels.to(device)
        optimizer.zero_grad()
        logits = model(images)
        loss = criterion(logits, labels)
        loss.backward()
        optimizer.step()
        running += loss.item() * images.size(0)
        correct += (logits.argmax(1) == labels).sum().item()
        total += images.size(0)
    return running / total, correct / total

@torch.no_grad()
def evaluate(model, loader, criterion, device):
    model.eval()
    running, correct, total = 0.0, 0, 0
    for images, labels in loader:
        images, labels = images.to(device), labels.to(device)
        logits = model(images)
        running += criterion(logits, labels).item() * images.size(0)
        correct += (logits.argmax(1) == labels).sum().item()
        total += images.size(0)
    return running / total, correct / total

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = ImageClassifier(freeze_backbone=True).to(device)
optimizer = torch.optim.AdamW(
    [p for p in model.parameters() if p.requires_grad], lr=1e-3
)
criterion = nn.CrossEntropyLoss()

dataset = datasets.ImageFolder("data/raw", transform=train_transform)
train_size = int(0.7 * len(dataset))
val_size = len(dataset) - train_size
train_set, val_set = random_split(dataset, [train_size, val_size], generator=torch.Generator().manual_seed(42))
val_set.dataset = datasets.ImageFolder("data/raw", transform=eval_transform)

train_loader = DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=4)
val_loader = DataLoader(val_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=4)

best_acc = 0.0
for epoch in range(1, 6):
    train_loss, train_acc = train_one_epoch(model, train_loader, optimizer, criterion, device)
    val_loss, val_acc = evaluate(model, val_loader, criterion, device)
    print(f"epoch {epoch}  train_acc={train_acc:.3f}  val_acc={val_acc:.3f}")
    if val_acc > best_acc:
        best_acc = val_acc
        torch.save(model.state_dict(), "checkpoints/best.pt")

Two details here earn their keep later. The evaluation transform is deterministic while the training transform is stochastic, so your validation accuracy is a stable number rather than a lottery. And the seed is fixed in the split, which means a rerun produces the same train and validation membership and therefore a comparable metric.

Phase 2: exporting for production inference

A training checkpoint is not a deployment artifact. Production wants a format that loads without the training stack, runs without autograd bookkeeping, and accepts a batch dimension that varies. TorchScript traced through the frozen model satisfies all three, and an ONNX export keeps a second path open if you later move serving to a different runtime.

python
import torch.onnx

model = ImageClassifier(num_classes=NUM_CLASSES, freeze_backbone=False)
model.load_state_dict(torch.load("checkpoints/best.pt", map_location="cpu"))
model.eval()

# TorchScript: single-file artifact, no Python class definition needed at serve time
example = torch.randn(1, 3, 224, 224)
scripted = torch.jit.trace(model, example)
scripted.save("artifacts/model.pt")

# ONNX: keep the batch axis dynamic for flexible serving
torch.onnx.export(
    model,
    example,
    "artifacts/model.onnx",
    input_names=["images"],
    output_names=["logits"],
    dynamic_axes={"images": {0: "batch"}, "logits": {0: "batch"}},
    opset_version=17,
)

print("torchscript size MB:", round(__import__("os").path.getsize("artifacts/model.pt") / 1e6, 1))
print("onnx size MB:", round(__import__("os").path.getsize("artifacts/model.onnx") / 1e6, 1))

Trace has one known weakness: control flow that depends on tensor values is baked in at trace time. This backbone has none, which is why tracing is safe here. If you add dynamic branches later, switch to scripting or re-export through ONNX, and add a numerical parity check that asserts the exported model's logits match the eager model's within a small tolerance on a batch of real images.

Phase 3: the prediction service

The service owns preprocessing. Callers send base64-encoded bytes and receive a class label and confidence, which keeps the model contract narrow and prevents the classic train-serve skew that appears when the client resizes images differently from training.

python
import base64
import io
from time import perf_counter

import torch
from fastapi import FastAPI, HTTPException
from PIL import Image
from pydantic import BaseModel, Field
from torchvision import transforms

app = FastAPI(title="Image Classifier", version="1.0.0")

artifact = torch.jit.load("artifacts/model.pt", map_location="cpu")
artifact.eval()

CLASS_NAMES = ["airplane", "automobile", "bird", "cat", "deer",
               "dog", "frog", "horse", "ship", "truck"]

serving_transform = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225]),
])

class ImageRequest(BaseModel):
    image_base64: str = Field(..., max_length=4_000_000)
    top_k: int = Field(1, ge=1, le=5)

class Prediction(BaseModel):
    label: str
    confidence: float

class ImageResponse(BaseModel):
    predictions: list[Prediction]
    latency_ms: float

@app.post("/predict", response_model=ImageResponse)
async def predict(request: ImageRequest) -> ImageResponse:
    start = perf_counter()
    try:
        raw = base64.b64decode(request.image_base64, validate=True)
        image = Image.open(io.BytesIO(raw)).convert("RGB")
    except Exception as exc:
        raise HTTPException(status_code=422, detail=f"invalid image: {exc}")

    tensor = serving_transform(image).unsqueeze(0)
    with torch.inference_mode():
        logits = artifact(tensor)
        probs = torch.softmax(logits, dim=1)[0]

    k = min(request.top_k, probs.numel())
    values, indices = torch.topk(probs, k)
    predictions = [
        Prediction(label=CLASS_NAMES[i], confidence=round(float(v), 4))
        for v, i in zip(values, indices)
    ]
    return ImageResponse(
        predictions=predictions,
        latency_ms=round((perf_counter() - start) * 1000, 2),
    )

@app.get("/health")
async def health() -> dict:
    probe = torch.zeros(1, 3, 224, 224)
    with torch.inference_mode():
        artifact(probe)
    return {"status": "ok", "classes": len(CLASS_NAMES)}

The health endpoint runs one throwaway forward pass. That is the cheapest honest signal that the weights loaded, the graph is valid, and the process can actually complete an inference, which a bare status string cannot prove.

Phase 4: the multi-stage container build

Training and serving have opposite dependency needs. Training wants the full vision stack and build tooling; serving wants weights, a small runtime, and nothing else. A multi-stage Dockerfile expresses that split and typically cuts the final image by more than half.

# ---- stage 1: produce the artifact ----
FROM python:3.11-slim AS builder

WORKDIR /build
COPY requirements-train.txt .
RUN pip install --no-cache-dir -r requirements-train.txt

COPY src/ ./src/
COPY checkpoints/ ./checkpoints/
RUN python -m src.export_model --checkpoint checkpoints/best.pt --out /build/artifacts

# ---- stage 2: slim serving image ----
FROM python:3.11-slim AS runtime

ENV PYTHONUNBUFFERED=1
WORKDIR /app

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

COPY --from=builder /build/artifacts ./artifacts
COPY app.py .

RUN useradd --create-home --uid 10001 appuser
USER appuser
EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
  CMD python -c "import urllib.request as u; u.urlopen('http://127.0.0.1:8000/health')"

CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]

One worker is intentional. TorchScript holds a thread pool per worker by default, and several workers on a small CPU instance thrash each other into worse latency than a single worker plus horizontal replicas. Verify that claim on your own hardware rather than trusting it; the load test will tell you within minutes.

Phase 5: running it on managed containers

For this project, a serverless container service is the right altitude: you keep control of the image, and the platform handles placement, health checks, and scaling. The task definition below is a compact example of the contract between your image and the orchestrator.

{
  "family": "image-classifier",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "1024",
  "memory": "2048",
  "containerDefinitions": [
    {
      "name": "classifier-api",
      "image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/image-classifier:1.0.0",
      "portMappings": [{ "containerPort": 8000, "protocol": "tcp" }],
      "healthCheck": {
        "command": ["CMD-SHELL", "curl -sf http://127.0.0.1:8000/health || exit 1"],
        "interval": 30,
        "timeout": 10,
        "retries": 3,
        "startPeriod": 60
      },
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/image-classifier",
          "awslogs-region": "us-east-1",
          "awslogs-stream-prefix": "api"
        }
      }
    }
  ]
}

The start period deserves a mention. Model loading takes longer than an average request handler, and without a generous start window the platform declares the task unhealthy and restarts it in a loop that never ends. Pair it with autoscaling on a request-count target rather than on CPU, because inference often saturates memory before it saturates processors.

Phase 6: verification and debugging

Run the evaluation harness against the deployed URL, not against the local process. The gap between local and remote catches everything that only appears over a network: payload size limits, timeouts, connection pooling, and the extra fifty milliseconds of TLS and load-balancer hops that quietly eat your latency budget.

SymptomLikely causeFirst check
Fifty-fours at the load balancerTimeout shorter than p99 plus queueingCompare LB timeout to measured p99
Accuracy far below validationPreprocessing mismatch at serve timeDiff serve transform against eval transform
Image pull fails at scaleArtifact larger than node ephemeral storageInspect image size, trim the runtime stage
Container restarts in a loopReadiness before weights loadRaise start period, gate on health body
Throughput collapses under loadToo many workers thrashing threadsPin worker count, load test the change
Memory climbs steadilyUndisposed request buffers or worker leakWatch resident memory over ten minutes

Fix issues in that order, re-running the harness after each change so improvements are provable. A deployment without a before-and-after measurement is just a different set of assumptions.

Common Mistakes

Serving the eager training checkpoint directly from the API process

Fix: Export to TorchScript or ONNX once, ship only the artifact, and load it in inference mode with gradients disabled

Letting the client resize images and skipping preprocessing on the server

Fix: Own the full preprocessing pipeline inside the service so serving always matches the evaluation transform

Adding more uvicorn workers to improve throughput on a small instance

Fix: Measure first; thread pools multiply per worker, so prefer fewer workers and more replicas

Setting no start period and watching the orchestrator restart a healthy-but-slow container forever

Fix: Give the task a start window longer than your measured cold start and gate readiness on a real forward pass

Checking accuracy on a fresh notebook kernel instead of a repeatable harness

Fix: Persist an evaluation script that loads the exported artifact and prints accuracy plus latency percentiles on every run

Best Practices

  • Record exit criteria before writing code, then let the harness decide whether the project is finished
  • Keep training, export, and serving dependencies in separate requirement files so the runtime image stays small
  • Save the class-name list alongside the artifact so label decoding cannot drift from the model version
  • Test export parity by comparing eager and exported logits on a fixed batch within a small tolerance
  • Deploy the same image to staging and production, differing only by a tag, so what you tested is what ships
  • Attach the evaluation report to the model version in your registry so rollback decisions have context

Interview Questions

Q1: Why export to TorchScript or ONNX instead of shipping the training checkpoint?

An exported artifact loads without the model class definition and without autograd bookkeeping, which shrinks the serving image and removes a whole class of dependency mismatches. It also enables graph-level optimizations and static shapes for batching. The checkpoint remains useful for resuming training, but it couples serving to your training code layout.

Q2: How do you know your exported model is numerically identical to the one you validated?

Run a parity check: feed the same batch of preprocessed images through the eager model and the exported artifact, then assert the maximum absolute difference in logits is below a small tolerance such as one e minus five. Do this inside CI so a future export upgrade cannot silently change predictions.

Q3: What breaks when you scale workers on a CPU-only inference container?

Each worker holds its own copy of the model and its own thread pool, so memory grows linearly and threads contend for the same cores. On a small instance this produces higher p95 latency than a single worker. The scalable path is more replicas behind the load balancer, with worker count tuned per instance family from load-test results.

Q4: Describe how you would roll back a bad model release.

The registry keeps the previous artifact tagged and its image digest recorded. Rollback points the serving task at the prior digest or model version, waits for health to pass, and re-runs the harness against the live URL to confirm metrics. Because responses carry the model version, you can attribute support tickets to the exact release that served them.

Key Takeaways

  • Define measurable exit criteria before training, covering accuracy, latency, image size, and cold start, not accuracy alone
  • Export once to TorchScript or ONNX with a dynamic batch axis, and verify parity against the eager model
  • Preprocessing belongs inside the service so the API always matches the evaluation transform that produced your reported accuracy
  • Multi-stage images and a single tuned worker keep the runtime small and predictable; scale with replicas
  • Verify against the deployed URL with a repeatable harness, because the network is where hidden assumptions surface
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Data Science Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement