romio_explore_ai_api / model /online_learner.py
marcolouis's picture
chore: Add Python version file and format code in online learner
86ec101
Raw History Blame Contribute Delete
11.7 kB
"""
Online Learning Implementation for Romio
Updates the recommendation model immediately after users interact.
This implements TRUE online learning:
- Model updates in near real-time
- Uses replay buffer to avoid instability
- Similar to how TikTok/Instagram adapt to your behavior instantly
"""
import torch
import torch.nn as nn
import numpy as np
from collections import deque
from typing import Dict, List, Any
import json
from datetime import datetime
class ExperienceReplayBuffer:
"""
Stores recent user interactions so the model learns from a *small batch*
instead of a single noisy example.
Why this is needed:
- If you update the model on every individual action β†’ unstable learning.
- Replay buffer ensures each update is more "balanced" and safer.
Think of it like reviewing the last few lessons before learning the next one.
"""
def __init__(self, max_size: int = 1000):
self.buffer = deque(maxlen=max_size) # Automatically removes oldest item
self.max_size = max_size
def add(self, interaction: Dict[str, Any]):
"""Store one new interaction in the buffer."""
self.buffer.append(interaction)
def sample(self, batch_size: int = 32) -> List[Dict[str, Any]]:
"""
Randomly sample a batch for training.
If buffer has fewer than batch_size, return everything we have.
"""
if len(self.buffer) < batch_size:
return list(self.buffer)
indices = np.random.choice(len(self.buffer), batch_size, replace=False)
return [self.buffer[i] for i in indices]
def size(self) -> int:
"""Get current number of stored interactions."""
return len(self.buffer)
class OnlineLearner:
"""
Main class that handles real-time model updates.
Workflow:
1. User interacts β†’ system logs that action
2. Store interaction in experience replay buffer
3. Every N interactions β†’ train model on a small batch
4. Model becomes smarter over time
This is modern recommender training: incremental and personalized.
"""
def __init__(
self,
model: nn.Module,
feature_extractor,
device: str = "cuda" if torch.cuda.is_available() else "cpu",
learning_rate: float = 0.0001,
batch_size: int = 32,
update_frequency: int = 10, # Update model every N user actions
):
self.model = model
self.feature_extractor = feature_extractor
self.device = device
# Online training parameters
self.base_learning_rate = learning_rate
self.batch_size = batch_size
self.update_frequency = update_frequency
# Replay buffer for stable updates
self.replay_buffer = ExperienceReplayBuffer(max_size=1000)
# Optimizer for incremental training
self.optimizer = torch.optim.Adam(
self.model.parameters(), lr=self.base_learning_rate
)
# Loss function for score prediction
self.criterion = nn.MSELoss()
# Stats for monitoring learning
self.n_updates = 0
self.n_interactions = 0
self.update_losses = []
print(f"[INFO] Online learner initialized")
print(f" - Device: {device}")
print(f" - Learning rate: {learning_rate}")
print(f" - Batch size: {batch_size}")
print(f" - Update frequency: every {update_frequency} interactions")
def add_interaction(
self,
interaction: Dict[str, Any],
plan_data: Dict[str, Any],
user_history: List[Dict[str, Any]],
plan_embeddings: Dict[str, torch.Tensor],
) -> Dict[str, Any]:
"""
Add a new interaction and optionally trigger a model update.
Args:
interaction: What the user just did (view, bookmark, rate...)
plan_data: Full info about the plan involved
user_history: Past user interactions (sequence)
plan_embeddings: Precomputed embeddings for plans
Returns:
Status dict with metadata on update/no-update
"""
self.n_interactions += 1
# Store interaction in the replay buffer
self.replay_buffer.add(
{
"interaction": interaction,
"plan_data": plan_data,
"user_history": user_history,
"timestamp": datetime.now().isoformat(),
}
)
# Decide whether to update model now
should_update = self.n_interactions % self.update_frequency == 0
if should_update and self.replay_buffer.size() >= self.batch_size:
# Perform one mini-batch SGD update
loss = self._update_model(plan_embeddings)
return {
"updated": True,
"n_updates": self.n_updates,
"n_interactions": self.n_interactions,
"buffer_size": self.replay_buffer.size(),
"loss": loss,
"message": f"Model updated! (Update #{self.n_updates})",
}
return {
"updated": False,
"n_interactions": self.n_interactions,
"buffer_size": self.replay_buffer.size(),
"next_update_in": self.update_frequency
- (self.n_interactions % self.update_frequency),
"message": "Interaction added to buffer",
}
def _update_model(self, plan_embeddings: Dict[str, torch.Tensor]) -> float:
"""
Performs one training step using a batch from replay buffer.
This is the core of online learning:
- Sample small batch
- Build tensors
- Forward pass β†’ compute loss
- Backward pass β†’ adjust weights
"""
batch = self.replay_buffer.sample(self.batch_size)
# Lists to collect training tensors
plan_interests_batch = []
plan_numerical_batch = []
user_sequences_batch = []
labels_batch = []
for item in batch:
interaction = item["interaction"]
plan_data = item["plan_data"]
user_history = item["user_history"]
try:
# Extract plan features β†’ tensors
interest_ids, numerical_features = (
self.feature_extractor.extract_plan_features(plan_data)
)
# Extract user sequence β†’ tensor
user_sequence = (
self.feature_extractor.extract_user_interaction_sequence(
user_history, plan_embeddings
)
)
# Label representing how much the user liked the plan
label = self._extract_label(interaction)
# Append everything
plan_interests_batch.append(interest_ids)
plan_numerical_batch.append(numerical_features)
user_sequences_batch.append(user_sequence)
labels_batch.append(label)
except Exception as e:
print(f"[WARN] Failed to process interaction: {e}")
continue
if not labels_batch:
print("[WARN] No usable samples in this batch – skipping update.")
return 0.0
# Convert Python lists β†’ tensors on device
plan_interests = torch.stack(plan_interests_batch).to(self.device)
plan_numerical = torch.stack(plan_numerical_batch).to(self.device)
user_sequences = torch.stack(user_sequences_batch).to(self.device)
labels = torch.tensor(labels_batch, dtype=torch.float32).to(self.device)
# Begin training step
self.model.train()
self.optimizer.zero_grad()
# Forward pass β†’ predicted scores
predictions = self.model(plan_interests, plan_numerical, user_sequences)
# Loss = MSE between prediction and true label
loss = self.criterion(predictions, labels)
# Backpropagation
loss.backward()
# Clip gradients (prevents exploding gradients)
torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=1.0)
# Apply weight update
self.optimizer.step()
# Record statistics
self.n_updates += 1
loss_value = loss.item()
self.update_losses.append(loss_value)
self.model.eval()
print(
f"[ONLINE UPDATE #{self.n_updates}] Loss: {loss_value:.4f} | Buffer size: {self.replay_buffer.size()}"
)
return loss_value
def _extract_label(self, interaction: Dict[str, Any]) -> float:
"""
Converts raw interaction into a numeric learning target.
We treat different user actions as implicit "ratings":
- Rating β†’ exact numeric score
- Bookmark β†’ strong positive signal
- Longer viewing β†’ user liked it more
"""
interaction_type = interaction.get("interaction_type", "view")
if interaction_type == "rate":
return float(interaction.get("rating", 3.0))
elif interaction_type == "bookmark":
return 4.5
elif interaction_type == "view":
duration = interaction.get("duration_seconds", 0)
if duration < 10:
return 2.0
elif duration < 30:
return 3.0
elif duration < 60:
return 4.0
else:
return 4.5
return 3.0 # Default neutral label
def get_statistics(self) -> Dict[str, Any]:
"""Return stats for monitoring online learning performance."""
avg_loss = np.mean(self.update_losses[-10:]) if self.update_losses else 0.0
return {
"n_interactions": self.n_interactions,
"n_updates": self.n_updates,
"buffer_size": self.replay_buffer.size(),
"avg_recent_loss": avg_loss,
"update_frequency": self.update_frequency,
"learning_rate": self.base_learning_rate,
}
def save_state(self, path: str):
"""Save online learner's current internal state to disk."""
state = {
"n_updates": self.n_updates,
"n_interactions": self.n_interactions,
"update_losses": self.update_losses,
"optimizer_state": self.optimizer.state_dict(),
}
torch.save(state, path)
print(f"[INFO] Saved online learner state to {path}")
def load_state(self, path: str):
"""Load online learning state (useful for server restarts)."""
try:
state = torch.load(path, map_location=self.device, weights_only=False)
self.n_updates = state.get("n_updates", 0)
self.n_interactions = state.get("n_interactions", 0)
self.update_losses = state.get("update_losses", [])
self.optimizer.load_state_dict(state["optimizer_state"])
print(f"[INFO] Loaded online learner state from {path}")
except Exception as e:
print(f"[WARN] Could not load online learner state: {e}")
# Demo usage
if __name__ == "__main__":
print("=" * 60)
print("ONLINE LEARNING DEMONSTRATION")
print("=" * 60)
from model.neural_models import CompleteRecommenderModel
from model.feature_extractor import FeatureExtractor
# Build model + extractor
model = CompleteRecommenderModel(n_interests=12, n_categories=50)
feature_extractor = FeatureExtractor()
# Create online learner
online_learner = OnlineLearner(
model=model,
feature_extractor=feature_extractor,
update_frequency=10,
)
print("\nOnline learning initialized and ready.")