| import random |
| from collections import defaultdict |
|
|
| import numpy as np |
| import scipy.sparse as sp |
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
|
|
| from base.graph_recommender import GraphRecommender |
| from base.torch_interface import TorchGraphInterface |
| from util.conf import OptionConf |
| from util.loss_torch import InfoNCE_FRGCF |
| from util.loss_torch import InfoNCE |
|
|
|
|
| class FRGCF(GraphRecommender): |
| """ |
| Feedback Reciprocal Graph Collaborative Filtering (FRGCF) |
| |
| Notes for this version: |
| - Keep the paper-consistent Joint(A_IF, A_IU) definition. |
| - Do NOT materialize the whole Joint sparse tensor on GPU. |
| - Compute Eq.(13) only for the current batch nodes by row-chunk slicing: |
| E_imp_batch = Joint[batch_nodes, :] @ E0 |
| This is mathematically equivalent to first computing Joint @ E0 on the |
| whole graph and then selecting the same rows, while using much less GPU memory. |
| """ |
|
|
| def __init__(self, conf, training_set, test_set): |
| super(FRGCF, self).__init__(conf, training_set, test_set) |
|
|
| args = OptionConf(self.config['FRGCF']) |
| self.n_layers = int(args['-n_layer']) |
| self.temp = float(args['-temp']) |
| self.lambda_1 = float(args['-lambda1']) |
| self.lambda_2 = float(args['-lambda2']) |
| self.lambda_3 = float(args['-lambda3']) |
| self.mu = float(args['-mu']) |
| self.cluster_num = int(args['-cluster_num']) |
| self.rating_threshold = float(args['-rating_threshold']) if args.contain('-rating_threshold') else 4.0 |
| self.partition_mode = args['-partition_mode'] if args.contain('-partition_mode') else 'standard' |
| self.seed = int(args['-seed']) if args.contain('-seed') else 2026 |
| self.decay = 1e-4 |
| self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
|
|
| random.seed(self.seed) |
| np.random.seed(self.seed) |
| torch.manual_seed(self.seed) |
| if torch.cuda.is_available(): |
| torch.cuda.manual_seed_all(self.seed) |
|
|
| |
| self.if_edges, self.iu_edges = self._split_feedback_edges(training_set) |
| self.if_user_pos = self._build_user_pos_dict(self.if_edges) |
| self.iu_user_pos = self._build_user_pos_dict(self.iu_edges) |
|
|
| self.norm_adj_if, self.norm_adj_iu = self._build_partition_norm_adj(self.if_edges, self.iu_edges) |
| self.joint_if_iu = self._build_joint_matrix(self.norm_adj_if, self.norm_adj_iu).tocsr() |
|
|
| self.encoder_if = FRGCFEncoder( |
| user_num=self.data.user_num, |
| item_num=self.data.item_num, |
| emb_size=self.emb_size, |
| n_layers=self.n_layers, |
| norm_adj=self.norm_adj_if, |
| ) |
| self.encoder_iu = FRGCFEncoder( |
| user_num=self.data.user_num, |
| item_num=self.data.item_num, |
| emb_size=self.emb_size, |
| n_layers=self.n_layers, |
| norm_adj=self.norm_adj_iu, |
| ) |
|
|
| self.best_user_emb = None |
| self.best_item_emb = None |
|
|
| |
| |
| |
| def _split_feedback_edges(self, training_set): |
| """ |
| Split raw interactions into IF and IU by rating threshold. |
| Expected record format in Douban / ml-1M style: |
| [user, item, rating] |
| """ |
| if_edges, iu_edges = [], [] |
| for rec in training_set: |
| u_raw, i_raw, rating = self._parse_record(rec) |
| u = self._resolve_user_index(u_raw) |
| i = self._resolve_item_index(i_raw) |
| if u is None or i is None: |
| continue |
|
|
| rating = float(rating) |
| if self.partition_mode == 'douban_45_proxy': |
| if rating >= 5.0: |
| if_edges.append((u, i, rating)) |
| elif rating >= 4.0: |
| iu_edges.append((u, i, rating)) |
| else: |
| continue |
| else: |
| if rating >= self.rating_threshold: |
| if_edges.append((u, i, rating)) |
| else: |
| iu_edges.append((u, i, rating)) |
|
|
| if len(if_edges) == 0 or len(iu_edges) == 0: |
| raise ValueError( |
| "FRGCF requires both IF and IU interactions. " |
| "Please check whether the dataset contains ratings and whether " |
| "the threshold produces two non-empty partitions." |
| ) |
| return if_edges, iu_edges |
|
|
| def _parse_record(self, rec): |
| if isinstance(rec, (list, tuple)): |
| if len(rec) >= 3: |
| return rec[0], rec[1], rec[2] |
| raise ValueError(f"Training record must have at least 3 fields, got: {rec}") |
| raise TypeError(f"Unsupported training record type: {type(rec)}") |
|
|
| def _resolve_user_index(self, u_raw): |
| if isinstance(u_raw, (int, np.integer)) and 0 <= int(u_raw) < self.data.user_num: |
| return int(u_raw) |
| if hasattr(self.data, 'user') and u_raw in self.data.user: |
| return self.data.user[u_raw] |
| if hasattr(self.data, 'user_id') and u_raw in self.data.user_id: |
| return self.data.user_id[u_raw] |
| try: |
| u = int(u_raw) |
| if 0 <= u < self.data.user_num: |
| return u |
| except Exception: |
| pass |
| return None |
|
|
| def _resolve_item_index(self, i_raw): |
| if isinstance(i_raw, (int, np.integer)) and 0 <= int(i_raw) < self.data.item_num: |
| return int(i_raw) |
| if hasattr(self.data, 'item') and i_raw in self.data.item: |
| return self.data.item[i_raw] |
| if hasattr(self.data, 'item_id') and i_raw in self.data.item_id: |
| return self.data.item_id[i_raw] |
| try: |
| i = int(i_raw) |
| if 0 <= i < self.data.item_num: |
| return i |
| except Exception: |
| pass |
| return None |
|
|
| def _build_user_pos_dict(self, edges): |
| user_pos = defaultdict(set) |
| for u, i, _ in edges: |
| user_pos[u].add(i) |
| return user_pos |
|
|
| def _build_partition_norm_adj(self, if_edges, iu_edges): |
| user_num, item_num = self.data.user_num, self.data.item_num |
| norm_if = self._edges_to_norm_adj(if_edges, user_num, item_num) |
| norm_iu = self._edges_to_norm_adj(iu_edges, user_num, item_num) |
| return norm_if, norm_iu |
|
|
| def _edges_to_norm_adj(self, edges, user_num, item_num): |
| rows, cols, vals = [], [], [] |
| for u, i, _ in edges: |
| rows.append(u) |
| cols.append(i) |
| vals.append(1.0) |
|
|
| r = sp.coo_matrix((vals, (rows, cols)), shape=(user_num, item_num), dtype=np.float32) |
| upper_left = sp.csr_matrix((user_num, user_num), dtype=np.float32) |
| lower_right = sp.csr_matrix((item_num, item_num), dtype=np.float32) |
| a = sp.vstack([ |
| sp.hstack([upper_left, r], format='csr'), |
| sp.hstack([r.T, lower_right], format='csr') |
| ], format='csr') |
|
|
| deg = np.array(a.sum(axis=1)).flatten() |
| deg[deg == 0.0] = 1.0 |
| deg_inv_sqrt = np.power(deg, -0.5) |
| d_inv_sqrt = sp.diags(deg_inv_sqrt) |
| norm_adj = d_inv_sqrt.dot(a).dot(d_inv_sqrt).tocsr() |
| return norm_adj |
|
|
| def _build_joint_matrix(self, norm_adj_if, norm_adj_iu): |
| """ |
| Equation (12) in the paper: |
| Joint(A_IF, A_IU) = (sum_{k=0}^2 A_IF^k) * (sum_{k=0}^2 A_IU^k) |
| """ |
| n = norm_adj_if.shape[0] |
| eye = sp.eye(n, dtype=np.float32, format='csr') |
| sum_if = eye + norm_adj_if + norm_adj_if.dot(norm_adj_if) |
| sum_iu = eye + norm_adj_iu + norm_adj_iu.dot(norm_adj_iu) |
| joint = sum_if.dot(sum_iu).tocsr() |
| return joint |
|
|
| |
| |
| |
| def train(self): |
| self.encoder_if = self.encoder_if.to(self.device) |
| self.encoder_iu = self.encoder_iu.to(self.device) |
|
|
| optimizer = torch.optim.Adam( |
| list(self.encoder_if.parameters()) + list(self.encoder_iu.parameters()), |
| lr=self.lRate |
| ) |
|
|
| steps_per_epoch = max( |
| int(np.ceil(len(self.if_edges) / self.batch_size)), |
| int(np.ceil(len(self.iu_edges) / self.batch_size)) |
| ) |
|
|
| for epoch in range(self.maxEpoch): |
| self.encoder_if.train() |
| self.encoder_iu.train() |
|
|
| epoch_loss = 0.0 |
| for _ in range(steps_per_epoch): |
| batch_if = self._sample_pairwise_batch(self.if_user_pos, self.batch_size) |
| batch_iu = self._sample_pairwise_batch(self.iu_user_pos, self.batch_size) |
|
|
| out_if = self.encoder_if() |
| out_iu = self.encoder_iu() |
|
|
| bpr_if = self._bpr_branch_loss(out_if['user_final'], out_if['item_final'], batch_if) |
| bpr_iu = self._bpr_branch_loss(out_iu['user_final'], out_iu['item_final'], batch_iu) |
|
|
| frcl_loss = self._feedback_reciprocal_contrastive_loss(out_if, out_iu, batch_if, batch_iu) |
| macro_loss = self._macro_feedback_modeling_loss(out_if, out_iu, batch_if, batch_iu) |
| dis_loss = self._distance_regularization(out_if['V'], out_iu['V']) |
|
|
| reg_loss = self._l2_regularization(out_if, out_iu, batch_if, batch_iu) |
|
|
| loss = ( |
| bpr_if |
| + bpr_iu |
| + self.lambda_1 * frcl_loss |
| + self.lambda_2 * macro_loss |
| + self.lambda_3 * dis_loss |
| + reg_loss |
| ) |
|
|
| optimizer.zero_grad() |
| loss.backward() |
| optimizer.step() |
| epoch_loss += loss.item() |
|
|
| with torch.no_grad(): |
| self.encoder_if.eval() |
| final_if = self.encoder_if() |
| self.user_emb = final_if['user_final'] |
| self.item_emb = final_if['item_final'] |
|
|
| self.fast_evaluation(epoch) |
|
|
| self.user_emb, self.item_emb = self.best_user_emb, self.best_item_emb |
|
|
| def _sample_pairwise_batch(self, user_pos_dict, batch_size): |
| users = list(user_pos_dict.keys()) |
| sampled_users = random.choices(users, k=batch_size) |
| pos_items, neg_items = [], [] |
|
|
| for u in sampled_users: |
| pos = random.choice(list(user_pos_dict[u])) |
| neg = random.randint(0, self.data.item_num - 1) |
| while neg in user_pos_dict[u]: |
| neg = random.randint(0, self.data.item_num - 1) |
| pos_items.append(pos) |
| neg_items.append(neg) |
|
|
| users = torch.tensor(sampled_users, dtype=torch.long, device=self.device) |
| pos_items = torch.tensor(pos_items, dtype=torch.long, device=self.device) |
| neg_items = torch.tensor(neg_items, dtype=torch.long, device=self.device) |
| return users, pos_items, neg_items |
|
|
| def _bpr_branch_loss(self, user_emb, item_emb, batch): |
| users, pos_items, neg_items = batch |
| u = user_emb[users] |
| i = item_emb[pos_items] |
| j = item_emb[neg_items] |
| pos_scores = torch.sum(u * i, dim=1) |
| neg_scores = torch.sum(u * j, dim=1) |
| return -torch.mean(F.logsigmoid(pos_scores - neg_scores)) |
|
|
| |
| |
| |
| def _feedback_reciprocal_contrastive_loss(self, out_if, out_iu, batch_if, batch_iu): |
| """ |
| Exact-memory-friendly FRCL. |
| |
| Original full-graph form: |
| E_imp = Joint @ E0 |
| then select batch users/items for InfoNCE_FRGCF |
| |
| This implementation computes only the required rows: |
| E_imp_batch = Joint[batch_nodes, :] @ E0 |
| |
| Because matrix multiplication is row-separable, this is mathematically |
| equivalent to full-graph computation followed by row selection, while |
| avoiding materializing the whole Joint tensor on GPU. |
| """ |
| users = torch.unique(torch.cat([batch_if[0], batch_iu[0]], dim=0)) |
| items = torch.unique(torch.cat([batch_if[1], batch_iu[1]], dim=0)) |
|
|
| |
| item_nodes = items + self.data.user_num |
| batch_nodes = torch.unique(torch.cat([users, item_nodes], dim=0)) |
|
|
| |
| e_imp_if_batch = self._joint_left_multiply_rows(batch_nodes, out_if['E0']) |
| e_imp_iu_batch = self._joint_left_multiply_rows(batch_nodes, out_iu['E0']) |
|
|
| |
| is_user = batch_nodes < self.data.user_num |
| user_pos = torch.nonzero(is_user, as_tuple=False).squeeze(1) |
| item_pos = torch.nonzero(~is_user, as_tuple=False).squeeze(1) |
|
|
| u_imp_if = e_imp_if_batch[user_pos] |
| u_imp_iu = e_imp_iu_batch[user_pos] |
| i_imp_if = e_imp_if_batch[item_pos] |
| i_imp_iu = e_imp_iu_batch[item_pos] |
|
|
| user_loss = InfoNCE_FRGCF(u_imp_if, u_imp_iu, self.temp) |
| item_loss = InfoNCE_FRGCF(i_imp_if, i_imp_iu, self.temp) |
| return user_loss + item_loss |
|
|
| def _joint_left_multiply_rows(self, row_idx, dense_rhs): |
| """ |
| Compute Joint[row_idx, :] @ dense_rhs exactly. |
| |
| row_idx: 1-D torch.LongTensor on any device, with ids in [0, M+N) |
| dense_rhs: torch.Tensor of shape (M+N, d) on self.device |
| |
| Returns: |
| torch.Tensor of shape (len(row_idx), d) on self.device |
| """ |
| |
| row_idx_cpu = row_idx.detach().cpu().numpy().astype(np.int64) |
| joint_rows = self.joint_if_iu[row_idx_cpu, :] |
|
|
| |
| joint_rows_tensor = TorchGraphInterface.convert_sparse_mat_to_tensor(joint_rows).to(self.device) |
|
|
| |
| return torch.sparse.mm(joint_rows_tensor, dense_rhs) |
|
|
| |
| |
| |
| def _macro_feedback_modeling_loss(self, out_if, out_iu, batch_if, batch_iu): |
| macro_if = self._build_macro_embeddings(out_if) |
| macro_iu = self._build_macro_embeddings(out_iu) |
|
|
| users = torch.unique(torch.cat([batch_if[0], batch_iu[0]], dim=0)) |
| items = torch.unique(torch.cat([batch_if[1], batch_iu[1]], dim=0)) |
|
|
| eK_if_u = out_if['user_last'][users] |
| eK_if_i = out_if['item_last'][items] |
| eK_iu_u = out_iu['user_last'][users] |
| eK_iu_i = out_iu['item_last'][items] |
|
|
| macro_if_u = macro_if['user_macro'][users] |
| macro_if_i = macro_if['item_macro'][items] |
| macro_iu_u = macro_iu['user_macro'][users] |
| macro_iu_i = macro_iu['item_macro'][items] |
|
|
| l_if = InfoNCE(eK_if_u, macro_if_u, self.temp) + self.mu * InfoNCE(eK_if_i, macro_if_i, self.temp) |
| l_iu = InfoNCE(eK_iu_u, macro_iu_u, self.temp) + self.mu * InfoNCE(eK_iu_i, macro_iu_i, self.temp) |
| return l_if + l_iu |
|
|
| def _build_macro_embeddings(self, out): |
| e0_user = out['user_e0'] |
| e0_item = out['item_e0'] |
| V = out['V'] |
|
|
| c_user = self._kmeans_centroids(e0_user, self.cluster_num) |
| c_item = self._kmeans_centroids(e0_item, self.cluster_num) |
| C = torch.cat([c_user, c_item], dim=0) |
|
|
| H = torch.matmul(V, C.t()) |
| W = H / (torch.norm(H, dim=1, keepdim=True) + 1e-12) |
| e_macro = out['E0'] + torch.matmul(W, C) / C.shape[0] |
|
|
| user_macro, item_macro = torch.split(e_macro, [self.data.user_num, self.data.item_num], dim=0) |
| return { |
| 'user_macro': user_macro, |
| 'item_macro': item_macro, |
| } |
|
|
| def _kmeans_centroids(self, embeddings, n_clusters): |
| from sklearn.cluster import KMeans |
|
|
| x = embeddings.detach().cpu().numpy() |
| n_clusters = min(n_clusters, x.shape[0]) |
| if n_clusters <= 1: |
| centroid = np.mean(x, axis=0, keepdims=True) |
| return torch.tensor(centroid, dtype=embeddings.dtype, device=embeddings.device) |
|
|
| model = KMeans(n_clusters=n_clusters, random_state=self.seed, n_init=10) |
| model.fit(x) |
| centers = torch.tensor(model.cluster_centers_, dtype=embeddings.dtype, device=embeddings.device) |
| return centers |
|
|
| def _distance_regularization(self, V_if, V_iu): |
| return -self._jsd(V_if, V_iu) |
|
|
| def _jsd(self, p_logits, q_logits): |
| p = F.softmax(p_logits, dim=-1) |
| q = F.softmax(q_logits, dim=-1) |
| m = 0.5 * (p + q) |
| kl_pm = torch.sum(p * (torch.log(p + 1e-12) - torch.log(m + 1e-12)), dim=-1) |
| kl_qm = torch.sum(q * (torch.log(q + 1e-12) - torch.log(m + 1e-12)), dim=-1) |
| return 0.5 * (kl_pm.mean() + kl_qm.mean()) |
|
|
| def _l2_regularization(self, out_if, out_iu, batch_if, batch_iu): |
| users_if, pos_if, neg_if = batch_if |
| users_iu, pos_iu, neg_iu = batch_iu |
|
|
| reg = 0.0 |
| reg += torch.norm(out_if['user_e0'][users_if]) ** 2 |
| reg += torch.norm(out_if['item_e0'][pos_if]) ** 2 |
| reg += torch.norm(out_if['item_e0'][neg_if]) ** 2 |
|
|
| reg += torch.norm(out_iu['user_e0'][users_iu]) ** 2 |
| reg += torch.norm(out_iu['item_e0'][pos_iu]) ** 2 |
| reg += torch.norm(out_iu['item_e0'][neg_iu]) ** 2 |
|
|
| return self.reg * self.decay * reg / (2.0 * self.batch_size) |
|
|
| def save(self): |
| with torch.no_grad(): |
| self.encoder_if.eval() |
| final_if = self.encoder_if() |
| self.best_user_emb = final_if['user_final'] |
| self.best_item_emb = final_if['item_final'] |
|
|
| def predict(self, u): |
| |
| u = self.data.get_user_id(u) |
| score = torch.matmul(self.user_emb[u], self.item_emb.transpose(0, 1)) |
| return score.detach().cpu().numpy() |
|
|
|
|
| class FRGCFEncoder(nn.Module): |
| def __init__(self, user_num, item_num, emb_size, n_layers, norm_adj): |
| super(FRGCFEncoder, self).__init__() |
| self.user_num = user_num |
| self.item_num = item_num |
| self.emb_size = emb_size |
| self.n_layers = n_layers |
| self.norm_adj = norm_adj |
|
|
| self.embedding_dict = self._init_model() |
| self.sparse_norm_adj = None |
|
|
| def _init_model(self): |
| initializer = nn.init.xavier_uniform_ |
| return nn.ParameterDict({ |
| 'user_emb': nn.Parameter(initializer(torch.empty(self.user_num, self.emb_size))), |
| 'item_emb': nn.Parameter(initializer(torch.empty(self.item_num, self.emb_size))), |
| }) |
|
|
| def _get_sparse_adj(self, device): |
| if self.sparse_norm_adj is None: |
| self.sparse_norm_adj = TorchGraphInterface.convert_sparse_mat_to_tensor(self.norm_adj) |
| return self.sparse_norm_adj.to(device) |
|
|
| def forward(self): |
| device = self.embedding_dict['user_emb'].device |
| sparse_adj = self._get_sparse_adj(device) |
|
|
| e0 = torch.cat([self.embedding_dict['user_emb'], self.embedding_dict['item_emb']], dim=0) |
| layer_outputs = [e0] |
|
|
| ego = e0 |
| for _ in range(self.n_layers): |
| ego = torch.sparse.mm(sparse_adj, ego) |
| layer_outputs.append(ego) |
|
|
| last = layer_outputs[-1] |
| if self.n_layers > 0: |
| all_propagated = torch.stack(layer_outputs[1:], dim=1) |
| final = torch.mean(all_propagated, dim=1) |
| diffs = [] |
| for i in range(self.n_layers): |
| diffs.append(layer_outputs[i + 1] - layer_outputs[i]) |
| V = torch.stack(diffs, dim=1).mean(dim=1) |
| else: |
| final = e0 |
| V = torch.zeros_like(e0) |
|
|
| user_final, item_final = torch.split(final, [self.user_num, self.item_num], dim=0) |
| user_e0, item_e0 = torch.split(e0, [self.user_num, self.item_num], dim=0) |
| user_last, item_last = torch.split(last, [self.user_num, self.item_num], dim=0) |
|
|
| return { |
| 'E0': e0, |
| 'E_last': last, |
| 'V': V, |
| 'user_final': user_final, |
| 'item_final': item_final, |
| 'user_e0': user_e0, |
| 'item_e0': item_e0, |
| 'user_last': user_last, |
| 'item_last': item_last, |
| } |
|
|