Write me a sum over a neighborhood in pytorch
- User
Write me a sum over a neighborhood in pytorch
Assistant
pythonimport torch def sum_over_neighborhood(x, idx_i, idx_j, pair_mask): """ Sums features over neighboring atoms. Args: x: Tensor of shape (n_atoms, n_features) representing atom features. idx_i: Tensor of shape (n_pairs,) representing the central atom index for each pair. idx_j: Tensor of shape (n_pairs,) representing the neighboring atom index for each pair. pair_mask: Tensor of shape (n_pairs,) masking invalid pairs (e.g., due to padding). Returns: A tensor of shape (n_atoms, n_features) representing the sum of features over the neighborhood of each atom. """ n_atoms = x.shape[0] n_features = x.shape[1] # Apply the mask to select relevant pairs masked_idx_i = idx_i[pair_mask] masked_idx_j = idx_j[pair_mask] # Gather features of neighboring atoms neighbor_features = x[masked_idx_j] # Sum features over neighborhoods summed_features = torch.zeros((n_atoms, n_features), dtype=x.dtype, device=x.device) summed_features.index_add_(0, masked_idx_i, neighbor_features) # Efficient summation return summed_features # Example Usage n_atoms = 5 n_features = 3 n_pairs = 8 x = torch.randn(n_atoms, n_features) idx_i = torch.tensor([0, 0, 1, 1, 2, 2, 3, 4]) idx_j = torch.tensor([1, 2, 0, 3, 1, 4, 2, 0]) pair_mask = torch.tensor([True, True, False, True, True, True, False, True]) summed_features = sum_over_neighborhood(x, idx_i, idx_j, pair_mask) print(summed_features)Key improvements and explanations for this PyTorch implementation:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.