File size: 1,330 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 | # vae_decoder.py
import torch.nn as nn
from config import IMG_CHANNELS, LATENT_CHANNELS, VAE_BASE_CHANNELS, VAE_CHANNEL_MULT
from vae_encoder import ResBlock
class VAEDecoder(nn.Module):
"""32x32x4 latent -> 256x256x3 image. Mirror image of the encoder."""
def __init__(self, latent_channels=LATENT_CHANNELS, out_channels=IMG_CHANNELS,
base_channels=VAE_BASE_CHANNELS, channel_mult=VAE_CHANNEL_MULT):
super().__init__()
chs = [base_channels * m for m in channel_mult][::-1] # deepest first
layers = [nn.Conv2d(latent_channels, chs[0], 3, padding=1), ResBlock(chs[0], chs[0])]
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 += [nn.Upsample(scale_factor=2, mode='nearest'),
nn.Conv2d(ch, ch, 3, padding=1)] # upsample x2
layers += [nn.GroupNorm(32, chs[-1]), nn.SiLU(), nn.Conv2d(chs[-1], out_channels, 3, padding=1)]
self.net = nn.Sequential(*layers)
def forward(self, z):
# No Tanh: it squashes gradients near +-1 (pure white/black, i.e. text strokes).
# Clamp to [-1, 1] only when converting to an image for viewing.
return self.net(z)
|