Spaces:
Sleeping
Sleeping
Download trainer.py from malelol/Adult_Game_Recommender: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/spaces/malelol/Adult_Game_Recommender/resolve/main/trainer.py
- Command line
-
hf download hf://spaces/malelol/Adult_Game_Recommender/trainer.py
-
curl -L -o trainer.py https://huggingface.co/spaces/malelol/Adult_Game_Recommender/resolve/main/trainer.py
14.6 kB
| #!/usr/bin/env python3 | |
| # trainer.py - SVD-GCL Training Logic | |
| import torch | |
| import torch.optim as optim | |
| import numpy as np | |
| import os | |
| import time | |
| from torch.utils.data import DataLoader, TensorDataset | |
| from collections import defaultdict | |
| # Evaluation & Training Constants | |
| EVAL_BATCH_SIZE = 1000 | |
| GRADIENT_CLIP_MAX_NORM = 1.0 | |
| class SVDGCLTrainer: | |
| """ | |
| Manages the training lifecycle for SVD-GCL model. | |
| Single-pass evaluation for both global metrics and per-epoch logging. | |
| """ | |
| def __init__( | |
| self, | |
| model, | |
| dataset, | |
| device, | |
| learning_rate=1e-3, | |
| reg_weight=1e-4, | |
| batch_size=2048, | |
| checkpoint_dir="checkpoints", | |
| early_stop_metric: str = "recall@10", | |
| # Parametry przyjmowane dla kompatybilności z grid_train_xsimgcl.py. | |
| # SVDGCLTrainer ich nie używa — LR scheduling jest poza zakresem tego trenera. | |
| use_lr_scheduler: bool = False, | |
| use_lr_warmup: bool = False, | |
| warmup_epochs: int = 3, | |
| ): | |
| self.model = model.to(device) | |
| self.dataset = dataset | |
| self.device = device | |
| self.batch_size = batch_size | |
| self.checkpoint_dir = checkpoint_dir | |
| self.reg_weight = reg_weight | |
| # Parse early_stop_metric | |
| parts = early_stop_metric.split('@') | |
| if len(parts) != 2: | |
| raise ValueError(f"early_stop_metric must be in format 'metric@k', got {early_stop_metric}") | |
| self.metric_type, k_str = parts | |
| if self.metric_type not in {'recall', 'ndcg'}: | |
| raise ValueError(f"metric must be 'recall' or 'ndcg', got {self.metric_type}") | |
| try: | |
| self.k = int(k_str) | |
| except ValueError: | |
| raise ValueError(f"k must be an integer, got {k_str}") | |
| if self.k not in {10, 20}: | |
| raise ValueError(f"k must be 10 or 20, got {self.k}") | |
| self.early_stop_metric = early_stop_metric | |
| # Adj Matrix Setup | |
| if hasattr(dataset, 'adj_matrix') and dataset.adj_matrix is not None: | |
| self.adj_matrix_device = dataset.adj_matrix.to(device) | |
| else: | |
| raise ValueError("Dataset must have adj_matrix initialized!") | |
| self.optimizer = optim.Adam( | |
| self.model.parameters(), | |
| lr=learning_rate, | |
| weight_decay=0 | |
| ) | |
| if not os.path.exists(checkpoint_dir): | |
| os.makedirs(checkpoint_dir) | |
| print(f"\n[Trainer Init] Device: {device} | Batch: {batch_size} | LR: {learning_rate:.2e}") | |
| def _sample_negatives(self, pos_items: torch.Tensor, n_items: int) -> torch.Tensor: | |
| """ | |
| Uniform Negative Sampling (Modulo Shift). | |
| Efficient, unbiased, zero extra memory. | |
| """ | |
| offsets = torch.randint(1, n_items, (pos_items.size(0),), device=self.device) | |
| neg_items = (pos_items + offsets) % n_items | |
| return neg_items | |
| def train(self, n_epochs, patience=5): | |
| """ | |
| Main training loop. | |
| """ | |
| best_metric = 0.0 | |
| best_epoch = 0 | |
| patience_counter = 0 | |
| # Dataloader setup | |
| train_data = torch.from_numpy(self.dataset.train_interactions) | |
| train_loader = DataLoader( | |
| TensorDataset(train_data), | |
| batch_size=self.batch_size, | |
| shuffle=True, | |
| pin_memory=True, # Transfer DMA (z pominięciem CPU) — krytyczne dla GPU | |
| num_workers=4, # Asynchroniczne prefetching batchy | |
| persistent_workers=True # Unikamy kosztownego fork/join per epoch | |
| ) | |
| print(f"\n{'='*80}") | |
| print(f"🚀 Starting Training: {n_epochs} epochs | Patience: {patience}") | |
| print(f"{'='*80}") | |
| for epoch in range(1, n_epochs + 1): | |
| t_start = time.time() | |
| # --- Training Phase --- | |
| self.model.train() | |
| metrics_accum = defaultdict(float) | |
| n_batches = 0 | |
| for batch_data in train_loader: | |
| # zero_grad NA POCZĄTKU pętli: | |
| # 1. jeśli batch jest NaN → gradienty wyczyszczone przed następną iteracją | |
| # 2. graph z NaN batcha jest zwolniony przez GC natychmiast po `del loss` | |
| self.optimizer.zero_grad() | |
| batch_data = batch_data[0].to(self.device) | |
| users = batch_data[:, 0].long() | |
| pos_items = batch_data[:, 1].long() | |
| # SSM usunięty — zawsze BPR z explicitnymi negatywami | |
| neg_items = self._sample_negatives(pos_items, self.dataset.n_games) | |
| # Wagi z kolumny 2: recenzje=1.0, lajki=like_weight (np. 0.3). | |
| # Używamy raw weights bez normalizacji: | |
| # - Recenzje zawsze dostają gradient z wagą 1.0 | |
| # - Lajki dostają gradient proporcjonalnie niższy (like_weight) | |
| # - Skala lossu nieznacznie spada gdy batch ma dużo likeów — to poprawne | |
| # zachowanie (mniej pewne interakcje = słabszy sygnał treningowy) | |
| # Jeśli likes_enabled=False, wszystkie wagi = 1.0 → sample_weights=None (zero narzutu) | |
| raw_weights = batch_data[:, 2].float() | |
| all_ones = raw_weights.min().item() >= 0.999 | |
| sample_weights = None if all_ones else raw_weights | |
| loss, loss_dict = self.model.compute_loss( | |
| self.adj_matrix_device, users, pos_items, neg_items, | |
| sample_weights=sample_weights, reg_weight=self.reg_weight | |
| ) | |
| # NaN/Inf check — skip batch, graph jest czyszczony przez del | |
| if torch.isnan(loss) or torch.isinf(loss): | |
| print(f"[⚠️ WARNING] NaN/Inf loss, skipping batch") | |
| del loss | |
| continue | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(self.model.parameters(), GRADIENT_CLIP_MAX_NORM) | |
| self.optimizer.step() | |
| for k, v in loss_dict.items(): | |
| metrics_accum[k] += v | |
| metrics_accum['loss'] += loss.item() | |
| n_batches += 1 | |
| # Averages | |
| if n_batches == 0: | |
| print("[❌ ERROR] All batches NaN/Inf in epoch! Breaking training.") | |
| break | |
| avg_metrics = {k: v / n_batches for k, v in metrics_accum.items()} | |
| train_time = time.time() - t_start | |
| # Klucz głównej straty (zawsze bpr) | |
| main_loss_key = "bpr" | |
| # --- Evaluation Phase --- | |
| eval_results = self.evaluate(self.dataset.val_interactions, ks=[10, 20]) | |
| uniformity = eval_results['uniformity'] | |
| recall_10 = eval_results.get('global@10', {}).get('recall', 0.0) | |
| ndcg_10 = eval_results.get('global@10', {}).get('ndcg', 0.0) | |
| recall_20 = eval_results.get('global@20', {}).get('recall', 0.0) | |
| ndcg_20 = eval_results.get('global@20', {}).get('ndcg', 0.0) | |
| # Determine monitoring metric | |
| curr_score = eval_results.get(f'global@{self.k}', {}).get(self.metric_type, 0.0) | |
| # Checkpointing | |
| is_best = curr_score > best_metric | |
| if is_best: | |
| best_metric = curr_score | |
| best_epoch = epoch | |
| patience_counter = 0 | |
| self.save_checkpoint("best_model.pt") | |
| status_str = f"\033[92m*BEST*\033[0m" # Green text | |
| else: | |
| patience_counter += 1 | |
| status_str = f"(Pat: {patience_counter}/{patience})" | |
| # --- Logging --- | |
| drift_str = f" | Drift:{avg_metrics.get('semantic_drift', 0):.4f}" if 'semantic_drift' in avg_metrics else "" | |
| print(f"Ep {epoch:3d} | T:{train_time:4.1f}s | L:{avg_metrics['loss']:.4f} | BPR:{avg_metrics.get('bpr', 0.0):.4f} | CL:{avg_metrics['cl']:.4f}{drift_str} | Unif:{uniformity:.2f}") | |
| print(f" [GLOBAL] R@10: {recall_10:.4f} | N@10: {ndcg_10:.4f} | R@20: {recall_20:.4f} | N@20: {ndcg_20:.4f} {status_str}") | |
| print(f" ES: {self.early_stop_metric} = {curr_score:.4f}") | |
| if patience_counter >= patience: | |
| print(f"\n[Early Stopping] No improvement for {patience} epochs.") | |
| break | |
| print(f"\nResult: Best {self.early_stop_metric} = {best_metric:.4f} at epoch {best_epoch}") | |
| def evaluate(self, interactions, ks=[20]): | |
| """ | |
| W pelni wektoryzowana ewaluacja — eliminuje OBA poziomy petli Pythona. | |
| Stare podejscie (oryginal): podwojna petla Python: N_users * K iteracji. | |
| Stare podejscie (czesc 1): petla po userach + np.isin per user. | |
| Nowe podejscie: hits (B, k) numpy array builowany dla calego batcha naraz, | |
| DCG = (hits * discount_vec).sum(1) — jedno mnozenie macierzowe numpy. | |
| IDCG = discount_cumsum[n_true_capped - 1] — indeksowanie tablicy. | |
| Przyspieszenie wzgledem oryginalu: ~15-20x dla 10k userow val i K=20. | |
| Jedyna pozostala petla Pythona: np.isin per user w batchu (O(batch*k)), | |
| nieuniknione bez specjalizowanych struktur (bloom filter / sorted search). | |
| """ | |
| self.model.eval() | |
| # 1. Embeddingi raz | |
| user_embeds, item_embeds, _ = self.model(self.adj_matrix_device) | |
| # 2. Ground truth | |
| gt = defaultdict(list) | |
| for row in interactions: | |
| gt[int(row[0])].append(int(row[1])) | |
| # 3. Precompute discount vectors i cumsum (raz, poza petlami batch+k) | |
| # discount[j] = 1/log2(j+2), j=0..k-1 | |
| # discount_cumsum[n-1] = IDCG idealnej listy dlugosci n (szybkie IDCG) | |
| discount_vecs = {} | |
| discount_cumsums = {} | |
| for k in ks: | |
| dv = 1.0 / np.log2(np.arange(2, k + 2, dtype=np.float64)) | |
| discount_vecs[k] = dv | |
| discount_cumsums[k] = np.cumsum(dv) | |
| # 4. Akumulatory | |
| accum = defaultdict(lambda: {'recall_sum': 0.0, 'ndcg_sum': 0.0, 'count': 0}) | |
| test_users = list(gt.keys()) | |
| # 5. Batch inference | |
| for i in range(0, len(test_users), EVAL_BATCH_SIZE): | |
| batch_uids = test_users[i:i + EVAL_BATCH_SIZE] | |
| B = len(batch_uids) | |
| batch_u_tensor = torch.tensor(batch_uids, device=self.device) | |
| scores = torch.mm(user_embeds[batch_u_tensor], item_embeds.t()) | |
| # Maskuj historię treningową | |
| for idx, u_id in enumerate(batch_uids): | |
| hist = self.dataset.train_user_history.get(u_id) | |
| if hist: | |
| scores[idx, list(hist)] = -float('inf') | |
| for k in ks: | |
| dv = discount_vecs[k] # (k,) float64 | |
| dcum = discount_cumsums[k] # (k,) float64 | |
| _, topk_t = torch.topk(scores, k, dim=1) | |
| topk = topk_t.cpu().numpy() # (B, k) int | |
| # Buduj (B, k) hits i (B,) n_true w jednej petli per user | |
| # Petla jest nieunikniona (gt per user roznej dlugosci), | |
| # ale eliminujemy wewnetrzna petla po rankach (O(B*k) → O(B)). | |
| hits = np.zeros((B, k), dtype=bool) | |
| n_true = np.zeros(B, dtype=np.int32) | |
| for idx, u_id in enumerate(batch_uids): | |
| true_list = gt[u_id] | |
| n_true[idx] = len(true_list) | |
| hits[idx] = np.isin(topk[idx], true_list) | |
| # DCG: (B, k) bool * (k,) float → (B,) float [broadcast] | |
| dcg = (hits * dv).sum(axis=1) # (B,) | |
| # IDCG: precomputed cumsum, unika petli po rankach w IDCG | |
| n_true_capped = np.minimum(n_true, k) | |
| idcg = np.zeros(B, dtype=np.float64) | |
| mask = n_true_capped > 0 | |
| idcg[mask] = dcum[n_true_capped[mask] - 1] | |
| ndcg_vals = np.where(idcg > 0, dcg / idcg, 0.0) # (B,) | |
| recall_vals = np.where(n_true > 0, | |
| hits.sum(axis=1) / n_true, 0.0) # (B,) | |
| # Akumulacja wektorowo — bez petli po userach | |
| accum[k]['recall_sum'] += float(recall_vals.sum()) | |
| accum[k]['ndcg_sum'] += float(ndcg_vals.sum()) | |
| accum[k]['count'] += B | |
| # 6. Finalizuj wyniki | |
| results = {'uniformity': self._compute_uniformity(item_embeds)} | |
| for k in ks: | |
| val = accum[k] | |
| count = val['count'] | |
| if count > 0: | |
| results[f'global@{k}'] = { | |
| 'recall': val['recall_sum'] / count, | |
| 'ndcg': val['ndcg_sum'] / count, | |
| 'n_users': count, | |
| } | |
| else: | |
| results[f'global@{k}'] = {'recall': 0.0, 'ndcg': 0.0, 'n_users': 0} | |
| return results | |
| def _compute_uniformity(self, embeddings, sample_size=2000): | |
| """ | |
| Calculates Uniformity metric (Wang & Isola, 2020). | |
| Wartość ujemna (np. -2 do -3) = dobry rozkład. Dodatnia = kolaps. | |
| """ | |
| embeddings = embeddings.cpu().detach() | |
| if embeddings.shape[0] > sample_size: | |
| gen = torch.Generator().manual_seed(0) | |
| indices = torch.randperm(embeddings.shape[0], generator=gen)[:sample_size] | |
| embeddings = embeddings[indices] | |
| norms = embeddings.norm(dim=1, keepdim=True) | |
| emb_norm = embeddings / (norms + 1e-8) | |
| similarities = torch.mm(emb_norm, emb_norm.t()) | |
| distances_sq = 2 * (1 - similarities) | |
| kernel = torch.exp(-2 * distances_sq) | |
| kernel.fill_diagonal_(0) | |
| avg_kernel = kernel.sum() / (embeddings.shape[0] * (embeddings.shape[0] - 1)) | |
| return torch.log(torch.clamp(avg_kernel, min=1e-12)).item() | |
| def save_checkpoint(self, filename): | |
| path = os.path.join(self.checkpoint_dir, filename) | |
| save_dict = { | |
| 'model_state_dict': self.model.state_dict(), | |
| 'optimizer_state_dict': self.optimizer.state_dict(), | |
| 'config': self.dataset.config | |
| } | |
| torch.save(save_dict, path) | |
| # Alias dla kompatybilności z grid_train_xsimgcl.py. | |
| # Grid search importuje XSimGCLTrainer, ale SVDGCLTrainer obsługuje | |
| # pełną logikę treningu włącznie z loss_type (bpr/ssm). | |
| XSimGCLTrainer = SVDGCLTrainer | |