Upload 3 files
Browse files- pyproject.toml +11 -0
- semantic_vae.py +452 -0
- semantic_vae_step_00050000.safetensors +3 -0
pyproject.toml
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "semantic-vae"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
description = "Add your description here"
|
| 5 |
+
readme = "README.md"
|
| 6 |
+
requires-python = ">=3.12"
|
| 7 |
+
dependencies = [
|
| 8 |
+
"safetensors>=0.8.0",
|
| 9 |
+
"timm>=1.0.29",
|
| 10 |
+
"torch>=2.13.0",
|
| 11 |
+
]
|
semantic_vae.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Inference wrapper for the Semantic VAE.
|
| 2 |
+
|
| 3 |
+
Images are BCHW tensors in [-1, 1]. ``encode`` and ``decode`` use normalized
|
| 4 |
+
latents; their ``_raw`` variants use the underlying VAE representation.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import copy
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Mapping
|
| 13 |
+
|
| 14 |
+
import timm
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
from safetensors import safe_open
|
| 19 |
+
from safetensors.torch import load_file
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
DINO_MODEL_NAME = "vit_base_patch14_dinov2.lvd142m"
|
| 23 |
+
DINO_MEAN = (0.485, 0.456, 0.406)
|
| 24 |
+
DINO_STD = (0.229, 0.224, 0.225)
|
| 25 |
+
DINO_PATCH_SIZE = 14
|
| 26 |
+
LATENT_DOWNSAMPLE_FACTOR = 16
|
| 27 |
+
SAFETENSORS_FORMAT = "semantic_vae_full_v1"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _dino_spatial_size(image_size: tuple[int, int]) -> tuple[int, int]:
|
| 31 |
+
height, width = image_size
|
| 32 |
+
half_stride = LATENT_DOWNSAMPLE_FACTOR // 2
|
| 33 |
+
patches = (
|
| 34 |
+
max(1, (size + half_stride) // LATENT_DOWNSAMPLE_FACTOR)
|
| 35 |
+
for size in (height, width)
|
| 36 |
+
)
|
| 37 |
+
return tuple(size * DINO_PATCH_SIZE for size in patches)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _group_norm(channels: int) -> nn.GroupNorm:
|
| 41 |
+
return nn.GroupNorm(32, channels, eps=1e-6, affine=True)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class ResnetBlock(nn.Module):
|
| 45 |
+
def __init__(self, in_ch: int, out_ch: int) -> None:
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.norm1 = _group_norm(in_ch)
|
| 48 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 49 |
+
self.norm2 = _group_norm(out_ch)
|
| 50 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 51 |
+
self.shortcut = (
|
| 52 |
+
nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 56 |
+
h = self.conv1(F.silu(self.norm1(x)))
|
| 57 |
+
h = self.conv2(F.silu(self.norm2(h)))
|
| 58 |
+
return self.shortcut(x) + h
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class AttnBlock(nn.Module):
|
| 62 |
+
def __init__(self, channels: int) -> None:
|
| 63 |
+
super().__init__()
|
| 64 |
+
self.norm = _group_norm(channels)
|
| 65 |
+
self.qkv = nn.Conv2d(channels, channels * 3, 1)
|
| 66 |
+
self.proj_out = nn.Conv2d(channels, channels, 1)
|
| 67 |
+
|
| 68 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 69 |
+
batch, channels, height, width = x.shape
|
| 70 |
+
q, k, v = (
|
| 71 |
+
self.qkv(self.norm(x))
|
| 72 |
+
.reshape(batch, 3, 1, channels, height * width)
|
| 73 |
+
.transpose(-2, -1)
|
| 74 |
+
.unbind(1)
|
| 75 |
+
)
|
| 76 |
+
h = F.scaled_dot_product_attention(q, k, v)
|
| 77 |
+
h = h.transpose(-2, -1).reshape(batch, channels, height, width)
|
| 78 |
+
return x + self.proj_out(h)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class Upsample(nn.Module):
|
| 82 |
+
def __init__(self, channels: int) -> None:
|
| 83 |
+
super().__init__()
|
| 84 |
+
self.conv = nn.Conv2d(channels, channels, 3, padding=1)
|
| 85 |
+
|
| 86 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 87 |
+
return self.conv(F.interpolate(x, scale_factor=2.0, mode="nearest"))
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class Decoder(nn.Module):
|
| 91 |
+
def __init__(
|
| 92 |
+
self,
|
| 93 |
+
z_channels: int = 64,
|
| 94 |
+
ch: int = 128,
|
| 95 |
+
num_res_blocks: int = 2,
|
| 96 |
+
) -> None:
|
| 97 |
+
super().__init__()
|
| 98 |
+
ch_mult = (1, 1, 2, 2, 4)
|
| 99 |
+
num_resolutions = len(ch_mult)
|
| 100 |
+
block_in = ch * ch_mult[-1]
|
| 101 |
+
current_resolution = 16
|
| 102 |
+
|
| 103 |
+
self.conv_in = nn.Conv2d(z_channels, block_in, 3, padding=1)
|
| 104 |
+
self.mid = nn.ModuleList(
|
| 105 |
+
[
|
| 106 |
+
ResnetBlock(block_in, block_in),
|
| 107 |
+
AttnBlock(block_in),
|
| 108 |
+
ResnetBlock(block_in, block_in),
|
| 109 |
+
]
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
self.up = nn.ModuleList()
|
| 113 |
+
for level in reversed(range(num_resolutions)):
|
| 114 |
+
block_out = ch * ch_mult[level]
|
| 115 |
+
blocks = nn.ModuleList()
|
| 116 |
+
for _ in range(num_res_blocks + 1):
|
| 117 |
+
blocks.append(ResnetBlock(block_in, block_out))
|
| 118 |
+
block_in = block_out
|
| 119 |
+
if current_resolution == 16:
|
| 120 |
+
blocks.append(AttnBlock(block_in))
|
| 121 |
+
if level != 0:
|
| 122 |
+
blocks.append(Upsample(block_in))
|
| 123 |
+
current_resolution *= 2
|
| 124 |
+
self.up.append(blocks)
|
| 125 |
+
|
| 126 |
+
self.norm_out = _group_norm(block_in)
|
| 127 |
+
self.conv_out = nn.Conv2d(block_in, 3, 3, padding=1)
|
| 128 |
+
|
| 129 |
+
def forward(self, latent: torch.Tensor) -> torch.Tensor:
|
| 130 |
+
hidden = self.conv_in(latent)
|
| 131 |
+
for block in self.mid:
|
| 132 |
+
hidden = block(hidden)
|
| 133 |
+
for level in self.up:
|
| 134 |
+
for block in level:
|
| 135 |
+
hidden = block(hidden)
|
| 136 |
+
return self.conv_out(F.silu(self.norm_out(hidden)))
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class SemanticVAE(nn.Module):
|
| 140 |
+
"""Inference portion of the trained DINOv2-B semantic autoencoder."""
|
| 141 |
+
|
| 142 |
+
def __init__(
|
| 143 |
+
self,
|
| 144 |
+
*,
|
| 145 |
+
pretrained: bool = True,
|
| 146 |
+
latent_dim: int = 64,
|
| 147 |
+
encoder_layers: int = 6,
|
| 148 |
+
decoder_ch: int = 128,
|
| 149 |
+
decoder_num_res_blocks: int = 2,
|
| 150 |
+
) -> None:
|
| 151 |
+
super().__init__()
|
| 152 |
+
self.encoder = timm.create_model(
|
| 153 |
+
DINO_MODEL_NAME,
|
| 154 |
+
pretrained=pretrained,
|
| 155 |
+
num_classes=0,
|
| 156 |
+
dynamic_img_size=True,
|
| 157 |
+
dynamic_img_pad=True,
|
| 158 |
+
)
|
| 159 |
+
self.semantic_encoder = copy.deepcopy(self.encoder)
|
| 160 |
+
self.semantic_encoder.requires_grad_(False)
|
| 161 |
+
self.semantic_encoder.eval()
|
| 162 |
+
|
| 163 |
+
self.encoder_layers = encoder_layers
|
| 164 |
+
self.latent_dim = latent_dim
|
| 165 |
+
self.decoder_ch = decoder_ch
|
| 166 |
+
self.decoder_num_res_blocks = decoder_num_res_blocks
|
| 167 |
+
embed_dim = self.encoder.embed_dim
|
| 168 |
+
self.feature_norms = nn.ModuleList(
|
| 169 |
+
nn.LayerNorm(embed_dim) for _ in range(encoder_layers)
|
| 170 |
+
)
|
| 171 |
+
branch_dim = latent_dim // 2
|
| 172 |
+
self.encoder_projection = nn.Conv2d(
|
| 173 |
+
embed_dim * encoder_layers, branch_dim, 1
|
| 174 |
+
)
|
| 175 |
+
self.semantic_projection = nn.Conv2d(embed_dim, branch_dim, 1)
|
| 176 |
+
self.decoder = Decoder(
|
| 177 |
+
z_channels=latent_dim,
|
| 178 |
+
ch=decoder_ch,
|
| 179 |
+
num_res_blocks=decoder_num_res_blocks,
|
| 180 |
+
)
|
| 181 |
+
self.register_buffer(
|
| 182 |
+
"dino_mean", torch.tensor(DINO_MEAN).view(1, 3, 1, 1), persistent=False
|
| 183 |
+
)
|
| 184 |
+
self.register_buffer(
|
| 185 |
+
"dino_std", torch.tensor(DINO_STD).view(1, 3, 1, 1), persistent=False
|
| 186 |
+
)
|
| 187 |
+
self.register_buffer(
|
| 188 |
+
"latent_mean", torch.zeros(1, latent_dim, 1, 1), persistent=True
|
| 189 |
+
)
|
| 190 |
+
self.register_buffer(
|
| 191 |
+
"latent_std", torch.ones(1, latent_dim, 1, 1), persistent=True
|
| 192 |
+
)
|
| 193 |
+
self.register_buffer(
|
| 194 |
+
"latent_stats_samples", torch.tensor(0, dtype=torch.int64), persistent=True
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
def train(self, mode: bool = True) -> SemanticVAE:
|
| 198 |
+
super().train(mode)
|
| 199 |
+
self.semantic_encoder.eval()
|
| 200 |
+
return self
|
| 201 |
+
|
| 202 |
+
def _dino_input(self, pixels: torch.Tensor) -> torch.Tensor:
|
| 203 |
+
pixels = F.interpolate(
|
| 204 |
+
pixels,
|
| 205 |
+
size=_dino_spatial_size(pixels.shape[-2:]),
|
| 206 |
+
mode="bicubic",
|
| 207 |
+
align_corners=False,
|
| 208 |
+
antialias=True,
|
| 209 |
+
)
|
| 210 |
+
return (pixels.add(1.0).mul(0.5) - self.dino_mean) / self.dino_std
|
| 211 |
+
|
| 212 |
+
@property
|
| 213 |
+
def has_latent_stats(self) -> bool:
|
| 214 |
+
return self.latent_stats_samples.item() > 0
|
| 215 |
+
|
| 216 |
+
def set_latent_stats(
|
| 217 |
+
self, mean: torch.Tensor, std: torch.Tensor, *, samples: int
|
| 218 |
+
) -> None:
|
| 219 |
+
self.latent_mean.copy_(mean.detach().view_as(self.latent_mean))
|
| 220 |
+
self.latent_std.copy_(std.detach().view_as(self.latent_std))
|
| 221 |
+
self.latent_stats_samples.fill_(samples)
|
| 222 |
+
|
| 223 |
+
def _require_latent_stats(self) -> None:
|
| 224 |
+
if not self.has_latent_stats:
|
| 225 |
+
raise RuntimeError(
|
| 226 |
+
"This model has no latent statistics. Use encode_raw/decode_raw, "
|
| 227 |
+
"or load a full .safetensors export containing latent statistics."
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
def normalize_latents(self, latent: torch.Tensor) -> torch.Tensor:
|
| 231 |
+
self._require_latent_stats()
|
| 232 |
+
return (latent - self.latent_mean.to(latent.dtype)) / self.latent_std.to(
|
| 233 |
+
latent.dtype
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
def denormalize_latents(self, latent: torch.Tensor) -> torch.Tensor:
|
| 237 |
+
self._require_latent_stats()
|
| 238 |
+
return latent * self.latent_std.to(latent.dtype) + self.latent_mean.to(
|
| 239 |
+
latent.dtype
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
def encode_raw(self, pixels: torch.Tensor) -> torch.Tensor:
|
| 243 |
+
"""Encode BCHW pixels to an unnormalized 16x-downsampled latent."""
|
| 244 |
+
dino_input = self._dino_input(pixels)
|
| 245 |
+
features = self.encoder.forward_intermediates(
|
| 246 |
+
dino_input,
|
| 247 |
+
indices=self.encoder_layers,
|
| 248 |
+
norm=False,
|
| 249 |
+
output_fmt="NCHW",
|
| 250 |
+
intermediates_only=True,
|
| 251 |
+
)
|
| 252 |
+
normalized = [
|
| 253 |
+
norm(feature.permute(0, 2, 3, 1))
|
| 254 |
+
.permute(0, 3, 1, 2)
|
| 255 |
+
.contiguous()
|
| 256 |
+
for feature, norm in zip(features, self.feature_norms, strict=True)
|
| 257 |
+
]
|
| 258 |
+
encoder_latent = self.encoder_projection(torch.cat(normalized, dim=1))
|
| 259 |
+
with torch.no_grad():
|
| 260 |
+
semantic_feature = self.semantic_encoder.forward_intermediates(
|
| 261 |
+
dino_input,
|
| 262 |
+
indices=1,
|
| 263 |
+
norm=True,
|
| 264 |
+
output_fmt="NCHW",
|
| 265 |
+
intermediates_only=True,
|
| 266 |
+
)[0]
|
| 267 |
+
semantic_latent = self.semantic_projection(semantic_feature)
|
| 268 |
+
return torch.cat((encoder_latent, semantic_latent), dim=1)
|
| 269 |
+
|
| 270 |
+
def encode(self, pixels: torch.Tensor) -> torch.Tensor:
|
| 271 |
+
"""Encode BCHW pixels to a normalized latent."""
|
| 272 |
+
return self.normalize_latents(self.encode_raw(pixels))
|
| 273 |
+
|
| 274 |
+
def decode_raw(
|
| 275 |
+
self,
|
| 276 |
+
latent: torch.Tensor,
|
| 277 |
+
output_size: tuple[int, int] | None = None,
|
| 278 |
+
) -> torch.Tensor:
|
| 279 |
+
"""Decode an unnormalized latent to pixels in [-1, 1]."""
|
| 280 |
+
reconstruction = torch.tanh(self.decoder(latent))
|
| 281 |
+
if output_size is not None and reconstruction.shape[-2:] != output_size:
|
| 282 |
+
reconstruction = F.interpolate(
|
| 283 |
+
reconstruction,
|
| 284 |
+
size=output_size,
|
| 285 |
+
mode="bicubic",
|
| 286 |
+
align_corners=False,
|
| 287 |
+
antialias=True,
|
| 288 |
+
)
|
| 289 |
+
return reconstruction
|
| 290 |
+
|
| 291 |
+
def decode(
|
| 292 |
+
self,
|
| 293 |
+
latent: torch.Tensor,
|
| 294 |
+
output_size: tuple[int, int] | None = None,
|
| 295 |
+
) -> torch.Tensor:
|
| 296 |
+
"""Decode a normalized BCHW latent to pixels in [-1, 1]."""
|
| 297 |
+
return self.decode_raw(self.denormalize_latents(latent), output_size)
|
| 298 |
+
|
| 299 |
+
def forward(self, pixels: torch.Tensor) -> torch.Tensor:
|
| 300 |
+
return self.decode(self.encode(pixels), output_size=pixels.shape[-2:])
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def load_vae(
|
| 304 |
+
checkpoint_path: str | Path,
|
| 305 |
+
*,
|
| 306 |
+
device: str | torch.device = "cpu",
|
| 307 |
+
dtype: torch.dtype = torch.float32,
|
| 308 |
+
pretrained: bool | None = None,
|
| 309 |
+
latent_stats_path: str | Path | None = None,
|
| 310 |
+
latent_dim: int = 64,
|
| 311 |
+
encoder_layers: int = 6,
|
| 312 |
+
decoder_ch: int = 128,
|
| 313 |
+
decoder_num_res_blocks: int = 2,
|
| 314 |
+
) -> SemanticVAE:
|
| 315 |
+
"""Load an eval-mode Semantic VAE from a full export or trainer checkpoint."""
|
| 316 |
+
checkpoint_path = Path(checkpoint_path)
|
| 317 |
+
is_safetensors = checkpoint_path.suffix == ".safetensors"
|
| 318 |
+
if is_safetensors:
|
| 319 |
+
with safe_open(checkpoint_path, framework="pt", device="cpu") as handle:
|
| 320 |
+
metadata = handle.metadata() or {}
|
| 321 |
+
if metadata.get("format") != SAFETENSORS_FORMAT:
|
| 322 |
+
raise RuntimeError(
|
| 323 |
+
f"Unsupported Semantic VAE safetensors format: "
|
| 324 |
+
f"{metadata.get('format')!r}"
|
| 325 |
+
)
|
| 326 |
+
latent_dim = int(metadata.get("latent_dim", latent_dim))
|
| 327 |
+
encoder_layers = int(metadata.get("encoder_layers", encoder_layers))
|
| 328 |
+
decoder_ch = int(metadata.get("decoder_ch", decoder_ch))
|
| 329 |
+
decoder_num_res_blocks = int(
|
| 330 |
+
metadata.get("decoder_num_res_blocks", decoder_num_res_blocks)
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
if pretrained is None:
|
| 334 |
+
pretrained = not is_safetensors
|
| 335 |
+
model = SemanticVAE(
|
| 336 |
+
pretrained=pretrained,
|
| 337 |
+
latent_dim=latent_dim,
|
| 338 |
+
encoder_layers=encoder_layers,
|
| 339 |
+
decoder_ch=decoder_ch,
|
| 340 |
+
decoder_num_res_blocks=decoder_num_res_blocks,
|
| 341 |
+
)
|
| 342 |
+
state: Mapping[str, torch.Tensor]
|
| 343 |
+
if is_safetensors:
|
| 344 |
+
state = load_file(checkpoint_path, device="cpu")
|
| 345 |
+
model.load_state_dict(state, strict=True)
|
| 346 |
+
else:
|
| 347 |
+
checkpoint = torch.load(
|
| 348 |
+
checkpoint_path, map_location="cpu", weights_only=True, mmap=True
|
| 349 |
+
)
|
| 350 |
+
if isinstance(checkpoint, Mapping) and "model" in checkpoint:
|
| 351 |
+
state = checkpoint["model"]
|
| 352 |
+
else:
|
| 353 |
+
state = checkpoint
|
| 354 |
+
|
| 355 |
+
incompatible = model.load_state_dict(state, strict=False)
|
| 356 |
+
if incompatible.unexpected_keys:
|
| 357 |
+
raise RuntimeError(
|
| 358 |
+
"Unexpected checkpoint keys: " + ", ".join(incompatible.unexpected_keys)
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
required_prefixes = (
|
| 362 |
+
"encoder.patch_embed.",
|
| 363 |
+
"feature_norms.",
|
| 364 |
+
"encoder_projection.",
|
| 365 |
+
"semantic_projection.",
|
| 366 |
+
"decoder.",
|
| 367 |
+
)
|
| 368 |
+
missing_learned = [
|
| 369 |
+
name
|
| 370 |
+
for name in incompatible.missing_keys
|
| 371 |
+
if name.startswith(required_prefixes)
|
| 372 |
+
]
|
| 373 |
+
if missing_learned:
|
| 374 |
+
raise RuntimeError(
|
| 375 |
+
"Checkpoint is missing learned parameters: "
|
| 376 |
+
+ ", ".join(missing_learned)
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
if latent_stats_path is None:
|
| 380 |
+
candidate = (
|
| 381 |
+
checkpoint_path.parent
|
| 382 |
+
/ "latent_stats"
|
| 383 |
+
/ f"semantic-{checkpoint_path.stem}.pt"
|
| 384 |
+
)
|
| 385 |
+
if candidate.is_file():
|
| 386 |
+
latent_stats_path = candidate
|
| 387 |
+
if latent_stats_path is not None:
|
| 388 |
+
stats = torch.load(
|
| 389 |
+
latent_stats_path, map_location="cpu", weights_only=True
|
| 390 |
+
)
|
| 391 |
+
model.set_latent_stats(
|
| 392 |
+
stats["mean"], stats["std"], samples=int(stats["samples"])
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
model.requires_grad_(False)
|
| 396 |
+
return model.to(device=device, dtype=dtype).eval()
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def _default_device() -> str:
|
| 400 |
+
if torch.cuda.is_available():
|
| 401 |
+
return "cuda"
|
| 402 |
+
if torch.backends.mps.is_available():
|
| 403 |
+
return "mps"
|
| 404 |
+
return "cpu"
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def main() -> None:
|
| 408 |
+
"""Reconstruct an image from its normalized latent."""
|
| 409 |
+
from PIL import Image, ImageOps
|
| 410 |
+
from torchvision.transforms.functional import pil_to_tensor, to_pil_image
|
| 411 |
+
|
| 412 |
+
parser = argparse.ArgumentParser(description=main.__doc__)
|
| 413 |
+
parser.add_argument(
|
| 414 |
+
"--checkpoint",
|
| 415 |
+
type=Path,
|
| 416 |
+
default=Path("semantic_vae_step_00050000.safetensors"),
|
| 417 |
+
)
|
| 418 |
+
parser.add_argument("input", type=Path)
|
| 419 |
+
parser.add_argument("--output", type=Path, default=Path("reconstructed.png"))
|
| 420 |
+
parser.add_argument("--size", type=int, default=1024)
|
| 421 |
+
parser.add_argument("--device", default=_default_device())
|
| 422 |
+
args = parser.parse_args()
|
| 423 |
+
|
| 424 |
+
with Image.open(args.input) as source:
|
| 425 |
+
source = source.convert("RGBA")
|
| 426 |
+
background = Image.new("RGBA", source.size, "white")
|
| 427 |
+
image = Image.alpha_composite(background, source).convert("RGB")
|
| 428 |
+
image = ImageOps.fit(
|
| 429 |
+
image,
|
| 430 |
+
(args.size, args.size),
|
| 431 |
+
method=Image.Resampling.LANCZOS,
|
| 432 |
+
)
|
| 433 |
+
pixels = pil_to_tensor(image).float().div(127.5).sub(1.0).unsqueeze(0)
|
| 434 |
+
|
| 435 |
+
model = load_vae(args.checkpoint, device=args.device)
|
| 436 |
+
pixels = pixels.to(args.device)
|
| 437 |
+
with torch.inference_mode():
|
| 438 |
+
latent = model.encode(pixels)
|
| 439 |
+
reconstruction = model.decode(latent, output_size=(args.size, args.size))
|
| 440 |
+
mse = F.mse_loss(reconstruction.float(), pixels.float())
|
| 441 |
+
psnr = 10.0 * torch.log10(mse.new_tensor(4.0) / mse)
|
| 442 |
+
|
| 443 |
+
result = reconstruction[0].float().cpu().add(1.0).mul(0.5).clamp(0.0, 1.0)
|
| 444 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 445 |
+
to_pil_image(result).save(args.output)
|
| 446 |
+
print(
|
| 447 |
+
f"Saved {args.output} from latent {tuple(latent.shape)} "
|
| 448 |
+
f"using {args.device}; PSNR: {psnr.item():.2f} dB"
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
if __name__ == "__main__":
|
| 452 |
+
main()
|
semantic_vae_step_00050000.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e24402fc26c5806b6ccac0baf575d77cd6dee1ac413b2d84bfb5c6c43333825c
|
| 3 |
+
size 859679660
|