File size: 1,981 Bytes
f1725f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# vae_encoder.py
import torch
import torch.nn as nn
from config import IMG_CHANNELS, LATENT_CHANNELS, VAE_BASE_CHANNELS, VAE_CHANNEL_MULT


class ResBlock(nn.Module):
    """GroupNorm -> SiLU -> Conv, twice, plus a skip connection.
    The skip lets fine detail (thin text strokes!) pass straight through; the
    old plain conv stack had to squeeze everything through each layer."""
    def __init__(self, in_ch, out_ch):
        super().__init__()
        self.block = nn.Sequential(
            nn.GroupNorm(32, in_ch), nn.SiLU(), nn.Conv2d(in_ch, out_ch, 3, padding=1),
            nn.GroupNorm(32, out_ch), nn.SiLU(), nn.Conv2d(out_ch, out_ch, 3, padding=1),
        )
        self.skip = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()

    def forward(self, x):
        return self.skip(x) + self.block(x)


class VAEEncoder(nn.Module):
    """
    256x256x3 image -> 32x32x4 latent (mu, log_var).
    One resolution level per entry in VAE_CHANNEL_MULT, downsampling between levels:
    256 -> 128 -> 64 -> 32.
    """
    def __init__(self, in_channels=IMG_CHANNELS, latent_channels=LATENT_CHANNELS,
                 base_channels=VAE_BASE_CHANNELS, channel_mult=VAE_CHANNEL_MULT):
        super().__init__()
        chs = [base_channels * m for m in channel_mult]
        layers = [nn.Conv2d(in_channels, chs[0], 3, padding=1)]
        for i, ch in enumerate(chs):
            prev = chs[i - 1] if i > 0 else chs[0]
            layers += [ResBlock(prev, ch), ResBlock(ch, ch)]
            if i < len(chs) - 1:
                layers.append(nn.Conv2d(ch, ch, 3, stride=2, padding=1))   # downsample x2
        layers += [ResBlock(chs[-1], chs[-1]), nn.GroupNorm(32, chs[-1]), nn.SiLU(),
                   nn.Conv2d(chs[-1], 2 * latent_channels, 3, padding=1)]
        self.net = nn.Sequential(*layers)

    def forward(self, x):
        mu, log_var = self.net(x).chunk(2, dim=1)
        return mu, log_var.clamp(-30.0, 20.0)   # keep exp(log_var) finite