e = self.lt(inputs) # (batch_size, len([pos_u, pos_v, neg_v]), dim)
with torch.no_grad():
e = self.manifold.normalize(e)
o = e.narrow(1,1,e.size(1)-1) # (batch_size, len([pos_u, pos_v, neg_v]) - 1, dim)
s = e.narrow(1,0,1).expand_as(o) # (batch_size, len([pos_u, pos_v, neg_v]) - 1, dim)
ans = self.distance(s,o) # (batch_size, len([pos_u, pos_v, neg_v]) - 1, 1) 我能不能把这里面的self.distance共享一下,这样会不会加速?我的意思是拼成一个矩阵一起计算
Assistant
Yes, you can potentially speed up the computation by performing the distance calculations in a batched manner, assuming that your self.distance method supports batch operations. This is often more efficient than doing them one at a time, as it allows the underlying hardware to take advantage of parallelism.
Here's a conceptual approach to batch these operations together:
Reshape Inputs: Instead of computing the distance between pairs individually, reshape your inputs such that you can compute all distances at once using matrix operations.
Broadcasting: Use broadcasting to expand and compute pairwise distances in a vectorized manner.
Here is how you can modify your code to batch the distance computations:
python
def forward(self, inputs, entry_ids_list, exit_ids_list):
device = self.lt.weight.device
entry_ids_list = torch.tensor(entry_ids_list, dtype=torch.long, device=device)
exit_ids_list = torch.tensor(exit_ids_list, dtype=torch.long, device=device)
list_entry = self.lt.weight[entry_ids_list] # (city_size, dim)
list_exit = self.lt.weight[exit_ids_list] # (city_size, dim)
dist_sum = self.distance(list_entry, list_exit) # (city_size, 1)
e = self.lt(inputs) # (batch_size, len([pos_u, pos_v, neg_v]), dim)
with torch.no_grad():
e = self.manifold.normalize(e)
# Extract and reshape tensors for distance calculation
o = e[:, 1:, :] # (batch_size, len([pos_u, pos_v, neg_v]) - 1, dim)
s = e[:, :1, :] # (batch_size, 1, dim)
# Expand s to match dimensions of o
s_expanded = s.expand(-1, o.size(1), -1) # (batch_size, len([pos_u, pos_v, neg_v]) - 1, dim)
# Compute all pairwise distances in a batch
ans = self.distance(s_expanded, o) # (batch_size, len([pos_u, pos_v, neg_v]) - 1, 1)
return dist_sum, ans
Explanation:
Broadcasting: By reshaping and expanding s to the size of o, you allow for vectorized computation of distances using broadcasting, which allows for efficient computation.
Efficiency: The major efficiency gain here is that by handling operations in a batch manner, you reduce the overhead associated with looping and allow for optimized linear algebra operations that can be parallelized by libraries like cuBLAS (CUDA Basic Linear Algebra Subprograms) in the backend.
Ensure that self.distance is capable of handling elements with the expanded dimensions. Depending on the nature of the distance computation (e.g., Euclidean, cosine), you might need to adjust its implementation to ensure it can handle these batched inputs correctly.