"""hete""" from hete.layers import MLP_generator, PairNorm # External imports from a local 'hete' package, functionality assumed to be MLP and Pair Normalization. import torch # Third-party library for tensor computations and neural networks. import torch.nn as nn # Neural network module from PyTorch. from dgl.nn import GraphConv # Graph Convolutional layer from Deep Graph Library (DGL). import random # Standard Python library for random number generation. import copy # Standard Python library for creating copies of objects. from torch.nn.functional import normalize # Normalization function from PyTorch. import numpy as np # Third-party library for numerical operations, especially array manipulation. def contrastive_loss(projected_emd, v_emd, sampled_embeddings_u, sampled_embeddings_neg_v, tau, lambda_loss): # This function calculates the Graph Asymmetric Contrastive Loss (GraphACL) as described # in Equation (5) of the paper "Simple and Asymmetric Graph Contrastive Learning without Augmentations". # It aims to make the projected online embedding of a central node 'p' (projected_emd) similar to the # target embeddings of its 1-hop neighbors 'u' (sampled_embeddings_u), # while being dissimilar to negative samples 'v_'. The online embedding of the central node 'v' (v_emd) # is used in the denominator for negative pairs. # Calculate the numerator term for positive pairs: exp(p^T * u / tau). # 'projected_emd' corresponds to 'p' in the paper. # 'sampled_embeddings_u' corresponds to 'u' (target embeddings of 1-hop neighbors). # 'tau' is the temperature hyperparameter. # .transpose(-1, -2) prepares for batch matrix multiplication. # .squeeze() removes dimensions of size 1. pos = torch.exp(torch.bmm(projected_emd, sampled_embeddings_u.transpose(-1, -2)).squeeze() / tau) # Calculate the denominator term: log( exp(p^T * u / tau) + sum(exp(v^T * v_ / tau)) ). # 'v_emd' corresponds to 'v' (online embedding of the central node) in the paper's denominator. # 'sampled_embeddings_neg_v' corresponds to 'v_' (online embeddings of negative samples). # The sum is over the negative samples for each central node. neg_score = torch.log( pos + torch.sum(torch.exp(torch.bmm(v_emd, sampled_embeddings_neg_v.transpose(-1, -2)).squeeze() / tau), dim=1).unsqueeze(-1)) # dim=1 sums over negative samples, unsqueeze adds a dim for broadcasting. # Sum the log scores for the denominator part over the positive samples dimension. neg_score = torch.sum(neg_score, dim=1) # Sum the log scores for the numerator part over the positive samples dimension. pos_socre = torch.sum(torch.log(pos), dim=1) # Calculate the total loss based on Equation (5). # Equation (5) is: L_A = -log( exp(p^T*u/tau) / (exp(p^T*u/tau) + sum(exp(v^T*v_/tau))) ) # This can be rewritten as: L_A = log(exp(p^T*u/tau) + sum(exp(v^T*v_/tau))) - log(exp(p^T*u/tau)) # The code implements: sum(lambda_loss * log(pos + sum_neg) - log(pos)) # If lambda_loss = 1, this matches the rewritten form of Equation (5). # The 'lambda_loss' parameter is not explicitly in Equation (5) but might be an # empirical coefficient or a way to balance terms. The paper's ablation study on L_COM # (a combination of prediction and uniformity loss) might relate to this, though L_A is presented as the final objective. total_loss = torch.sum(lambda_loss * neg_score - pos_socre) # Normalize the loss by the batch size and the number of positive samples per node. # This provides an average loss per positive pair. total_loss = total_loss / sampled_embeddings_u.shape[0] / sampled_embeddings_u.shape[1] return total_loss class EMA(): # This class implements the Exponential Moving Average (EMA) utility. # EMA is used in the GraphACL paper to update the parameters of the target encoder (f_xi) # using the parameters of the online encoder (f_theta). # The update rule is: xi <- lambda * xi + (1 - lambda) * theta, where 'lambda' is the decay rate. def __init__(self, beta): # Initializes the EMA updater. # 'beta' corresponds to the decay rate 'lambda' in the paper's EMA update rule. super().__init__() self.beta = beta def update_average(self, old, new): # Performs one step of EMA update for a given parameter. # 'old' is the parameter from the target model (xi). # 'new' is the parameter from the online model (theta). if old is None: # Handles the initial update where the target model might not have parameters yet. return new return old * self.beta + (1 - self.beta) * new def update_moving_average(target_ema_updater, ma_model, current_model): # This function applies the EMA update to all parameters of a target model (ma_model) # using the parameters from an online model (current_model). # It iterates through corresponding parameters of both models and uses the 'target_ema_updater' # (an instance of the EMA class) to perform the update. for current_params, ma_params in zip(current_model.parameters(), ma_model.parameters()): old_weight, up_weight = ma_params.data, current_params.data # Get current data of target and online parameters. ma_params.data = target_ema_updater.update_average(old_weight, up_weight) # Update target parameter data. def set_requires_grad(model, val): # Utility function to set the 'requires_grad' attribute for all parameters in a given model. # In GraphACL, this is used to "freeze" the target encoder, meaning its weights are # updated only via EMA and not through direct backpropagation. for p in model.parameters(): p.requires_grad = val class Model(nn.Module): # This class defines the main GraphACL model structure. # It includes the online encoder (f_theta), the target encoder (f_xi), and the projector (g_phi) # as described in the paper. # The encoders are GNNs, and the projector is an MLP. def __init__(self, in_dim, hidden_dim, layer_num, sample_size, tau, norm_mode="PN-SCS", norm_scale=20, lambda_loss=1, moving_average_decay=0.0, num_MLP=3): # Initializes the GraphACL model components. # 'in_dim': Dimensionality of input node features. # 'hidden_dim': Dimensionality of hidden layers and output embeddings. # 'layer_num': Number of GNN layers. The paper uses a GCN model as the encoder, # and experiments typically use 2-layer GCNs. This parameter seems to control GNN depth. # 'sample_size': Number of neighbors to sample for the loss calculation. # 'tau': Temperature hyperparameter for the contrastive loss. # 'norm_mode', 'norm_scale': Parameters for 'PairNorm'. PairNorm is not explicitly mentioned in the GraphACL # paper's core methodology but might be an auxiliary technique for stabilization or performance, # potentially from the 'hete.layers' import. # 'lambda_loss': Coefficient for the contrastive loss, as discussed in the `contrastive_loss` function. # 'moving_average_decay': Decay rate for the EMA update of the target encoder, corresponds to 'lambda' in paper. # 'num_MLP': Number of layers in the MLP projector (g_phi). super(Model, self).__init__() self.norm = PairNorm(norm_mode, norm_scale) # PairNorm layer, external to core GraphACL logic in paper. self.out_dim = hidden_dim # Output dimension of embeddings. self.lambda_loss = lambda_loss # Coefficient for the loss function. self.tau = tau # Temperature for the loss function. # GNN Encoder (Online Encoder f_theta) # The paper uses GCN as the encoder. This implementation uses two GraphConv layers. # The 'layer_num' parameter is not directly used here to vary GNN depth dynamically in init, # it's fixed at two layers. If layer_num was intended for depth, it's a discrepancy. self.graphconv1 = GraphConv(in_dim, hidden_dim) self.graphconv2 = GraphConv(hidden_dim, hidden_dim) # Target GNN Encoder (f_xi) # Initialized as a deep copy of the online encoder. self.target_graphconv1 = copy.deepcopy(self.graphconv1) self.target_graphconv2 = copy.deepcopy(self.graphconv2) # Freeze target encoder: gradients should not be computed for it. set_requires_grad(self.target_graphconv1, False) set_requires_grad(self.target_graphconv2, False) # EMA updater for the target encoder. self.target_ema_updater = EMA(moving_average_decay) self.num_MLP = num_MLP # Number of layers for the projector. # Projector (g_phi): an MLP that maps online encoder representations. # 'MLP_generator' is an external import, assumed to create an MLP. self.projector = MLP_generator(hidden_dim, hidden_dim, num_MLP) self.in_dim = in_dim # Store input dimension. self.sample_size = sample_size # Store neighbor sample size. def update_moving_average(self): # Method to update the target GNN encoder's parameters using EMA. # The assertion for 'use_momentum' is commented out, implying EMA is always used if a target encoder exists. # assert self.use_momentum, 'you do not need to update the moving average, since you have turned off momentum for the target encoder' assert self.target_graphconv1 or self.target_graphconv2 is not None, 'target encoder has not been created yet' # Update the first layer of the target encoder. update_moving_average(self.target_ema_updater, self.target_graphconv1, self.graphconv1) # Update the second layer of the target encoder. update_moving_average(self.target_ema_updater, self.target_graphconv2, self.graphconv2) def forward_encoder(self, g, h): # This method performs the forward pass through both online and target encoders, and the projector. # 'g': Graph structure (e.g., DGL graph object). # 'h': Input node features for all nodes in the graph. # Online encoder (f_theta): generates online embeddings 'v'. v_emd = self.graphconv2(g, self.graphconv1(g, h)) # Target encoder (f_xi): generates target embeddings 'u'. # These embeddings are L2 normalized as per common practice in contrastive learning, though not explicitly # stated for 'u' before loss in Eq (5), but 'p' and 'u' are L2 normalized in Eq (11) derivation. u_emd = normalize(self.target_graphconv2(g, self.target_graphconv1(g, h)), p=2, dim=-1) # Projector (g_phi): takes online embeddings 'v_emd' and produces projected embeddings 'p'. # These are also L2 normalized. projected_emd = normalize(self.projector(v_emd), p=2, dim=-1) return v_emd, u_emd, projected_emd def get_emb(self, neighbor_indexes, gt_embeddings): # Utility function to sample embeddings for a given list of neighbor indices. # 'neighbor_indexes': A list of node indices to sample from. # 'gt_embeddings': The source tensor of embeddings (e.g., all node embeddings from an encoder). # 'self.sample_size': The desired number of samples. sampled_embeddings = [] if len(neighbor_indexes) < self.sample_size: # If the number of available neighbors is less than sample_size, # take all available neighbors and then resample with replacement from them to reach sample_size. sample_indexes = list(neighbor_indexes) # Ensure it's a list for extend/+= # Discrepancy: np.random.choice might not be ideal if neighbor_indexes is very small (e.g., 1) as it might pick the same index repeatedly. # Also, tolist() is applied to the output of np.random.choice. sample_indexes += np.random.choice(neighbor_indexes, self.sample_size - len(sample_indexes)).tolist() else: # If enough neighbors are available, sample without replacement. sample_indexes = random.sample(neighbor_indexes, self.sample_size) for index in sample_indexes: sampled_embeddings.append(gt_embeddings[index]) return torch.stack(sampled_embeddings) # Stack the list of tensors into a single tensor. # Sample neighbors from neighbor set, if the length of neighbor set less than sample size, then do the padding. def sample_neighbors(self, neighbor_dict, u_emd, v_emd): # This method samples positive and negative embeddings for each node in a batch (implicitly defined by iterating u_emd). # 'neighbor_dict': A dictionary where keys are central node indices and values are lists of their 1-hop neighbor indices. # This is used to sample positive neighbors. # 'u_emd': Target embeddings for all nodes in the graph (source for positive samples 'u'). # 'v_emd': Online embeddings for all nodes in the graph (source for negative samples 'v_'). # It is assumed that u_emd (and thus projected_emd, v_emd in the caller) corresponds to the embeddings for nodes # for which the loss is being computed (the batch). The loop `for index, embedding in enumerate(u_emd)` iterates # through these batch nodes. sampled_embeddings_list = [] # To store positive sampled embeddings for each node in the batch. sampled_embeddings_neg_list = [] # To store negative sampled embeddings for each node in the batch. # The paper states negative samples v_ are from V (all nodes). # The code here iterates `enumerate(u_emd)`. If `u_emd` are batch embeddings, then `index` is a batch-local index. # However, `neighbor_dict[index]` implies `index` must be a global graph node index. # This suggests `u_emd` passed here should be the embeddings of the *batch* nodes, but `neighbor_dict` uses global indices. # Let's assume `u_emd` are embeddings for the current batch of nodes, and `index` is a local batch index. # For `neighbor_dict[index]` to work, `index` would need to be mapped to a global node ID, or `neighbor_dict` # would need to be pre-filtered/remapped for the batch. The current implementation of iterating `enumerate(u_emd)` and # then using that local `index` for `neighbor_dict` seems problematic if `u_emd` represents only a batch of embeddings # and `neighbor_dict` uses global indices. # If `u_emd` refers to *all* node embeddings, then this loop iterates over all nodes to prepare samples, # which is inefficient if loss is calculated per batch. The `contrastive_loss` function expects batch-sized inputs. # Assuming `u_emd` are the batch's target embeddings and `v_emd` are the batch's online embeddings. # For `neighbor_dict[index]` to make sense, if `index` refers to the i-th node *in the batch*, then # `neighbor_dict` should be keyed by these batch indices, or `index` should be the global ID. # The most straightforward interpretation of the code `for index, embedding in enumerate(u_emd)` # is that `u_emd` is a tensor of embeddings for the nodes *in the current processing batch*. # `index` is then the local index within that batch (0 to batch_size-1). # `neighbor_dict` must therefore be structured to accept these local batch indices or, more likely, # the global indices corresponding to these batch nodes must be available to query `neighbor_dict`. # The current code does not show this mapping. # Let's assume `neighbor_dict` is keyed by global node IDs, and `u_emd` here is for the batch, # and `index` needs to be the global ID of the node in the batch. This is a point of ambiguity. # For negative sampling, `range(0, len(neighbor_dict))` implies sampling from all nodes in the graph # (assuming `len(neighbor_dict)` is total number of nodes with specified neighbors). # This aligns with Equation (5) where negative samples v_ are drawn from the entire node set V. for i in range(u_emd.shape[0]): # Iterate for each node in the (assumed) batch. 'i' is local batch index. # To get neighbors, a global node ID is needed for `neighbor_dict`. This ID is not explicitly passed or derived here. # This is a significant discrepancy/missing detail if `u_emd` is just for a batch. # If `u_emd` is for ALL nodes, then `index` is global, but then `reconstruction_neighbors` needs to handle batching. # For this annotation, we'll assume `index` (from `enumerate(u_emd)`) is intended to be a global node ID, # implying `u_emd` (and `v_emd`) are for all nodes, and batching happens later or in `reconstruction_neighbors`. # This matches `forward_encoder` returning all embeddings. # `index` here is the global node ID. neighbor_indexes_for_node = neighbor_dict[i] # Get 1-hop neighbors for the current central node 'i'. # Sample positive embeddings 'u' from the target encoder embeddings `u_emd`. sampled_pos_embeddings = self.get_emb(neighbor_indexes_for_node, u_emd) # u_emd here is target embeddings of ALL nodes. sampled_embeddings_list.append(sampled_pos_embeddings) # Sample negative embeddings 'v_' from the online encoder embeddings `v_emd`. # Negative samples are drawn from the set of all nodes in the graph. all_node_indices = range(0, v_emd.shape[0]) # Assuming v_emd contains embeddings for all nodes. sampled_neg_embeddings = self.get_emb(all_node_indices, v_emd) # v_emd here is online embeddings of ALL nodes. sampled_embeddings_neg_list.append(sampled_neg_embeddings) return torch.stack(sampled_embeddings_list), torch.stack(sampled_embeddings_neg_list) def reconstruction_neighbors(self, projected_emd, u_emd, v_emd, neighbor_dict): # This method prepares the sampled embeddings and computes the contrastive loss. # `projected_emd`: Projected online embeddings 'p' for ALL nodes. # `u_emd`: Target embeddings 'u' for ALL nodes. # `v_emd`: Online embeddings 'v' for ALL nodes. # `neighbor_dict`: Adjacency information for sampling. # Sample positive ('u') and negative ('v_') embeddings. # `u_emd` (target embeddings) is passed as the source for positive samples. # `normalize(v_emd, ...)` (normalized online embeddings) is passed as the source for negative samples. # This aligns with Eq (5) where 'u' is from target f_xi, and 'v' and 'v_' are from online f_theta. sampled_embeddings_u, sampled_embeddings_neg_v = self.sample_neighbors(neighbor_dict, u_emd, normalize(v_emd, p=2, dim=-1)) # The `sample_neighbors` function, as analyzed, returns tensors of shape (num_nodes, sample_size, embed_dim). # The `contrastive_loss` expects batch-sized inputs. # This implies that `projected_emd` and `v_emd` need to be sliced for the current batch of nodes # for which the loss is being computed. This slicing is not shown here but is implied by the `unsqueeze(1)` # and the expected input shapes of `contrastive_loss`. # This means this function is likely called iteratively for batches, or these are already batch embeddings. # Given `forward_encoder` produces all embeddings, these are likely all embeddings. # The batching logic is a critical missing link between `sample_neighbors` and `contrastive_loss`. # If `projected_emd` is [N, D], `unsqueeze(1)` makes it [N, 1, D]. # This would be passed to `contrastive_loss` which expects [batch_size, 1, D]. # This implies that `projected_emd` and `v_emd` here must be pre-sliced for the batch *before* this call, # or `sample_neighbors` must only return samples for the batch. # The current `sample_neighbors` iterates `u_emd.shape[0]` times, which if `u_emd` is for all nodes, # means it computes samples for *all* nodes. This would be memory intensive. # Assuming that `projected_emd` and `v_emd` passed into this function are already the # embeddings for the *current batch* of central nodes (size B). # Then `sampled_embeddings_u` and `sampled_embeddings_neg_v` would be of shape [B, sample_size, D]. projected_emd_batch = projected_emd.unsqueeze(1) # [B, 1, D] v_emd_batch = normalize(v_emd, p=2, dim=-1).unsqueeze(1) # [B, 1, D] neighbor_recons_loss = contrastive_loss(projected_emd_batch, v_emd_batch, sampled_embeddings_u, sampled_embeddings_neg_v, self.tau, self.lambda_loss) return neighbor_recons_loss def neighbor_decoder(self, v_emd, u_emd, projected_emd, neighbor_dict): # This seems to be a wrapper around `reconstruction_neighbors`. # The paper does not use the term "neighbor_decoder". This method encapsulates the loss calculation # step which involves predicting/reconstructing neighborhood signals. # The arguments `v_emd`, `u_emd`, `projected_emd` here are assumed to be for the specific batch of nodes # for which loss is being computed, due to how `reconstruction_neighbors` must use them for `contrastive_loss`. neighbor_recons_loss = self.reconstruction_neighbors(projected_emd, u_emd, v_emd, neighbor_dict) return neighbor_recons_loss def forward(self, g, h, neighbor_dict, device): # Main forward pass of the GraphACL model. # 'g': Graph structure. # 'h': Input features for all nodes. # 'neighbor_dict': Adjacency information for sampling. # 'device': Computation device (e.g., 'cuda', 'cpu'). This is not used in the snippet. # 1. Get embeddings from encoders and projector for ALL nodes. v_emd_all, u_emd_all, projected_emd_all = self.forward_encoder(g, h) # 2. Compute loss. # The `neighbor_decoder` (and `reconstruction_neighbors` it calls) expects embeddings for the batch. # However, `v_emd_all`, `u_emd_all`, `projected_emd_all` are for all nodes. # This implies that either: # a) The entire graph is treated as a single batch (if memory allows). # b) There's missing logic here to select a batch of nodes and pass their respective embeddings # (e.g., `v_emd_batch = v_emd_all[batch_indices]`) to `neighbor_decoder`. # `neighbor_dict` would also need to be relevant to this batch or globally accessible. # Given the structure, if this is full-batch training, then `v_emd_all` is effectively the batch. # The `sample_neighbors` within `reconstruction_neighbors` iterates based on `u_emd.shape[0]`. # If `u_emd_all` (all N nodes) is passed, it will sample for all N nodes. # This matches the GraphACL loss definition which sums over all v in V. # So, this implementation appears to be for full-graph training where the "batch" is all nodes. loss = self.neighbor_decoder(v_emd_all, u_emd_all, projected_emd_all, neighbor_dict) # Returns the computed loss and the online embeddings 'v_emd_all' (f_theta(G)[v]), # which are typically used for downstream tasks. return loss, v_emd_all