To compute the mean vectors based on indices efficiently in PyTorch, you can use advanced indexing and the index_select function to select the vectors you want to average, followed by a mean computation. Here's a function that performs this operation:
import torch
def compute_mean_vectors_efficient(v, i):
"""
Compute the mean of vectors based on indices (efficient implementation).
Args:
v (torch.Tensor): Batched sequence of vectors (shape: batch_size x seq_len x feature_size).
i (torch.Tensor): Indices for each batch (shape: batch_size x num_indices).
Returns:
torch.Tensor: Mean vectors (shape: batch_size x num_indices x feature_size).
"""
# Calculate the batch size, sequence length, and feature size
batch_size, seq_len, feature_size = v.size()
num_indices = i.size(1)
# Initialize an empty tensor for the output
mean_vectors = torch.zeros(batch_size, num_indices, feature_size, device=v.device)
# Loop through the batch to handle different indices for each sample
for b in range(batch_size):
# Select the vectors corresponding to the indices for this batch
selected_vectors = v[b].index_select(0, i[b])
# Compute the mean along the sequence length dimension
mean_vectors[b] = selected_vectors.mean(dim=0)
return mean_vectors
However, the code above uses a for-loop to iterate over the batch, which might not be the most efficient approach when using GPUs. A more efficient implementation would avoid explicit Python loops and perform operations in batch whenever possible, which can be more parallelizable and hence faster on GPU.
Here is an alternative implementation using PyTorch's advanced indexing and avoiding explicit for-loops:
def compute_mean_vectors_efficient(v, i):
"""
Compute the mean of vectors based on indices (efficient implementation).
Args:
v (torch.Tensor): Batched sequence of vectors (shape: batch_size x seq_len x feature_size).
i (torch.Tensor): Indices for each batch (shape: batch_size x num_indices).
Returns:
torch.Tensor: Mean vectors (shape: batch_size x num_indices x feature_size).
"""
batch_size, num_indices = i.shape
feature_size = v.size(2)
# Expand the indices tensor to match the feature size
expanded_indices = i.unsqueeze(-1).expand(-1, -1, feature_size)
# Use advanced indexing to gather the vectors
gathered_vectors = v.gather(1, expanded_indices)
# Compute the mean along the second dimension (seq_len)
mean_vectors = gathered_vectors.mean(dim=1)
return mean_vectors
In this version, we expand the indices tensor to have the same size as the vectors tensor and use gather to get the vectors according to the indices, then compute the mean. This version should be faster than the first one since it's vectorized and exploits the parallelism of the GPU.