Model Deployment

Model Deployment

Guides an AI agent to deploy trained machine learning models to production through REST APIs, Docker, cloud platforms and batch or streaming serving.

Skill files3 files

scripts/

templates/

SKILL.md393 lines
1
---
2
name: Model Deployment
3
description: Deploy machine learning models to production using Flask, FastAPI, Docker, cloud platforms (AWS, GCP, Azure), and model serving frameworks
4
---
5
6
# Model Deployment
7
8
## Overview
9
10
Model deployment is the process of taking a trained machine learning model and making it available for production use through APIs, web services, or batch processing systems.
11
12
## When to Use
13
14
- When productionizing trained models for real-world inference and predictions
15
- When building REST APIs or web services for model serving
16
- When scaling predictions to serve multiple users or applications
17
- When deploying models to cloud platforms, edge devices, or containers
18
- When implementing CI/CD pipelines for ML model updates
19
- When creating batch processing systems for large-scale predictions
20
21
## Deployment Approaches
22
23
- **REST APIs**: Flask, FastAPI for synchronous inference
24
- **Batch Processing**: Scheduled jobs for large-scale predictions
25
- **Real-time Streaming**: Kafka, Spark Streaming for continuous data
26
- **Serverless**: AWS Lambda, Google Cloud Functions
27
- **Edge Deployment**: TensorFlow Lite, ONNX for edge devices
28
- **Model Serving**: TensorFlow Serving, Seldon Core, BentoML
29
30
## Key Considerations
31
32
- **Model Format**: Pickle, SavedModel, ONNX, PMML
33
- **Scalability**: Load balancing, auto-scaling
34
- **Latency**: Response time requirements
35
- **Monitoring**: Model drift, performance metrics
36
- **Versioning**: Multiple model versions in production
37
38
## Python Implementation
39
40
```python
41
import numpy as np
42
import pandas as pd
43
import pickle
44
import json
45
from sklearn.ensemble import RandomForestClassifier
46
from sklearn.preprocessing import StandardScaler
47
from sklearn.datasets import make_classification
48
import joblib
49
50
# FastAPI for REST API
51
from fastapi import FastAPI, HTTPException, BackgroundTasks
52
from pydantic import BaseModel, Field
53
import uvicorn
54
55
# For model serving
56
import mlflow.pyfunc
57
import mlflow.sklearn
58
59
# Docker and deployment
60
import logging
61
import time
62
from typing import List, Dict
63
64
# Configure logging
65
logging.basicConfig(level=logging.INFO)
66
logger = logging.getLogger(__name__)
67
68
print("=== 1. Train and Save Model ===")
69
70
# Create dataset
71
X, y = make_classification(n_samples=1000, n_features=20, random_state=42)
72
scaler = StandardScaler()
73
X_scaled = scaler.fit_transform(X)
74
75
# Train model
76
model = RandomForestClassifier(n_estimators=100, max_depth=10, random_state=42)
77
model.fit(X_scaled, y)
78
79
# Save model and preprocessing
80
model_path = '/tmp/model.pkl'
81
scaler_path = '/tmp/scaler.pkl'
82
83
joblib.dump(model, model_path)
84
joblib.dump(scaler, scaler_path)
85
86
print(f"Model saved to {model_path}")
87
print(f"Scaler saved to {scaler_path}")
88
89
# 2. Model Serving Class
90
print("\n=== 2. Model Serving Class ===")
91
92
class ModelPredictor:
93
def __init__(self, model_path, scaler_path):
94
self.model = joblib.load(model_path)
95
self.scaler = joblib.load(scaler_path)
96
self.load_time = time.time()
97
self.predictions_count = 0
98
logger.info("Model loaded successfully")
99
100
def predict(self, features: List[List[float]]) -> Dict:
101
try:
102
X = np.array(features)
103
X_scaled = self.scaler.transform(X)
104
predictions = self.model.predict(X_scaled)
105
probabilities = self.model.predict_proba(X_scaled)
106
107
self.predictions_count += len(X)
108
109
return {
110
'predictions': predictions.tolist(),
111
'probabilities': probabilities.tolist(),
112
'count': len(X),
113
'timestamp': time.time()
114
}
115
except Exception as e:
116
logger.error(f"Prediction error: {str(e)}")
117
raise
118
119
def health_check(self) -> Dict:
120
return {
121
'status': 'healthy',
122
'uptime': time.time() - self.load_time,
123
'predictions': self.predictions_count
124
}
125
126
# Initialize predictor
127
predictor = ModelPredictor(model_path, scaler_path)
128
129
# 3. FastAPI Application
130
print("\n=== 3. FastAPI Application ===")
131
132
app = FastAPI(
133
title="ML Model API",
134
description="Production ML model serving API",
135
version="1.0.0"
136
)
137
138
class PredictionRequest(BaseModel):
139
features: List[List[float]] = Field(..., example=[[1.0, 2.0, 3.0]])
140
141
class PredictionResponse(BaseModel):
142
predictions: List[int]
143
probabilities: List[List[float]]
144
count: int
145
timestamp: float
146
147
class HealthResponse(BaseModel):
148
status: str
149
uptime: float
150
predictions: int
151
152
@app.get("/health", response_model=HealthResponse)
153
async def health_check():
154
"""Health check endpoint"""
155
return predictor.health_check()
156
157
@app.post("/predict", response_model=PredictionResponse)
158
async def predict(request: PredictionRequest):
159
"""Make predictions"""
160
try:
161
result = predictor.predict(request.features)
162
return result
163
except Exception as e:
164
raise HTTPException(status_code=400, detail=str(e))
165
166
@app.post("/predict-batch")
167
async def predict_batch(requests: List[PredictionRequest], background_tasks: BackgroundTasks):
168
"""Batch prediction with background processing"""
169
all_features = []
170
for req in requests:
171
all_features.extend(req.features)
172
173
result = predictor.predict(all_features)
174
background_tasks.add_task(logger.info, f"Batch prediction processed: {result['count']} samples")
175
return result
176
177
@app.get("/stats")
178
async def get_stats():
179
"""Get model statistics"""
180
return {
181
'model_type': type(predictor.model).__name__,
182
'n_estimators': predictor.model.n_estimators,
183
'max_depth': predictor.model.max_depth,
184
'feature_importance': predictor.model.feature_importances_.tolist(),
185
'total_predictions': predictor.predictions_count
186
}
187
188
# 4. Dockerfile template
189
print("\n=== 4. Dockerfile Template ===")
190
191
dockerfile_content = '''FROM python:3.9-slim
192
193
WORKDIR /app
194
195
COPY requirements.txt .
196
RUN pip install --no-cache-dir -r requirements.txt
197
198
COPY model.pkl .
199
COPY scaler.pkl .
200
COPY app.py .
201
202
EXPOSE 8000
203
204
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
205
'''
206
207
print("Dockerfile content:")
208
print(dockerfile_content)
209
210
# 5. Requirements file
211
print("\n=== 5. Requirements.txt ===")
212
213
requirements = """fastapi==0.104.1
214
uvicorn[standard]==0.24.0
215
numpy==1.24.0
216
pandas==2.1.0
217
scikit-learn==1.3.2
218
joblib==1.3.2
219
pydantic==2.5.0
220
mlflow==2.8.1
221
"""
222
223
print("Requirements:")
224
print(requirements)
225
226
# 6. Docker Compose for deployment
227
print("\n=== 6. Docker Compose Template ===")
228
229
docker_compose = '''version: '3.8'
230
231
services:
232
ml-api:
233
build: .
234
ports:
235
- "8000:8000"
236
environment:
237
- LOG_LEVEL=info
238
- WORKERS=4
239
restart: unless-stopped
240
healthcheck:
241
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
242
interval: 10s
243
timeout: 5s
244
retries: 3
245
246
ml-monitor:
247
image: prom/prometheus:latest
248
ports:
249
- "9090:9090"
250
volumes:
251
- ./prometheus.yml:/etc/prometheus/prometheus.yml
252
command:
253
- "--config.file=/etc/prometheus/prometheus.yml"
254
255
ml-dashboard:
256
image: grafana/grafana:latest
257
ports:
258
- "3000:3000"
259
environment:
260
- GF_SECURITY_ADMIN_PASSWORD=admin
261
volumes:
262
- ./grafana/dashboards:/etc/grafana/provisioning/dashboards
263
'''
264
265
print("Docker Compose content:")
266
print(docker_compose)
267
268
# 7. Testing the API
269
print("\n=== 7. Testing the API ===")
270
271
def test_predictor():
272
# Test single prediction
273
test_features = [[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0,
274
1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1, 9.1, 10.1]]
275
276
result = predictor.predict(test_features)
277
print(f"Prediction result: {result}")
278
279
# Health check
280
health = predictor.health_check()
281
print(f"Health status: {health}")
282
283
# Batch predictions
284
batch_features = [
285
[1.0] * 20,
286
[2.0] * 20,
287
[3.0] * 20,
288
]
289
batch_result = predictor.predict(batch_features)
290
print(f"Batch prediction: {batch_result['count']} samples processed")
291
292
test_predictor()
293
294
# 8. Model versioning and registry
295
print("\n=== 8. Model Registry with MLflow ===")
296
297
# Log model to MLflow
298
with mlflow.start_run():
299
mlflow.sklearn.log_model(model, "model")
300
mlflow.log_param("max_depth", 10)
301
mlflow.log_param("n_estimators", 100)
302
mlflow.log_metric("accuracy", 0.95)
303
304
model_uri = "runs:/" + mlflow.active_run().info.run_id + "/model"
305
print(f"Model logged to MLflow: {model_uri}")
306
307
# 9. Deployment monitoring code
308
print("\n=== 9. Monitoring Setup ===")
309
310
class ModelMonitor:
311
def __init__(self):
312
self.predictions = []
313
self.latencies = []
314
315
def log_prediction(self, features, prediction, latency):
316
self.predictions.append({
317
'timestamp': time.time(),
318
'features_mean': np.mean(features),
319
'prediction': prediction,
320
'latency_ms': latency * 1000
321
})
322
323
def check_model_drift(self):
324
if len(self.predictions) < 100:
325
return {'drift_detected': False}
326
327
recent_predictions = [p['prediction'] for p in self.predictions[-100:]]
328
historical_mean = np.mean([p['prediction'] for p in self.predictions[:-100]])
329
recent_mean = np.mean(recent_predictions)
330
331
drift = abs(recent_mean - historical_mean) > 0.1
332
333
return {
334
'drift_detected': drift,
335
'historical_mean': float(historical_mean),
336
'recent_mean': float(recent_mean),
337
'threshold': 0.1
338
}
339
340
def get_stats(self):
341
if not self.latencies:
342
return {}
343
344
return {
345
'avg_latency_ms': np.mean(self.latencies) * 1000,
346
'p95_latency_ms': np.percentile(self.latencies, 95) * 1000,
347
'p99_latency_ms': np.percentile(self.latencies, 99) * 1000,
348
'total_predictions': len(self.predictions)
349
}
350
351
monitor = ModelMonitor()
352
353
print("\nDeployment setup completed!")
354
print("To run FastAPI server: uvicorn app:app --reload")
355
```
356
357
## Deployment Checklist
358
359
- Model format and serialization
360
- Input/output validation
361
- Error handling and logging
362
- Authentication and security
363
- Rate limiting and throttling
364
- Health check endpoints
365
- Monitoring and alerting
366
- Version management
367
- Rollback procedures
368
369
## Cloud Deployment Options
370
371
- **AWS**: SageMaker, Lambda, EC2
372
- **GCP**: Vertex AI, Cloud Run, App Engine
373
- **Azure**: Machine Learning, App Service
374
- **Kubernetes**: Self-managed on-premises
375
376
## Performance Optimization
377
378
- Model quantization for smaller size
379
- Caching predictions
380
- Batch processing
381
- GPU acceleration
382
- Request pooling
383
384
## Deliverables
385
386
- Deployed model endpoint
387
- API documentation
388
- Docker configuration
389
- Monitoring dashboard
390
- Deployment guide
391
- Performance benchmarks
392
- Scaling recommendations
393

© AJ Geddes · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…