ML in Practice — Lightweight MLOps
Back to Serving and Deployment

Building a Prediction Service — The FastAPI Pattern

FastAPI + a Pydantic schema + a loaded model = production-grade prediction service. The standard pattern. FIND_VIDEO: search 'fastapi machine learning model serving' — recommended channel: FastAPI / Made with ML. Aim for 11 min or under.

18 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.
Loading progress...

Key moments

  1. Serving Prerequisites Review — The instructor compares training pipelines with serving architectures and reviews the IMDB sentiment model architecture.
  2. Pruning Code for Inference — The training loop, optimizers, and loss definitions are removed to create a lean inference module.
  3. FastAPI Initialization — A FastAPI application instance is created alongside a basic health-check root route.
  4. Uvicorn and Swagger Inspection — The ASGI server is launched on port 12000 and tested via the interactive Swagger documentation UI.
  5. Model Weight Loading — The pre-trained model weights are loaded into memory globally and a typed prediction route is defined.
  6. Inference Pipeline Integration — Query strings are converted into dataset inputs with dummy targets and evaluated using a batch size of one.
  7. Logit Calibration and Response — Raw output logits are transformed via sigmoid activation into positive and negative confidence scores returned as JSON.
PDF notes

Frequently asked questions

Why does my API return unbounded values like 3.42 instead of sentiment percentages?

Models trained with BCEWithLogitsLoss output raw, unactivated logits. You must explicitly apply torch.sigmoid() to map output logits into a valid 0.0 to 1.0 probability range.

Why should I use GET instead of POST for this sentiment endpoint?

GET endpoints with query parameters allow quick manual debugging in browser address bars and Swagger UI; however, production payloads with long text should use POST with request bodies.

What happens if I forget to specify batch_size=1 in model.predict()?

The predict engine defaults to higher batch evaluations, incurring unnecessary memory buffering overhead and adding latency to real-time single-sample requests.

How do I access the interactive API documentation?

Navigate to the `/docs` path on your running server in any browser to open the auto-generated Swagger UI.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.