Spaces:
Sleeping
Sleeping
Update src/dlrm_inference.py
Browse files- src/dlrm_inference.py +99 -17
src/dlrm_inference.py
CHANGED
|
@@ -3,6 +3,8 @@ DLRM Inference Engine for Book Recommendations
|
|
| 3 |
Loads trained DLRM model and provides recommendation functionality
|
| 4 |
"""
|
| 5 |
|
|
|
|
|
|
|
| 6 |
import torch
|
| 7 |
import numpy as np
|
| 8 |
import pandas as pd
|
|
@@ -10,17 +12,34 @@ import pickle
|
|
| 10 |
import mlflow
|
| 11 |
from mlflow import MlflowClient
|
| 12 |
import tempfile
|
| 13 |
-
import os
|
| 14 |
from typing import List, Dict, Tuple, Optional, Any
|
| 15 |
from functools import partial
|
| 16 |
import warnings
|
| 17 |
warnings.filterwarnings('ignore')
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
class DLRMBookRecommender:
|
| 26 |
"""DLRM-based book recommender for inference"""
|
|
@@ -36,7 +55,22 @@ class DLRMBookRecommender:
|
|
| 36 |
self.device = torch.device("cpu")
|
| 37 |
self.model = None
|
| 38 |
self.preprocessing_info = None
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
# Load preprocessing info
|
| 41 |
self._load_preprocessing_info()
|
| 42 |
|
|
@@ -48,6 +82,23 @@ class DLRMBookRecommender:
|
|
| 48 |
else:
|
| 49 |
print("⚠️ No model loaded. Please provide model_path or run_id")
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
def _load_preprocessing_info(self):
|
| 52 |
"""Load preprocessing information"""
|
| 53 |
if os.path.exists('book_dlrm_preprocessing.pkl'):
|
|
@@ -268,10 +319,18 @@ class DLRMBookRecommender:
|
|
| 268 |
Returns:
|
| 269 |
Prediction probability (0-1)
|
| 270 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
if self.model is None:
|
| 272 |
print("❌ Model not loaded")
|
| 273 |
return 0.0
|
| 274 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
try:
|
| 276 |
# Prepare features
|
| 277 |
dense_features, user_id_encoded, country_encoded, age_group = self._prepare_user_features(user_id, user_data)
|
|
@@ -314,8 +373,8 @@ class DLRMBookRecommender:
|
|
| 314 |
Returns:
|
| 315 |
List of (book_isbn, prediction_score) tuples
|
| 316 |
"""
|
| 317 |
-
if self.model is None:
|
| 318 |
-
print("❌ Model not loaded")
|
| 319 |
return []
|
| 320 |
|
| 321 |
recommendations = []
|
|
@@ -407,33 +466,56 @@ def load_dlrm_recommender(model_source: str = "latest") -> DLRMBookRecommender:
|
|
| 407 |
Returns:
|
| 408 |
DLRMBookRecommender instance
|
| 409 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
recommender = DLRMBookRecommender()
|
| 411 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
if model_source == "latest":
|
| 413 |
# Try to get latest MLflow run
|
| 414 |
try:
|
| 415 |
experiment = mlflow.get_experiment_by_name('dlrm-book-recommendation-book_recommender')
|
| 416 |
if experiment:
|
| 417 |
-
runs = mlflow.search_runs(experiment_ids=[experiment.experiment_id],
|
| 418 |
order_by=["start_time desc"], max_results=1)
|
| 419 |
if len(runs) > 0:
|
| 420 |
latest_run_id = runs.iloc[0].run_id
|
| 421 |
recommender = DLRMBookRecommender(run_id=latest_run_id)
|
| 422 |
return recommender
|
| 423 |
-
except:
|
| 424 |
-
|
| 425 |
|
| 426 |
elif model_source == "file":
|
| 427 |
# Try to load from local file
|
| 428 |
-
for filename in [
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
if os.path.exists(filename):
|
| 430 |
-
|
| 431 |
-
|
|
|
|
|
|
|
|
|
|
| 432 |
|
| 433 |
else:
|
| 434 |
# Treat as run_id
|
| 435 |
-
|
| 436 |
-
|
|
|
|
|
|
|
|
|
|
| 437 |
|
| 438 |
print("⚠️ Could not load any trained model")
|
| 439 |
return recommender
|
|
|
|
| 3 |
Loads trained DLRM model and provides recommendation functionality
|
| 4 |
"""
|
| 5 |
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
import torch
|
| 9 |
import numpy as np
|
| 10 |
import pandas as pd
|
|
|
|
| 12 |
import mlflow
|
| 13 |
from mlflow import MlflowClient
|
| 14 |
import tempfile
|
|
|
|
| 15 |
from typing import List, Dict, Tuple, Optional, Any
|
| 16 |
from functools import partial
|
| 17 |
import warnings
|
| 18 |
warnings.filterwarnings('ignore')
|
| 19 |
|
| 20 |
+
# Check for CPU_ONLY environment variable
|
| 21 |
+
CPU_ONLY = os.environ.get('CPU_ONLY', 'false').lower() == 'true'
|
| 22 |
+
|
| 23 |
+
# Disable CUDA if CPU_ONLY is set
|
| 24 |
+
if CPU_ONLY:
|
| 25 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = ''
|
| 26 |
+
print("🔄 Running in CPU-only mode (CUDA disabled)")
|
| 27 |
+
|
| 28 |
+
# Only import torchrec if not in CPU_ONLY mode
|
| 29 |
+
TORCHREC_AVAILABLE = False
|
| 30 |
+
if not CPU_ONLY:
|
| 31 |
+
try:
|
| 32 |
+
from torchrec import EmbeddingBagCollection
|
| 33 |
+
from torchrec.models.dlrm import DLRM, DLRMTrain
|
| 34 |
+
from torchrec.modules.embedding_configs import EmbeddingBagConfig
|
| 35 |
+
from torchrec.sparse.jagged_tensor import KeyedJaggedTensor
|
| 36 |
+
from torchrec.datasets.utils import Batch
|
| 37 |
+
TORCHREC_AVAILABLE = True
|
| 38 |
+
except ImportError as e:
|
| 39 |
+
print(f"⚠️ Warning: torchrec import error: {e}")
|
| 40 |
+
print("⚠️ Some functionality will be limited")
|
| 41 |
+
else:
|
| 42 |
+
print("⚠️ Running in CPU-only mode without torchrec")
|
| 43 |
|
| 44 |
class DLRMBookRecommender:
|
| 45 |
"""DLRM-based book recommender for inference"""
|
|
|
|
| 55 |
self.device = torch.device("cpu")
|
| 56 |
self.model = None
|
| 57 |
self.preprocessing_info = None
|
| 58 |
+
self.torchrec_available = TORCHREC_AVAILABLE
|
| 59 |
+
self.cpu_only = CPU_ONLY
|
| 60 |
+
self.dense_cols = []
|
| 61 |
+
self.cat_cols = []
|
| 62 |
+
self.emb_counts = []
|
| 63 |
+
|
| 64 |
+
if self.cpu_only:
|
| 65 |
+
print("⚠️ Running in CPU-only mode with limited functionality")
|
| 66 |
+
# Load minimal preprocessing info for browsing
|
| 67 |
+
self._load_minimal_preprocessing()
|
| 68 |
+
return
|
| 69 |
+
|
| 70 |
+
if not self.torchrec_available:
|
| 71 |
+
print("⚠️ Running in limited mode without torchrec")
|
| 72 |
+
return
|
| 73 |
+
|
| 74 |
# Load preprocessing info
|
| 75 |
self._load_preprocessing_info()
|
| 76 |
|
|
|
|
| 82 |
else:
|
| 83 |
print("⚠️ No model loaded. Please provide model_path or run_id")
|
| 84 |
|
| 85 |
+
def _load_minimal_preprocessing(self):
|
| 86 |
+
"""Load minimal preprocessing info for CPU-only mode"""
|
| 87 |
+
try:
|
| 88 |
+
if os.path.exists('book_dlrm_preprocessing.pkl'):
|
| 89 |
+
with open('book_dlrm_preprocessing.pkl', 'rb') as f:
|
| 90 |
+
self.preprocessing_info = pickle.load(f)
|
| 91 |
+
|
| 92 |
+
self.dense_cols = self.preprocessing_info.get('dense_cols', [])
|
| 93 |
+
self.cat_cols = self.preprocessing_info.get('cat_cols', [])
|
| 94 |
+
self.emb_counts = self.preprocessing_info.get('emb_counts', [])
|
| 95 |
+
|
| 96 |
+
print("✅ Minimal preprocessing info loaded for CPU-only mode")
|
| 97 |
+
else:
|
| 98 |
+
print("⚠️ No preprocessing info found for CPU-only mode")
|
| 99 |
+
except Exception as e:
|
| 100 |
+
print(f"⚠️ Error loading minimal preprocessing: {e}")
|
| 101 |
+
|
| 102 |
def _load_preprocessing_info(self):
|
| 103 |
"""Load preprocessing information"""
|
| 104 |
if os.path.exists('book_dlrm_preprocessing.pkl'):
|
|
|
|
| 319 |
Returns:
|
| 320 |
Prediction probability (0-1)
|
| 321 |
"""
|
| 322 |
+
if self.cpu_only:
|
| 323 |
+
print("⚠️ Cannot make predictions in CPU-only mode")
|
| 324 |
+
return 0.5 # Return default neutral prediction
|
| 325 |
+
|
| 326 |
if self.model is None:
|
| 327 |
print("❌ Model not loaded")
|
| 328 |
return 0.0
|
| 329 |
|
| 330 |
+
if not self.torchrec_available:
|
| 331 |
+
print("❌ Cannot make predictions without torchrec")
|
| 332 |
+
return 0.5 # Return default neutral prediction
|
| 333 |
+
|
| 334 |
try:
|
| 335 |
# Prepare features
|
| 336 |
dense_features, user_id_encoded, country_encoded, age_group = self._prepare_user_features(user_id, user_data)
|
|
|
|
| 373 |
Returns:
|
| 374 |
List of (book_isbn, prediction_score) tuples
|
| 375 |
"""
|
| 376 |
+
if self.cpu_only or self.model is None or not self.torchrec_available:
|
| 377 |
+
print("❌ Model not loaded, CPU-only mode, or torchrec not available")
|
| 378 |
return []
|
| 379 |
|
| 380 |
recommendations = []
|
|
|
|
| 466 |
Returns:
|
| 467 |
DLRMBookRecommender instance
|
| 468 |
"""
|
| 469 |
+
# Check if we're in CPU-only mode
|
| 470 |
+
cpu_only = os.environ.get('CPU_ONLY', 'false').lower() == 'true'
|
| 471 |
+
if cpu_only:
|
| 472 |
+
print("🔄 Loading recommender in CPU-only mode")
|
| 473 |
+
# In CPU-only mode, just return a basic recommender instance
|
| 474 |
+
return DLRMBookRecommender()
|
| 475 |
+
|
| 476 |
+
# Create recommender instance
|
| 477 |
recommender = DLRMBookRecommender()
|
| 478 |
|
| 479 |
+
# If torchrec is not available, return limited recommender
|
| 480 |
+
if not TORCHREC_AVAILABLE:
|
| 481 |
+
print("⚠️ torchrec not available, returning limited recommender")
|
| 482 |
+
return recommender
|
| 483 |
+
|
| 484 |
if model_source == "latest":
|
| 485 |
# Try to get latest MLflow run
|
| 486 |
try:
|
| 487 |
experiment = mlflow.get_experiment_by_name('dlrm-book-recommendation-book_recommender')
|
| 488 |
if experiment:
|
| 489 |
+
runs = mlflow.search_runs(experiment_ids=[experiment.experiment_id],
|
| 490 |
order_by=["start_time desc"], max_results=1)
|
| 491 |
if len(runs) > 0:
|
| 492 |
latest_run_id = runs.iloc[0].run_id
|
| 493 |
recommender = DLRMBookRecommender(run_id=latest_run_id)
|
| 494 |
return recommender
|
| 495 |
+
except Exception as e:
|
| 496 |
+
print(f"⚠️ Error loading from MLflow: {e}")
|
| 497 |
|
| 498 |
elif model_source == "file":
|
| 499 |
# Try to load from local file
|
| 500 |
+
for filename in [
|
| 501 |
+
'/home/mr-behdadi/PROJECT/ICE/notebooks/dlrm_book_model_final.pth',
|
| 502 |
+
'/home/mr-behdadi/PROJECT/ICE/notebooks/dlrm_book_model_epoch_2.pth',
|
| 503 |
+
'/home/mr-behdadi/PROJECT/ICE/notebooks/dlrm_book_model_epoch_0.pth',
|
| 504 |
+
'/home/mr-behdadi/PROJECT/ICE/notebooks/dlrm_book_model_epoch_1.pth']:
|
| 505 |
if os.path.exists(filename):
|
| 506 |
+
try:
|
| 507 |
+
recommender = DLRMBookRecommender(model_path=filename)
|
| 508 |
+
return recommender
|
| 509 |
+
except Exception as e:
|
| 510 |
+
print(f"⚠️ Error loading from {filename}: {e}")
|
| 511 |
|
| 512 |
else:
|
| 513 |
# Treat as run_id
|
| 514 |
+
try:
|
| 515 |
+
recommender = DLRMBookRecommender(run_id=model_source)
|
| 516 |
+
return recommender
|
| 517 |
+
except Exception as e:
|
| 518 |
+
print(f"⚠️ Error loading from run_id {model_source}: {e}")
|
| 519 |
|
| 520 |
print("⚠️ Could not load any trained model")
|
| 521 |
return recommender
|