File size: 13,701 Bytes
9a85a36 | 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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | """
Compare optim_tiled_decode vs optim_tiled_decode_cached_stats.
For each overlap_factor we:
1. Decode tiles independently (no blending) and measure MSE in overlap strips.
2. Decode with blending and measure global MSE vs a ground-truth full decode.
3. Save decoded images for visual inspection.
Usage (latent input):
python eval_code/eval_tiled_decode_overlap.py \
--latent_path latent_4k.pt \
--latent_size 128 \
--output_dir eval_code/tiled_decode_results
Usage (image input):
python eval_code/eval_tiled_decode_overlap.py \
--image_path my_image.png \
--output_dir eval_code/tiled_decode_results
"""
import argparse
import csv
import copy
import os
import sys
import time
import numpy as np
import torch
import torch.nn as nn
from PIL import Image
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from pipeline_sd_invsr import optim_tiled_decode
from utils import optim_tiled_decode_cached_stats
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Helpers
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def save_decoded_image(tensor: torch.Tensor, path: str):
img = (tensor / 2 + 0.5).clamp(0, 1)
img = img.squeeze(0).detach().cpu()
np_img = img.mul(255).byte().numpy()
np_img = np.transpose(np_img, (1, 2, 0))
Image.fromarray(np_img).save(path)
@torch.no_grad()
def decode_tiles_no_blend(vae, z, sample_size, tile_size, overlap_factor):
"""
Decode overlapping latent tiles independently (no blending).
Returns a list of (decoded_tile, pixel_i_start, pixel_j_start) tuples.
"""
overlap_size = int(tile_size * (1 - overlap_factor))
scale = sample_size // tile_size
tiles = []
for i in range(0, z.shape[2], overlap_size):
for j in range(0, z.shape[3], overlap_size):
tile = z[:, :, i: i + tile_size, j: j + tile_size]
if tile.shape[-2] != tile_size or tile.shape[-1] != tile_size:
continue
if vae.config.use_post_quant_conv:
tile = vae.post_quant_conv(tile)
decoded = vae.decoder(tile)
tiles.append((decoded, i * scale, j * scale))
return tiles, sample_size
def compute_overlap_mse(tiles, sample_size, overlap_factor):
"""
Given decoded tiles with their pixel positions, measure MSE in every
overlapping region between adjacent tiles.
"""
pixel_overlap = int(sample_size * overlap_factor)
if pixel_overlap == 0:
return 0.0
mse_values = []
n = len(tiles)
for a in range(n):
dec_a, ia, ja = tiles[a]
for b in range(a + 1, n):
dec_b, ib, jb = tiles[b]
h_a, w_a = dec_a.shape[2], dec_a.shape[3]
h_b, w_b = dec_b.shape[2], dec_b.shape[3]
# Vertical neighbour: b directly below a
if ja == jb and ib == ia + (sample_size - pixel_overlap):
strip_a = dec_a[:, :, -pixel_overlap:, :]
strip_b = dec_b[:, :, :pixel_overlap, :]
min_w = min(strip_a.shape[3], strip_b.shape[3])
mse = ((strip_a[:, :, :, :min_w] - strip_b[:, :, :, :min_w]) ** 2).mean().item()
mse_values.append(mse)
# Horizontal neighbour: b directly right of a
if ia == ib and jb == ja + (sample_size - pixel_overlap):
strip_a = dec_a[:, :, :, -pixel_overlap:]
strip_b = dec_b[:, :, :, :pixel_overlap]
min_h = min(strip_a.shape[2], strip_b.shape[2])
mse = ((strip_a[:, :, :min_h, :] - strip_b[:, :, :min_h, :]) ** 2).mean().item()
mse_values.append(mse)
return float(np.mean(mse_values)) if mse_values else 0.0
@torch.no_grad()
def decode_tiles_no_blend_cached_stats(vae, z, sample_size, tile_size, overlap_factor):
"""
Same as decode_tiles_no_blend but with CrossPatchGroupNorm cached stats.
We replicate the cached-stats setup from optim_tiled_decode_cached_stats,
then decode tiles individually (no blending) to measure raw overlap MSE.
"""
from utils import replace_groupnorm, CrossPatchGroupNorm
overlap_size = int(tile_size * (1 - overlap_factor))
scale = sample_size // tile_size
all_latent_tiles = []
positions = []
for i in range(0, z.shape[2], overlap_size):
for j in range(0, z.shape[3], overlap_size):
tile = z[:, :, i: i + tile_size, j: j + tile_size]
if tile.shape[-2] != tile_size or tile.shape[-1] != tile_size:
continue
all_latent_tiles.append(tile)
positions.append((i * scale, j * scale))
replace_groupnorm(vae)
norm_layers = [m for m in vae.modules() if isinstance(m, CrossPatchGroupNorm)]
for layer in norm_layers:
layer.clear_cache()
hooks = []
for layer in norm_layers:
def make_hook(l):
def hook(module, input, output):
l.compute_and_cache_stats(input[0])
return hook
hooks.append(layer.register_forward_hook(make_hook(layer)))
tiles = []
for idx, (tile, (pi, pj)) in enumerate(zip(all_latent_tiles, positions)):
if vae.config.use_post_quant_conv:
tile = vae.post_quant_conv(tile)
decoded = vae.decoder(tile)
if idx == 0:
for h in hooks:
h.remove()
tiles.append((decoded, pi, pj))
return tiles, sample_size
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Main
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def load_image_as_tensor(image_path: str, device: str):
"""Load an image and convert to (1, 3, H, W) tensor in [-1, 1]."""
img = Image.open(image_path).convert("RGB")
img_np = np.array(img).astype(np.float32) / 255.0
img_tensor = torch.from_numpy(img_np).permute(2, 0, 1).unsqueeze(0)
img_tensor = img_tensor * 2.0 - 1.0
return img_tensor.to(device)
def main():
parser = argparse.ArgumentParser(description="Compare tiled VAE decode functions")
parser.add_argument("--latent_path", type=str, default=None, help="Path to saved latent tensor")
parser.add_argument("--image_path", type=str, default=None, help="Path to input image (will be encoded to latent)")
parser.add_argument("--latent_size", type=int, default=128, help="Resize latent to this spatial size (H=W)")
parser.add_argument("--vae_model", type=str, default="stabilityai/sd-turbo", help="VAE source model")
parser.add_argument("--output_dir", type=str, default="eval_code/tiled_decode_results", help="Output directory")
args = parser.parse_args()
if args.latent_path is None and args.image_path is None:
parser.error("Provide either --latent_path or --image_path")
os.makedirs(args.output_dir, exist_ok=True)
device = "cuda" if torch.cuda.is_available() else "cpu"
# ββ Step 1: Load VAE ββββββββββββββββββββββββββββββββββββββββββββββββββ
print("Loading VAE...")
from diffusers import StableDiffusionPipeline
pipe = StableDiffusionPipeline.from_pretrained(args.vae_model, torch_dtype=torch.float32)
vae = pipe.vae.to(device).eval()
del pipe
sample_size = vae.tile_sample_min_size
tile_size = vae.tile_latent_min_size
print(f"VAE tile config: sample_size={sample_size}, tile_size={tile_size}")
# ββ Step 1b: Load or encode latent ββββββββββββββββββββββββββββββββββββ
if args.image_path is not None:
print(f"Loading image from {args.image_path} and encoding to latent...")
img_tensor = load_image_as_tensor(args.image_path, device)
print(f"Image tensor shape: {img_tensor.shape}")
vae.enable_tiling()
with torch.no_grad():
z = vae.encode(img_tensor).latent_dist.sample()
z = z * vae.config.scaling_factor
print(f"Encoded latent shape: {z.shape}")
vae.disable_tiling()
else:
print(f"Loading latent from {args.latent_path}...")
z = torch.load(args.latent_path, map_location=device).to(torch.float32)
if z.shape[2] != args.latent_size or z.shape[3] != args.latent_size:
z = torch.nn.functional.interpolate(z, size=(args.latent_size, args.latent_size), mode="bilinear")
print(f"Latent shape: {z.shape}")
# ββ Step 2: Ground truth decode βββββββββββββββββββββββββββββββββββββββ
print("Computing ground truth (full VAE decode)...")
try:
z_scaled = z / vae.config.scaling_factor
gt_image = vae.decode(z_scaled).sample
has_gt = True
save_decoded_image(gt_image, os.path.join(args.output_dir, "ground_truth.jpg"))
print("Ground truth saved.")
except RuntimeError as e:
print(f"Full decode OOM, skipping ground truth: {e}")
gt_image = None
has_gt = False
# ββ Step 3: Sweep overlap factors βββββββββββββββββββββββββββββββββββββ
overlap_factors = [0.03125, 0.0625, 0.125, 0.25, 0.5]
results = []
z_decode = z / vae.config.scaling_factor
for ovf in overlap_factors:
print(f"\n{'='*60}")
print(f"overlap_factor = {ovf}")
print(f"{'='*60}")
row = {"overlap_factor": ovf}
# ββ optim_tiled_decode (standard) βββββββββββββββββββββββββββββββββ
vae_standard = copy.deepcopy(vae)
t0 = time.time()
# Overlap MSE (no-blend tiles)
tiles_std, ss = decode_tiles_no_blend(vae_standard, z_decode, sample_size, tile_size, ovf)
overlap_mse_std = compute_overlap_mse(tiles_std, sample_size, ovf)
del tiles_std
torch.cuda.empty_cache()
# Blended decode
img_std = optim_tiled_decode(vae_standard, z_decode, sample_size, tile_size, ovf)
t_std = time.time() - t0
global_mse_std = ((img_std - gt_image) ** 2).mean().item() if has_gt else float("nan")
save_decoded_image(img_std, os.path.join(args.output_dir, f"standard_ovf{ovf}.jpg"))
del img_std, vae_standard
torch.cuda.empty_cache()
row["std_overlap_mse"] = overlap_mse_std
row["std_global_mse"] = global_mse_std
row["std_time_s"] = t_std
# ββ optim_tiled_decode_cached_stats βββββββββββββββββββββββββββββββ
vae_cached = copy.deepcopy(vae)
t0 = time.time()
# Overlap MSE (no-blend tiles, with cached stats)
tiles_cs, ss = decode_tiles_no_blend_cached_stats(vae_cached, z_decode, sample_size, tile_size, ovf)
overlap_mse_cs = compute_overlap_mse(tiles_cs, sample_size, ovf)
del tiles_cs
torch.cuda.empty_cache()
# Blended decode
vae_cached2 = copy.deepcopy(vae)
img_cs = optim_tiled_decode_cached_stats(vae_cached2, z_decode, sample_size, tile_size, ovf)
t_cs = time.time() - t0
global_mse_cs = ((img_cs - gt_image) ** 2).mean().item() if has_gt else float("nan")
save_decoded_image(img_cs, os.path.join(args.output_dir, f"cached_stats_ovf{ovf}.jpg"))
del img_cs, vae_cached, vae_cached2
torch.cuda.empty_cache()
row["cs_overlap_mse"] = overlap_mse_cs
row["cs_global_mse"] = global_mse_cs
row["cs_time_s"] = t_cs
results.append(row)
print(f" Standard | overlap_MSE={overlap_mse_std:.6f} global_MSE={global_mse_std:.6f} time={t_std:.2f}s")
print(f" CachedStats | overlap_MSE={overlap_mse_cs:.6f} global_MSE={global_mse_cs:.6f} time={t_cs:.2f}s")
# ββ Step 4: Output results ββββββββββββββββββββββββββββββββββββββββββββ
print(f"\n{'='*90}")
print(f"{'overlap':>10} | {'std_overlap_MSE':>16} {'cs_overlap_MSE':>16} | {'std_global_MSE':>16} {'cs_global_MSE':>16}")
print(f"{'-'*90}")
for r in results:
print(
f"{r['overlap_factor']:>10.5f} | "
f"{r['std_overlap_mse']:>16.6f} {r['cs_overlap_mse']:>16.6f} | "
f"{r['std_global_mse']:>16.6f} {r['cs_global_mse']:>16.6f}"
)
csv_path = os.path.join(args.output_dir, "results.csv")
with open(csv_path, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=[
"overlap_factor",
"std_overlap_mse", "std_global_mse", "std_time_s",
"cs_overlap_mse", "cs_global_mse", "cs_time_s",
])
writer.writeheader()
writer.writerows(results)
print(f"\nCSV saved to: {csv_path}")
print(f"Images saved to: {args.output_dir}/")
if __name__ == "__main__":
main()
|