"training/configs/vscode:/vscode.git/clone" did not exist on "0bf5e50038ee341ece03bfd0c8ff45a6c57aed5a"
taesd.py 2.97 KB
Newer Older
space-nuko's avatar
space-nuko committed
1
2
3
4
5
6
7
8
#!/usr/bin/env python3
"""
Tiny AutoEncoder for Stable Diffusion
(DNN for encoding / decoding SD's latent space)
"""
import torch
import torch.nn as nn

comfyanonymous's avatar
comfyanonymous committed
9
import comfy.utils
10
import comfy.ops
comfyanonymous's avatar
comfyanonymous committed
11

space-nuko's avatar
space-nuko committed
12
def conv(n_in, n_out, **kwargs):
13
    return comfy.ops.disable_weight_init.Conv2d(n_in, n_out, 3, padding=1, **kwargs)
space-nuko's avatar
space-nuko committed
14
15
16
17
18
19
20
21
22

class Clamp(nn.Module):
    def forward(self, x):
        return torch.tanh(x / 3) * 3

class Block(nn.Module):
    def __init__(self, n_in, n_out):
        super().__init__()
        self.conv = nn.Sequential(conv(n_in, n_out), nn.ReLU(), conv(n_out, n_out), nn.ReLU(), conv(n_out, n_out))
23
        self.skip = comfy.ops.disable_weight_init.Conv2d(n_in, n_out, 1, bias=False) if n_in != n_out else nn.Identity()
space-nuko's avatar
space-nuko committed
24
25
26
27
        self.fuse = nn.ReLU()
    def forward(self, x):
        return self.fuse(self.conv(x) + self.skip(x))

Dr.Lt.Data's avatar
Dr.Lt.Data committed
28
def Encoder(latent_channels=4):
space-nuko's avatar
space-nuko committed
29
30
31
32
33
    return nn.Sequential(
        conv(3, 64), Block(64, 64),
        conv(64, 64, stride=2, bias=False), Block(64, 64), Block(64, 64), Block(64, 64),
        conv(64, 64, stride=2, bias=False), Block(64, 64), Block(64, 64), Block(64, 64),
        conv(64, 64, stride=2, bias=False), Block(64, 64), Block(64, 64), Block(64, 64),
Dr.Lt.Data's avatar
Dr.Lt.Data committed
34
        conv(64, latent_channels),
space-nuko's avatar
space-nuko committed
35
36
    )

Dr.Lt.Data's avatar
Dr.Lt.Data committed
37
38

def Decoder(latent_channels=4):
space-nuko's avatar
space-nuko committed
39
    return nn.Sequential(
Dr.Lt.Data's avatar
Dr.Lt.Data committed
40
        Clamp(), conv(latent_channels, 64), nn.ReLU(),
space-nuko's avatar
space-nuko committed
41
42
43
44
45
46
47
48
49
50
        Block(64, 64), Block(64, 64), Block(64, 64), nn.Upsample(scale_factor=2), conv(64, 64, bias=False),
        Block(64, 64), Block(64, 64), Block(64, 64), nn.Upsample(scale_factor=2), conv(64, 64, bias=False),
        Block(64, 64), Block(64, 64), Block(64, 64), nn.Upsample(scale_factor=2), conv(64, 64, bias=False),
        Block(64, 64), conv(64, 3),
    )

class TAESD(nn.Module):
    latent_magnitude = 3
    latent_shift = 0.5

Dr.Lt.Data's avatar
Dr.Lt.Data committed
51
    def __init__(self, encoder_path=None, decoder_path=None, latent_channels=4):
space-nuko's avatar
space-nuko committed
52
53
        """Initialize pretrained TAESD on the given device from the given checkpoints."""
        super().__init__()
Dr.Lt.Data's avatar
Dr.Lt.Data committed
54
55
        self.taesd_encoder = Encoder(latent_channels=latent_channels)
        self.taesd_decoder = Decoder(latent_channels=latent_channels)
56
        self.vae_scale = torch.nn.Parameter(torch.tensor(1.0))
space-nuko's avatar
space-nuko committed
57
        if encoder_path is not None:
58
            self.taesd_encoder.load_state_dict(comfy.utils.load_torch_file(encoder_path, safe_load=True))
space-nuko's avatar
space-nuko committed
59
        if decoder_path is not None:
60
            self.taesd_decoder.load_state_dict(comfy.utils.load_torch_file(decoder_path, safe_load=True))
space-nuko's avatar
space-nuko committed
61
62
63
64
65
66
67
68
69
70

    @staticmethod
    def scale_latents(x):
        """raw latents -> [0, 1]"""
        return x.div(2 * TAESD.latent_magnitude).add(TAESD.latent_shift).clamp(0, 1)

    @staticmethod
    def unscale_latents(x):
        """[0, 1] -> raw latents"""
        return x.sub(TAESD.latent_shift).mul(2 * TAESD.latent_magnitude)
71
72
73
74
75
76
77
78

    def decode(self, x):
        x_sample = self.taesd_decoder(x * self.vae_scale)
        x_sample = x_sample.sub(0.5).mul(2)
        return x_sample

    def encode(self, x):
        return self.taesd_encoder(x * 0.5 + 0.5) / self.vae_scale