30 Mins

4. Multi-Model Pipelines

Packaging Preprocessing Pipelines

In production environments, keeping the preprocessing logic separate from your model creates 'training-serving skew'. By using Scikit-Learn's Pipeline object, you bundle transformers and estimators into a single artifact.

When you save a pipeline using joblib, you preserve the state of transformers (like mean values in a scaler), ensuring that the exact same transformations are applied during inference as during training.

Operator Note: Always include your preprocessing steps inside the pipeline to avoid data leakage and manual calculation errors.
Python 3
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
import numpy as np
import joblib

# Create a mock pipeline
pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('regressor', LinearRegression())
])

# Fit on dummy data
X = np.array([[1, 2], [3, 4], [5, 6]])
y = np.array([10, 20, 30])
pipeline.fit(X, y)

# Save the bundle
joblib.dump(pipeline, 'model_bundle.pkl')
print('Pipeline saved successfully.')

Serving Multiple Models in FastAPI

A robust FastAPI application can handle heterogeneous models by initializing them within the app state or as a dictionary mapping route patterns to specific model loaders.

By leveraging the lifespan context manager, you ensure models are loaded into memory exactly once when the server starts, rather than during every request.

Operator Note: Using a dictionary to map endpoint arguments to model objects is more scalable than using complex if-else logic.
Text
from fastapi import FastAPI

app = FastAPI()
models = {
    'regression': 'reg_model_v1',
    'classification': 'clf_model_v1'
}

@app.get('/predict/{model_type}')
async def predict(model_type: str):
    if model_type not in models:
        return {'error': 'Model not found'}
    return {'using': models[model_type]}

Dynamic Model Routing

Dynamic routing allows you to support A/B testing or canary deployments. You can route traffic to different model versions based on header information or query parameters.

Below is a comparison of common routing strategies in production systems.

Operator Note: Use headers for routing in production so the client code remains clean of model versioning logic.
MethodUse Case
Query ParamDeveloper debugging
Header-basedA/B Testing

Testing Endpoints with TestClient

Testing is crucial for deployment. FastAPI provides a built-in TestClient (based on Starlette) that allows you to simulate network requests to your endpoints without running a live server.

You should test the payload parsing, the status codes, and the inference structure for every model integrated into your app.

Operator Note: Always write integration tests that assert both the status code and the JSON structure of your predictions.
Python 3
from fastapi.testclient import TestClient
from fastapi import FastAPI

app = FastAPI()
@app.get('/health')
def health(): return {'status': 'ok'}

client = TestClient(app)
response = client.get('/health')
print(f'Status: {response.status_code}, Data: {response.json()}')

Knowledge Check

Ready to test your understanding of 4. Multi-Model Pipelines?

Back