diff --git a/.jules/bolt.md b/.jules/bolt.md index 7e410c4..43ca330 100644 --- a/.jules/bolt.md +++ b/.jules/bolt.md @@ -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. diff --git a/ml_service.py b/ml_service.py index bee0bde..c5d2bb3 100644 --- a/ml_service.py +++ b/ml_service.py @@ -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)