PerceptualSimilarity icon indicating copy to clipboard operation
PerceptualSimilarity copied to clipboard

A new `forward_distmat` method to accelerate distance matrix computing among images.

Open Animadversio opened this issue 2 years ago • 6 comments

Summary

Add another forward function forward_distmat to compute the distance matrix with one or two stacks of images.

Rationale

The currentforward method of LPIPS supports computing the distance between two images (A,B), or between one image to a batch of images (As,Bs) or the distance between corresponding pairs in two batches (As,Bs). Because of this, computing the distance matrix cannot be directly performed using the current forward function It needs to be computed row by row, for example given a imgtsrs of shape [B,C,H,W]

Dist = LPIPS(net="squeeze", ).cuda()
Dist.requires_grad_(False)

distmat_bin = []
for i in range(imgtsrs.shape[0]):
    dist_in_bin = Dist(imgtsrs.cuda(), imgtsrs[i:i + 1].cuda()).cpu().squeeze()
    distmat_bin.append(dist_in_bin)

distmat_bin = torch.stack(distmat_bin, dim=0)

A simple fix to accelerate this is to move this loop into the forward function. Then it can reuse the features computed for images, so it largely accelerates the speed of computing a large distance matrix among a set of images.

distmat_bin = Dist.forward_distmat(imgtsrs_rf.cuda(), None).cpu().squeeze()

Memory usage.

We choose to compute the matrix row by row, such that the memory footprint shall be still linear in the number of images instead of quadratic.

TODO

It could be extended to compute a few rows in a batch. The batch size needs to be chosen w.r.t. memory. Currently, it's fast enough for most of my works, but there is space for further optimization. If there is interest in more efficiency I can help implement more.

Animadversio avatar Apr 23 '22 01:04 Animadversio

Bump this up the pile!

Animadversio avatar May 01 '22 05:05 Animadversio

Bump this up the pile !

Animadversio avatar May 24 '22 05:05 Animadversio

Bump up this thread

Animadversio avatar Jun 17 '22 19:06 Animadversio

+1

matteo-pennisi avatar Feb 01 '23 09:02 matteo-pennisi

Bump up this thread again!

Animadversio avatar Jun 12 '23 02:06 Animadversio

+1

JefferyChiang avatar Sep 15 '23 08:09 JefferyChiang