Spaces:
Sleeping
Sleeping
import torch | |
import torch.nn as nn | |
import torch.nn.functional as F | |
from torch.nn import init | |
from torchvision import models | |
import os | |
import numpy as np | |
class Options: | |
def __init__(self): | |
# Default values | |
self.fine_height = 256 | |
self.fine_width = 192 | |
self.grid_size = 5 | |
self.use_dropout = False | |
self.input_nc = 22 | |
self.input_nc_B = 1 | |
self.tom_input_nc = 26 | |
self.tom_output_nc = 4 | |
def weights_init_normal(m): | |
classname = m.__class__.__name__ | |
if classname.find('Conv') != -1: | |
init.normal_(m.weight.data, 0.0, 0.02) | |
elif classname.find('Linear') != -1: | |
init.normal(m.weight.data, 0.0, 0.02) | |
elif classname.find('BatchNorm2d') != -1: | |
init.normal_(m.weight.data, 1.0, 0.02) | |
init.constant_(m.bias.data, 0.0) | |
def init_weights(net, init_type='normal'): | |
print('initialization method [%s]' % init_type) | |
net.apply(weights_init_normal) | |
class FeatureExtraction(nn.Module): | |
def __init__(self, input_nc, ngf=64, n_layers=3, norm_layer=nn.BatchNorm2d, use_dropout=False): | |
super(FeatureExtraction, self).__init__() | |
downconv = nn.Conv2d(input_nc, ngf, kernel_size=4, stride=2, padding=1) | |
model = [downconv, nn.ReLU(True), norm_layer(ngf)] | |
for i in range(n_layers): | |
in_ngf = 2**i * ngf if 2**i * ngf < 512 else 512 | |
out_ngf = 2**(i+1) * ngf if 2**i * ngf < 512 else 512 | |
downconv = nn.Conv2d(in_ngf, out_ngf, kernel_size=4, stride=2, padding=1) | |
model += [downconv, nn.ReLU(True), norm_layer(out_ngf)] | |
model += [nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1), nn.ReLU(True)] | |
model += [norm_layer(512)] | |
model += [nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1), nn.ReLU(True)] | |
self.model = nn.Sequential(*model) | |
init_weights(self.model) | |
class FeatureL2Norm(nn.Module): | |
def __init__(self): | |
super(FeatureL2Norm, self).__init__() | |
def forward(self, feature): | |
epsilon = 1e-6 | |
norm = torch.pow(torch.sum(torch.pow(feature, 2), 1) + epsilon, 0.5).unsqueeze(1).expand_as(feature) | |
return torch.div(feature, norm) | |
class FeatureCorrelation(nn.Module): | |
def __init__(self): | |
super(FeatureCorrelation, self).__init__() | |
def forward(self, feature_A, feature_B): | |
b, c, h, w = feature_A.size() | |
feature_A = feature_A.transpose(2, 3).contiguous().view(b, c, h*w) | |
feature_B = feature_B.view(b, c, h*w).transpose(1, 2) | |
feature_mul = torch.bmm(feature_B, feature_A) | |
return feature_mul.view(b, h, w, h*w).transpose(2, 3).transpose(1, 2) | |
class FeatureRegression(nn.Module): | |
def __init__(self, input_nc=512, output_dim=6): | |
super(FeatureRegression, self).__init__() | |
self.conv = nn.Sequential( | |
nn.Conv2d(input_nc, 512, kernel_size=4, stride=2, padding=1), | |
nn.BatchNorm2d(512), | |
nn.ReLU(inplace=True), | |
nn.Conv2d(512, 256, kernel_size=4, stride=2, padding=1), | |
nn.BatchNorm2d(256), | |
nn.ReLU(inplace=True), | |
nn.Conv2d(256, 128, kernel_size=3, padding=1), | |
nn.BatchNorm2d(128), | |
nn.ReLU(inplace=True), | |
nn.Conv2d(128, 64, kernel_size=3, padding=1), | |
nn.BatchNorm2d(64), | |
nn.ReLU(inplace=True), | |
) | |
self.linear = nn.Linear(64 * 4 * 3, output_dim) | |
self.tanh = nn.Tanh() | |
def forward(self, x): | |
x = self.conv(x) | |
x = x.contiguous().view(x.size(0), -1) | |
x = self.linear(x) | |
return self.tanh(x) | |
class TpsGridGen(nn.Module): | |
def __init__(self, out_h=256, out_w=192, grid_size=5): | |
super(TpsGridGen, self).__init__() | |
self.out_h, self.out_w = out_h, out_w | |
self.grid_size = grid_size | |
# Create grid | |
axis_coords = np.linspace(-1, 1, grid_size) | |
self.N = grid_size * grid_size | |
P_Y, P_X = np.meshgrid(axis_coords, axis_coords) | |
P_X = torch.FloatTensor(P_X.reshape(-1, 1)) | |
P_Y = torch.FloatTensor(P_Y.reshape(-1, 1)) | |
self.P_X_base = P_X.clone() | |
self.P_Y_base = P_Y.clone() | |
self.Li = self.compute_L_inverse(P_X, P_Y).unsqueeze(0) | |
# Grid for interpolation | |
grid_X, grid_Y = np.meshgrid(np.linspace(-1, 1, out_w), np.linspace(-1, 1, out_h)) | |
self.grid_X = torch.FloatTensor(grid_X).unsqueeze(0).unsqueeze(3) | |
self.grid_Y = torch.FloatTensor(grid_Y).unsqueeze(0).unsqueeze(3) | |
def compute_L_inverse(self, X, Y): | |
N = X.size()[0] | |
Xmat, Ymat = X.expand(N, N), Y.expand(N, N) | |
P_dist_squared = torch.pow(Xmat-Xmat.transpose(0, 1), 2) + torch.pow(Ymat-Ymat.transpose(0, 1), 2) | |
P_dist_squared[P_dist_squared == 0] = 1 | |
K = torch.mul(P_dist_squared, torch.log(P_dist_squared)) | |
O = torch.FloatTensor(N, 1).fill_(1) | |
Z = torch.FloatTensor(3, 3).fill_(0) | |
P = torch.cat((O, X, Y), 1) | |
L = torch.cat((torch.cat((K, P), 1), torch.cat((P.transpose(0, 1), Z), 1)), 0) | |
return torch.inverse(L) | |
def forward(self, theta): | |
theta = theta.contiguous() | |
batch_size = theta.size()[0] | |
# Split theta into point coordinates | |
Q_X = theta[:, :self.N].contiguous().view(batch_size, self.N, 1) | |
Q_Y = theta[:, self.N:].contiguous().view(batch_size, self.N, 1) | |
Q_X = Q_X + self.P_X_base.expand_as(Q_X) | |
Q_Y = Q_Y + self.P_Y_base.expand_as(Q_Y) | |
# Compute weights | |
W_X, W_Y = self.apply_theta(Q_X, Q_Y) | |
# Calculate transformed grid | |
points_X, points_Y = self.transform_points(W_X, W_Y) | |
return torch.cat((points_X, points_Y), 3) | |
class GMM(nn.Module): | |
def __init__(self, opt=None): | |
super(GMM, self).__init__() | |
if opt is None: | |
opt = Options() | |
self.extractionA = FeatureExtraction(opt.input_nc) | |
self.extractionB = FeatureExtraction(opt.input_nc_B) | |
self.l2norm = FeatureL2Norm() | |
self.correlation = FeatureCorrelation() | |
self.regression = FeatureRegression(input_nc=192, output_dim=2*opt.grid_size**2) | |
self.gridGen = TpsGridGen(opt.fine_height, opt.fine_width, opt.grid_size) | |
def forward(self, inputA, inputB): | |
featureA = self.extractionA(inputA) | |
featureB = self.extractionB(inputB) | |
featureA = self.l2norm(featureA) | |
featureB = self.l2norm(featureB) | |
correlation = self.correlation(featureA, featureB) | |
theta = self.regression(correlation) | |
grid = self.gridGen(theta) | |
return grid, theta | |
class UnetGenerator(nn.Module): | |
def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.InstanceNorm2d): | |
super(UnetGenerator, self).__init__() | |
unet_block = UnetSkipConnectionBlock( | |
ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) | |
for _ in range(num_downs - 5): | |
unet_block = UnetSkipConnectionBlock( | |
ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer) | |
unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer) | |
unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer) | |
unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer) | |
self.model = UnetSkipConnectionBlock( | |
output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) | |
def forward(self, input): | |
return self.model(input) | |
class UnetSkipConnectionBlock(nn.Module): | |
def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, | |
outermost=False, innermost=False, norm_layer=nn.InstanceNorm2d): | |
super(UnetSkipConnectionBlock, self).__init__() | |
self.outermost = outermost | |
use_bias = norm_layer == nn.InstanceNorm2d | |
if input_nc is None: | |
input_nc = outer_nc | |
downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) | |
downrelu = nn.LeakyReLU(0.2, True) | |
downnorm = norm_layer(inner_nc) | |
uprelu = nn.ReLU(True) | |
upnorm = norm_layer(outer_nc) | |
if outermost: | |
upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1) | |
down = [downconv] | |
up = [uprelu, upconv, nn.Tanh()] | |
model = down + [submodule] + up | |
elif innermost: | |
upconv = nn.ConvTranspose2d(inner_nc, outer_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) | |
down = [downrelu, downconv] | |
up = [uprelu, upconv, upnorm] | |
model = down + up | |
else: | |
upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) | |
down = [downrelu, downconv, downnorm] | |
up = [uprelu, upconv, upnorm] | |
model = down + [submodule] + up | |
self.model = nn.Sequential(*model) | |
def forward(self, x): | |
if self.outermost: | |
return self.model(x) | |
else: | |
return torch.cat([x, self.model(x)], 1) | |
class TOM(nn.Module): | |
""" Try-On Module """ | |
def __init__(self, opt=None): | |
super(TOM, self).__init__() | |
if opt is None: | |
opt = Options() | |
# Input: [agnostic(3) + warped_design(3) + warped_mask(1) + features(19)] = 26 channels | |
self.unet = UnetGenerator( | |
input_nc=opt.tom_input_nc, | |
output_nc=opt.tom_output_nc, # [rendered(3) + mask(1)] | |
num_downs=6, | |
norm_layer=nn.InstanceNorm2d | |
) | |
def forward(self, x): | |
output = self.unet(x) | |
p_rendered, m_composite = torch.split(output, [3, 1], dim=1) | |
p_rendered = torch.tanh(p_rendered) | |
m_composite = torch.sigmoid(m_composite) | |
return p_rendered, m_composite | |
def save_checkpoint(model, save_path): | |
if not os.path.exists(os.path.dirname(save_path)): | |
os.makedirs(os.path.dirname(save_path)) | |
torch.save(model.state_dict(), save_path) | |
def load_checkpoint(model, checkpoint_path, strict=True): | |
if not os.path.exists(checkpoint_path): | |
raise FileNotFoundError(f"Checkpoint file not found: {checkpoint_path}") | |
state_dict = torch.load(checkpoint_path, map_location=torch.device('cpu')) | |
model.load_state_dict(state_dict, strict=strict) |