sd_vae_approx.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import os
  2. import torch
  3. from torch import nn
  4. from modules import devices, paths
  5. sd_vae_approx_model = None
  6. class VAEApprox(nn.Module):
  7. def __init__(self):
  8. super(VAEApprox, self).__init__()
  9. self.conv1 = nn.Conv2d(4, 8, (7, 7))
  10. self.conv2 = nn.Conv2d(8, 16, (5, 5))
  11. self.conv3 = nn.Conv2d(16, 32, (3, 3))
  12. self.conv4 = nn.Conv2d(32, 64, (3, 3))
  13. self.conv5 = nn.Conv2d(64, 32, (3, 3))
  14. self.conv6 = nn.Conv2d(32, 16, (3, 3))
  15. self.conv7 = nn.Conv2d(16, 8, (3, 3))
  16. self.conv8 = nn.Conv2d(8, 3, (3, 3))
  17. def forward(self, x):
  18. extra = 11
  19. x = nn.functional.interpolate(x, (x.shape[2] * 2, x.shape[3] * 2))
  20. x = nn.functional.pad(x, (extra, extra, extra, extra))
  21. for layer in [self.conv1, self.conv2, self.conv3, self.conv4, self.conv5, self.conv6, self.conv7, self.conv8, ]:
  22. x = layer(x)
  23. x = nn.functional.leaky_relu(x, 0.1)
  24. return x
  25. def model():
  26. global sd_vae_approx_model
  27. if sd_vae_approx_model is None:
  28. model_path = os.path.join(paths.models_path, "VAE-approx", "model.pt")
  29. sd_vae_approx_model = VAEApprox()
  30. if not os.path.exists(model_path):
  31. model_path = os.path.join(paths.script_path, "models", "VAE-approx", "model.pt")
  32. sd_vae_approx_model.load_state_dict(torch.load(model_path, map_location='cpu' if devices.device.type != 'cuda' else None))
  33. sd_vae_approx_model.eval()
  34. sd_vae_approx_model.to(devices.device, devices.dtype)
  35. return sd_vae_approx_model
  36. def cheap_approximation(sample):
  37. # https://discuss.huggingface.co/t/decoding-latents-to-rgb-without-upscaling/23204/2
  38. coefs = torch.tensor([
  39. [0.298, 0.207, 0.208],
  40. [0.187, 0.286, 0.173],
  41. [-0.158, 0.189, 0.264],
  42. [-0.184, -0.271, -0.473],
  43. ]).to(sample.device)
  44. x_sample = torch.einsum("lxy,lr -> rxy", sample, coefs)
  45. return x_sample