""" 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()