MCPcopy Create free account
hub / github.com/CompVis/diff2flow / TinyAutoencoderKL

Class TinyAutoencoderKL

diff2flow/tiny_autoencoder.py:49–100  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

47
48
49class TinyAutoencoderKL(nn.Module):
50 latent_magnitude = 3
51 latent_shift = 0.5
52
53 def __init__(self, encoder_path="taesd_encoder.pth", decoder_path="taesd_decoder.pth", latent_channels=None):
54 """Initialize pretrained TAESD on the given device from the given checkpoints."""
55 super().__init__()
56 if latent_channels is None:
57 latent_channels = self.guess_latent_channels(str(encoder_path))
58 self.encoder = Encoder(latent_channels)
59 self.decoder = Decoder(latent_channels)
60 if encoder_path is not None:
61 self.encoder.load_state_dict(torch.load(encoder_path, map_location="cpu", weights_only=True))
62 if decoder_path is not None:
63 self.decoder.load_state_dict(torch.load(decoder_path, map_location="cpu", weights_only=True))
64
65 @torch.no_grad()
66 def encode(self, x):
67 """
68 Args:
69 x: torch.Tensor, shape (b, 3, h, w) in [-1, 1]
70 """
71 # scale to [0, 1]
72 x = x.div(2).add(0.5)
73 return self.encoder(x)
74
75 @torch.no_grad()
76 def decode(self, z):
77 """
78 Args:
79 z: torch.Tensor, shape (b, latent_channels, h, w)
80 """
81 # scale to [-1, 1]
82 return self.decoder(z).mul(2).sub(1)
83
84 def guess_latent_channels(self, encoder_path):
85 """guess latent channel count based on encoder filename"""
86 if "taef1" in encoder_path:
87 return 16
88 if "taesd3" in encoder_path:
89 return 16
90 return 4
91
92 @staticmethod
93 def scale_latents(x):
94 """raw latents -> [0, 1]"""
95 return x.div(2 * TinyAutoencoderKL.latent_magnitude).add(TinyAutoencoderKL.latent_shift).clamp(0, 1)
96
97 @staticmethod
98 def unscale_latents(x):
99 """[0, 1] -> raw latents"""
100 return x.sub(TinyAutoencoderKL.latent_shift).mul(2 * TinyAutoencoderKL.latent_magnitude)
101
102
103if __name__ == "__main__":

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected