Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,7 @@
## 2026-06-10 - [Lazy Loading Scikit-learn & NumPy]
**Learning:** Top-level imports of `numpy` and `joblib` plus loading a serialized model file (`.joblib`) during FastAPI startup adds significant overhead (e.g., ~3 seconds). Refactoring this into a service with `cached_property` and local imports deferred the cost until the first request.
**Action:** Move all heavy ML model loading and their dependencies into lazy-loaded properties to ensure near-instant application startup.

## 2026-06-20 - [ML Prediction Hot Path Optimization]
**Learning:** Passing a list of lists directly to Scikit-learn's `model.predict()` avoids the significant overhead of `numpy` array creation and reshaping for single-sample inference. Combining this with per-instance `lru_cache` (via a `cached_property` returning a closure) provides safe, massive performance wins for repeat requests without memory leaks or unhashable `self` issues.
**Action:** For single-sample ML inference, prefer native Python structures over `numpy` when supported by the model, and use per-instance memoization closures to optimize hot paths safely.
23 changes: 18 additions & 5 deletions ml_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,25 @@ def model(self):
logger.error(f"Error loading ML model: {e}")
return None

@cached_property
def _predict_internal(self):
"""Internal method to provide instance-level caching for predictions."""
from functools import lru_cache

@lru_cache(maxsize=128)
def _cached_predict(features_tuple):
# Scikit-learn models can often take a list of lists directly,
# avoiding the overhead of numpy array creation for a single sample.
prediction = self.model.predict([features_tuple])
return int(prediction[0])

return _cached_predict

def predict(self, features_list):
"""Perform prediction using the lazy-loaded model."""
"""Perform prediction using the lazy-loaded model with caching."""
if self.model is None:
raise RuntimeError("ML model could not be loaded")

import numpy as np
features = np.array(features_list).reshape(1, -1)
prediction = self.model.predict(features)
return int(prediction[0])
# Use a tuple to make features hashable for lru_cache
features_tuple = tuple(features_list)
return self._predict_internal(features_tuple)
Loading