Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add batch support #124

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 12 additions & 1 deletion lpips/lpips.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ def __init__(self, pretrained=True, net='alex', version='0.1', lpips=True, spati
self.eval()

def forward(self, in0, in1, retPerLayer=False, normalize=False):
batch_size0 = in0.shape[0]
batch_size1 = in1.shape[0]

if normalize: # turn on this flag if input is [0,1] so it can be adjusted to [-1, +1]
in0 = 2 * in0 - 1
in1 = 2 * in1 - 1
Expand All @@ -121,7 +124,9 @@ def forward(self, in0, in1, retPerLayer=False, normalize=False):

for kk in range(self.L):
feats0[kk], feats1[kk] = lpips.normalize_tensor(outs0[kk]), lpips.normalize_tensor(outs1[kk])
diffs[kk] = (feats0[kk]-feats1[kk])**2
diffs[kk] = (feats0[kk][:, None] - feats1[kk][None]) ** 2
# put all pairwise differences in batch dimension
diffs[kk] = diffs[kk].view(batch_size0 * batch_size1, *diffs[kk].shape[2:])

if(self.lpips):
if(self.spatial):
Expand All @@ -134,6 +139,12 @@ def forward(self, in0, in1, retPerLayer=False, normalize=False):
else:
res = [spatial_average(diffs[kk].sum(dim=1,keepdim=True), keepdim=True) for kk in range(self.L)]

# unpack again to get batch_size0 x batch_size1 outputs for all pairwise distances
if(self.spatial):
res = [r.view(batch_size0, batch_size1, *r.shape[1:]) for r in res]
else:
res = [r.view(batch_size0, batch_size1) for r in res]

val = 0
for l in range(self.L):
val += res[l]
Expand Down