26 Letting the Cat Outside
MLOps, APIs, and Docker
⏳ 2026 Edition: Last verified: 2026-11-26
Prerequisites: Chapter 25
Technical Keywords: MLOps, Model Deployment, APIs (REST/FastAPI), Docker/Containerization, CI/CD for ML, Model Monitoring, Data Drift, Edge AI
🧭 Advanced Track Navigation Core Track completion is defined by Checkpoints 1-4. This chapter belongs to the Advanced Track. Safe to skim on first pass; not required for checkpoints.
A Jupyter Notebook is a cozy, warm experimentation environment. The data is cleaner and operational risks are lower, though it is not a security sandbox (code runs with your normal user permissions), and pressing Shift + Enter simply executes one cell inside the existing kernel state—to truly reset memory and start fresh, you have to restart the kernel and re-run from the top.
But users don’t live in Jupyter Notebooks. If you want to build a real product, you have to package Pixel up, put him on a server, and let him talk to the internet. This is the discipline of MLOps (Machine Learning Operations).
26.1 APIs: The Cat Door
How does a user’s mobile app actually talk to your PyTorch model? Through an API (Application Programming Interface)—commonly built following the REST architectural style over HTTP, implemented with a Python web framework such as FastAPI or Flask.
The API acts as a cat door between external clients and your model:
- The user’s phone sends a JSON packet over the internet containing an image of a toy (the Request).
- The cat door receives the image, formats it into a Tensor, and hands it to Pixel.
- Pixel does a Forward Pass (Chapter 8) and outputs
[0.99, "Mouse"]. - The cat door packages that answer into a JSON packet and sends it back to the phone (the Response).
Note that an API is not safe by default: exposing a model endpoint on the internet requires explicit security controls—authentication (API keys or OAuth/JWT), strict input validation (schemas and payload size limits), rate limiting, and TLS/HTTPS encryption.
26.2 Docker: The Indestructible Carrier
“It works on my machine!” is the most dangerous phrase in software engineering. If you build an AI on a Windows laptop using Python 3.9 and PyTorch 2.0, and then upload that code to a Linux cloud server running Python 3.10 and PyTorch 1.8… you hit dependency crashes, incompatible APIs, or subtle weight-loading errors.
To fix this, we use Docker. Docker packages your code, your exact Python and PyTorch versions, and all system libraries into a frozen, immutable blueprint called a Docker image. When you deploy, Docker launches a Docker container—an isolated running process built from that image, like placing Pixel inside an indestructible virtual carrier.
When you deploy to the cloud, you don’t rely on raw host libraries—you run a container from your image. This greatly improves environment consistency across machines (though OS kernel or GPU driver/hardware differences can still matter in edge cases).
Minimal Production Walkthrough: FastAPI + Docker
Here is a compact, runnable PyTorch inference service with Pydantic input validation, packaged in a Dockerfile:
# app.py — minimal FastAPI inference server for a PyTorch model
from fastapi import FastAPI
from pydantic import BaseModel, Field
import torch
app = FastAPI(title="Pixel Treat Predictor")
# Deterministic demo linear layer (swap with torch.load(...) in production)
model = torch.nn.Linear(2, 1)
with torch.no_grad():
model.weight.copy_(torch.tensor([[0.2, -0.1]]))
model.bias.zero_()
model.eval()
class JumpInput(BaseModel):
forward_paws: float = Field(..., ge=-100.0, le=100.0)
sideways_paws: float = Field(..., ge=-100.0, le=100.0)
@app.post("/predict")
def predict(payload: JumpInput):
x = torch.tensor([[payload.forward_paws, payload.sideways_paws]])
with torch.inference_mode():
score = float(torch.sigmoid(model(x)).item())
return {"treat_score": round(score, 4)}(Note: This uses an untrained demonstration model with fixed weights that outputs a raw sigmoid score, not a calibrated probability.)
# Dockerfile — immutable blueprint (image) for consistent runtime dependencies
FROM python:3.11-slim
WORKDIR /app
RUN pip install --no-cache-dir fastapi uvicorn
RUN pip install --no-cache-dir torch \
--index-url https://download.pytorch.org/whl/cpu
COPY app.py .
EXPOSE 8000
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]Build the image, run a container bound to localhost (127.0.0.1), and query the endpoint with curl:
docker build -t pixel-api:v1 .
docker run -d -p 127.0.0.1:8000:8000 --name pixel-serving pixel-api:v1
curl -X POST http://127.0.0.1:8000/predict \
-H "Content-Type: application/json" \
-d '{"forward_paws": 3.0, "sideways_paws": 4.0}'26.3 Monitoring: The GPS Collar (Data Drift)
Pixel is running perfectly in the cloud. You go to sleep. Three months later, the model’s accuracy drops from 95% to 40%. The API didn’t crash. No code changed. What happened?
Data Drift or Concept Drift (both forms of Distribution Shift from Chapter 18) happened:
- Data Drift (Covariate Shift): The distribution of incoming inputs changes (P_{\text{live}}(X) \neq P_{\text{train}}(X))—for example, users start uploading night-time or low-resolution photos your model rarely saw during training.
- Concept Drift: The underlying relationship between inputs and targets shifts (P(Y \mid X) changes)—for example, macro conditions or interest rates shift, so the exact same house features no longer correspond to the same sale price.
In MLOps, you build Monitoring Dashboards to track both incoming feature distributions and live model accuracy/calibration. When live inputs or target behavior diverge from your Training Set, the dashboard triggers an alert so you know it is time to evaluate and retrain.
26.4 Edge AI: The Kitten in your Pocket
Sometimes, relying on a cloud server is impossible. If you are building a self-driving car, you cannot afford a 200-millisecond API delay while the car asks a server in Virginia if it should hit the brakes.
You must put the AI directly onto the hardware (the phone, the car, the drone). This is Edge AI. Because Edge devices have tiny batteries and no massive GPUs, you must aggressively use Quantization (Chapter 24) to shrink the model from FP32 to INT8, and use specialized mobile architectures.
26.5 Agent Runtimes: Thought, Action, and Memory 🧭
In production, AI is rarely just a single-turn chatbot. Increasingly, it runs as an Agent — a system that autonomously plans, calls tools, and recovers state over multi-step tasks.
- The ReAct Loop (Reason + Act): The foundational pattern for tool use. Pixel thinks (“I need weather”), acts (calls the Weather API), and observes the result (“It is raining”). He repeats this loop until the task is complete.
- Reflexion (Learning from Failure): If Pixel fails a task, he writes a short reflection on why he failed, stores it in memory, and uses that memory to guide his next attempt.
- Managed Agent Platforms (2026 Shift): Historically, developers wrote fragile custom
whileloops to orchestrate agents, which broke easily on long-running jobs. In 2026, cloud and framework providers increasingly offer hosted or managed agent runtimes—running orchestration inside persistent, checkpointed sandboxes with credential isolation, state recovery, and automated verification or rollback gates when a multi-step edit fails tests.
Rosetta Stone
| Kitten World | Math/Concept | The Tool/System |
|---|---|---|
| “The cat door” | APIs (REST architectural style) | FastAPI / Flask (web frameworks) |
| “The indestructible carrier” | Containerization (Image vs. Container) | Docker |
| “The GPS collar” | Monitoring, Data Drift & Concept Drift | Prometheus / Grafana / Evidently |
| “The kitten in your pocket” | Edge AI & Quantization | CoreML / TFLite / ONNX |
26.6 Removing the Training Wheels
The Real Engineering
Deploying a model means wrapping PyTorch inference code in a REST API (implemented with a web framework like FastAPI) and packaging dependencies into an immutable Docker image launched as an isolated container. In production, Data Drift (P(X) shifts) and Concept Drift (P(Y \mid X) shifts) erode model accuracy, requiring continuous monitoring of both feature distributions and live outcomes. For Edge AI, models are compressed via quantization and pruning to meet strict latency and power limits.
26.7 Paws and Reflect: Chapter Quiz
Work through these conceptually before checking the answers.
You build a PyTorch model. A web developer asks, “How do I send data to this from my JavaScript frontend?” What do you build to connect them?
You update a single library on your laptop, and suddenly your deployment server crashes. What MLOps technology—and specifically which two artifacts/concepts—would have prevented this environment mismatch?
Your model’s accuracy slowly degrades over six months even though no code changed. Distinguish between the two main kinds of drift that could cause this.
Reveal answers
- A REST API built with a Python web framework such as FastAPI or Flask. REST defines the HTTP request/response style, while FastAPI is the framework implementing the server endpoint between the frontend and your Python model.
- Docker / Containerization. You freeze your code and exact library versions into an immutable Docker image (the blueprint) and run it inside an isolated Docker container (the live process) on the server.
- Data Drift (input distributions shift, P_{\text{live}}(X) \neq P_{\text{train}}(X)) or Concept Drift (the relationship between inputs and true labels shifts, P(Y \mid X) changes).
26.8 Chapter 26 Summary
You’ve learned core deployment patterns and risks:
- APIs (REST via FastAPI): The interface that lets front-end apps query your model (secured with auth, input validation, rate limiting, and TLS).
- Docker: The container that improves environment consistency across platforms.
- MLOps & Monitoring: Tracking live data to catch Data Drift before it causes catastrophic business failures.
- Edge AI: Quantizing models so they can run locally on phones and cars without internet latency.
AI Safety Thread: Chapter 26
Feedback Loops: When you deploy an AI, its outputs often become the internet’s future inputs. If you deploy an AI to automatically write news articles, those articles get indexed by Google. Next year, when you scrape Google to train your next AI, your new AI is training on the hallucinated outputs of your old AI. This creates a terrifying Feedback Loop that continuously amplifies biases and hallucinations, permanently polluting the digital ecosystem. MLOps teams must build rigorous filters to ensure live outputs do not poison future training data.
Next: Chapter 27: Dreaming of Electric Mice: GANs, VAEs, and Diffusion →