generators.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. from fastai.core import *
  2. from fastai.conv_learner import model_meta, cut_model
  3. from fastai.transforms import scale_min
  4. from .modules import ConvBlock, UnetBlock, UpSampleBlock, SaveFeatures
  5. from abc import ABC, abstractmethod
  6. from torchvision import transforms
  7. class GeneratorModule(ABC, nn.Module):
  8. def __init__(self):
  9. super().__init__()
  10. def set_trainable(self, trainable:bool):
  11. set_trainable(self, trainable)
  12. @abstractmethod
  13. def get_layer_groups(self, precompute:bool=False)->[]:
  14. pass
  15. @abstractmethod
  16. def forward(self, x_in:torch.Tensor, max_render_sz:int=400):
  17. pass
  18. def freeze_to(self, n:int):
  19. c=self.get_layer_groups()
  20. for l in c: set_trainable(l, False)
  21. for l in c[n:]: set_trainable(l, True)
  22. def get_device(self):
  23. return next(self.parameters()).device
  24. class Unet34(GeneratorModule):
  25. @staticmethod
  26. def _get_pretrained_resnet_base(layers_cut:int=0):
  27. f = resnet34
  28. cut,lr_cut = model_meta[f]
  29. cut-=layers_cut
  30. layers = cut_model(f(True), cut)
  31. return nn.Sequential(*layers), lr_cut
  32. def __init__(self, nf_factor:int=1, scale:int=1):
  33. super().__init__()
  34. assert (math.log(scale,2)).is_integer()
  35. leakyReLu=False
  36. self_attention=True
  37. bn=True
  38. sn=True
  39. self.rn, self.lr_cut = Unet34._get_pretrained_resnet_base()
  40. self.relu = nn.ReLU()
  41. self.up1 = UnetBlock(512,256,512*nf_factor, sn=sn, leakyReLu=leakyReLu, bn=bn)
  42. self.up2 = UnetBlock(512*nf_factor,128,512*nf_factor, sn=sn, leakyReLu=leakyReLu, bn=bn)
  43. self.up3 = UnetBlock(512*nf_factor,64,512*nf_factor, sn=sn, self_attention=self_attention, leakyReLu=leakyReLu, bn=bn)
  44. self.up4 = UnetBlock(512*nf_factor,64,256*nf_factor, sn=sn, leakyReLu=leakyReLu, bn=bn)
  45. self.up5 = UpSampleBlock(256*nf_factor, 32*nf_factor, 2*scale, sn=sn, leakyReLu=leakyReLu, bn=bn)
  46. self.out= nn.Sequential(ConvBlock(32*nf_factor, 3, ks=3, actn=False, bn=False, sn=sn), nn.Tanh())
  47. #Gets around irritating inconsistent halving coming from resnet
  48. def _pad(self, x:torch.Tensor, target:torch.Tensor, total_padh:int, total_padw:int)-> torch.Tensor:
  49. h = x.shape[2]
  50. w = x.shape[3]
  51. target_h = target.shape[2]*2
  52. target_w = target.shape[3]*2
  53. if h<target_h or w<target_w:
  54. padh = target_h-h if target_h > h else 0
  55. total_padh = total_padh + padh
  56. padw = target_w-w if target_w > w else 0
  57. total_padw = total_padw + padw
  58. return (F.pad(x, (0,padw,0,padh), "reflect",0), total_padh, total_padw)
  59. return (x, total_padh, total_padw)
  60. def _remove_padding(self, x:torch.Tensor, padh:int, padw:int)->torch.Tensor:
  61. if padw == 0 and padh == 0:
  62. return x
  63. target_h = x.shape[2]-padh
  64. target_w = x.shape[3]-padw
  65. return x[:,:,:target_h, :target_w]
  66. def _encode(self, x:torch.Tensor):
  67. x = self.rn[0](x)
  68. x = self.rn[1](x)
  69. x = self.rn[2](x)
  70. enc0 = x
  71. x = self.rn[3](x)
  72. x = self.rn[4](x)
  73. enc1 = x
  74. x = self.rn[5](x)
  75. enc2 = x
  76. x = self.rn[6](x)
  77. enc3 = x
  78. x = self.rn[7](x)
  79. return (x, enc0, enc1, enc2, enc3)
  80. def _decode(self, x:torch.Tensor, enc0:torch.Tensor, enc1:torch.Tensor, enc2:torch.Tensor, enc3:torch.Tensor):
  81. padh = 0
  82. padw = 0
  83. x = self.relu(x)
  84. enc3, padh, padw = self._pad(enc3, x, padh, padw)
  85. x = self.up1(x, enc3)
  86. enc2, padh, padw = self._pad(enc2, x, padh, padw)
  87. x = self.up2(x, enc2)
  88. enc1, padh, padw = self._pad(enc1, x, padh, padw)
  89. x = self.up3(x, enc1)
  90. enc0, padh, padw = self._pad(enc0, x, padh, padw)
  91. x = self.up4(x, enc0)
  92. #This is a bit too much padding being removed, but I
  93. #haven't yet figured out a good way to determine what
  94. #exactly should be removed. This is consistently more
  95. #than enough though.
  96. x = self.up5(x)
  97. x = self.out(x)
  98. x = self._remove_padding(x, padh, padw)
  99. return x
  100. def forward(self, x:torch.Tensor):
  101. x, enc0, enc1, enc2, enc3 = self._encode(x)
  102. x = self._decode(x, enc0, enc1, enc2, enc3)
  103. return x
  104. def get_layer_groups(self, precompute:bool=False)->[]:
  105. lgs = list(split_by_idxs(children(self.rn), [self.lr_cut]))
  106. return lgs + [children(self)[1:]]
  107. def close(self):
  108. for sf in self.sfs:
  109. sf.remove()