Spaces:
Sleeping
Sleeping
File size: 11,720 Bytes
884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 86ec101 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 86ec101 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 86ec101 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 86ec101 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | """
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.")
|