Spaces:
Sleeping
Sleeping
File size: 14,222 Bytes
a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a a675e04 3187b3a | 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 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 | # app.py
# LaViSE: Latent-space Vision-Semantic Editing
# Gradio Space (Mode A): per-image latent delta optimization in SDXL VAE latent space
#
# Fixes applied:
# - Gradio 6: css passed to launch()
# - Better CPU/GPU handling + user-visible warning
# - SSR disabled (reduces asyncio shutdown noise)
# - Full UI renamed to match the paper (LaViSE terminology)
import os
import time
from dataclasses import dataclass
import numpy as np
import torch
import torch.nn.functional as F
import gradio as gr
from diffusers import AutoencoderKL
import open_clip
import kornia.augmentation as K
import kornia.filters as KF
# -------------------------
# Runtime config
# -------------------------
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32
# -------------------------
# Small helpers
# -------------------------
def set_seed(seed: int):
if seed is None or seed < 0:
return
torch.manual_seed(seed)
np.random.seed(seed)
def np_to_torch_image(img: np.ndarray) -> torch.Tensor:
"""
img: HWC uint8 or float
returns: (1,3,H,W) float in [0,1]
"""
if img is None:
raise ValueError("No image provided.")
if img.dtype != np.float32:
img = img.astype(np.float32)
if img.max() > 1.5:
img = img / 255.0
img = np.clip(img, 0.0, 1.0)
t = torch.from_numpy(img).permute(2, 0, 1).unsqueeze(0).to(device=DEVICE, dtype=DTYPE)
return t
def torch_to_np_image(t: torch.Tensor) -> np.ndarray:
"""
t: (1,3,H,W) float in [0,1]
returns: HWC uint8
"""
t = t.detach().float().clamp(0, 1).cpu()[0]
img = (t.permute(1, 2, 0).numpy() * 255.0 + 0.5).astype(np.uint8)
return img
def cosine_sim(a: torch.Tensor, b: torch.Tensor, eps=1e-8) -> torch.Tensor:
a = a / (a.norm(dim=-1, keepdim=True) + eps)
b = b / (b.norm(dim=-1, keepdim=True) + eps)
return (a * b).sum(dim=-1)
def trimmed_mean(x: torch.Tensor, trim: float) -> torch.Tensor:
x_sorted, _ = torch.sort(x)
n = x_sorted.numel()
lo = int(n * trim)
hi = int(n * (1.0 - trim))
if hi <= lo:
return x_sorted.mean()
return x_sorted[lo:hi].mean()
def total_variation(x: torch.Tensor) -> torch.Tensor:
tv_h = (x[:, :, 1:, :] - x[:, :, :-1, :]).abs().mean()
tv_w = (x[:, :, :, 1:] - x[:, :, :, :-1]).abs().mean()
return tv_h + tv_w
def lowpass_gaussian_latent(dz: torch.Tensor, kernel_size: int, sigma: float) -> torch.Tensor:
return KF.gaussian_blur2d(dz, (kernel_size, kernel_size), (sigma, sigma))
def lowpass_fft_latent(dz: torch.Tensor, keep_frac: float) -> torch.Tensor:
B, C, H, W = dz.shape
f = torch.fft.fft2(dz, dim=(-2, -1))
f = torch.fft.fftshift(f, dim=(-2, -1))
h_keep = max(2, int(H * keep_frac))
w_keep = max(2, int(W * keep_frac))
mask = torch.zeros((H, W), device=dz.device, dtype=torch.float32)
cy, cx = H // 2, W // 2
y0, y1 = cy - h_keep // 2, cy + h_keep // 2
x0, x1 = cx - w_keep // 2, cx + w_keep // 2
mask[y0:y1, x0:x1] = 1.0
mask = mask[None, None, :, :]
f = f * mask
f = torch.fft.ifftshift(f, dim=(-2, -1))
out = torch.fft.ifft2(f, dim=(-2, -1)).real
return out
# -------------------------
# Lazy-loaded models
# -------------------------
@dataclass
class LaViSEModels:
vae: AutoencoderKL
clip_model: torch.nn.Module
tokenizer: any
clip_res: int
_MODELS: LaViSEModels | None = None
def load_lavise_models(
clip_variant: str = "ViT-bigG-14",
clip_pretrained: str = "laion2b_s39b_b160k",
clip_res: int = 224,
) -> LaViSEModels:
global _MODELS
if _MODELS is not None:
return _MODELS
# SDXL VAE
vae = AutoencoderKL.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
subfolder="vae",
torch_dtype=DTYPE,
).to(DEVICE).eval()
for p in vae.parameters():
p.requires_grad_(False)
# OpenCLIP
clip_model, _, _ = open_clip.create_model_and_transforms(
clip_variant, pretrained=clip_pretrained
)
clip_model = clip_model.to(DEVICE).eval()
for p in clip_model.parameters():
p.requires_grad_(False)
tokenizer = open_clip.get_tokenizer(clip_variant)
_MODELS = LaViSEModels(vae=vae, clip_model=clip_model, tokenizer=tokenizer, clip_res=clip_res)
return _MODELS
def clip_text_embed(m: LaViSEModels, text: str) -> torch.Tensor:
tokens = m.tokenizer([text]).to(DEVICE)
with torch.no_grad():
return m.clip_model.encode_text(tokens)
def clip_image_embed(m: LaViSEModels, img_01: torch.Tensor) -> torch.Tensor:
"""
img_01: (B,3,clip_res,clip_res) in [0,1]
"""
mean = torch.tensor([0.48145466, 0.4578275, 0.40821073], device=img_01.device, dtype=img_01.dtype)[None, :, None, None]
std = torch.tensor([0.26862954, 0.26130258, 0.27577711], device=img_01.device, dtype=img_01.dtype)[None, :, None, None]
x = (img_01 - mean) / std
return m.clip_model.encode_image(x)
@torch.no_grad()
def sdxl_vae_encode(m: LaViSEModels, img_01: torch.Tensor) -> torch.Tensor:
x = img_01 * 2.0 - 1.0 # VAE expects [-1,1]
z = m.vae.encode(x).latent_dist.sample()
z = z * m.vae.config.scaling_factor
return z
def sdxl_vae_decode(m: LaViSEModels, z: torch.Tensor) -> torch.Tensor:
x = m.vae.decode(z / m.vae.config.scaling_factor).sample
return (x + 1.0) / 2.0
# -------------------------
# Core LaViSE editor (Mode A)
# -------------------------
def lavise_edit(
image_np: np.ndarray,
base_prompt: str,
target_prompt: str,
steps: int,
learning_rate: float,
views_per_step: int,
trim_ratio: float,
alpha_directional: float,
lowfreq_mode: str,
gaussian_sigma: float,
fft_keep: float,
lambda_clip: float,
lambda_identity: float,
lambda_latent: float,
lambda_tv: float,
dz_clamp: float,
seed: int,
progress=gr.Progress(track_tqdm=False),
):
if image_np is None:
raise gr.Error("Please upload an image.")
if not target_prompt or not target_prompt.strip():
raise gr.Error("Please enter a target prompt.")
if not base_prompt or not base_prompt.strip():
base_prompt = "a photo"
set_seed(seed)
m = load_lavise_models()
img0 = np_to_torch_image(image_np).clamp(0, 1) # (1,3,H,W)
z0 = sdxl_vae_encode(m, img0)
dz = torch.zeros_like(z0, requires_grad=True)
opt = torch.optim.Adam([dz], lr=float(learning_rate))
vT0 = clip_text_embed(m, base_prompt)
vT1 = clip_text_embed(m, target_prompt)
# anchor embedding for directional loss
with torch.no_grad():
img0_clip = F.interpolate(img0, size=(m.clip_res, m.clip_res), mode="bilinear", align_corners=False)
vI0 = clip_image_embed(m, img0_clip)
# Differentiable EOT augmentations (multi-crop)
augment = torch.nn.Sequential(
K.RandomResizedCrop((m.clip_res, m.clip_res), scale=(0.6, 1.0), ratio=(0.9, 1.1), p=1.0),
K.ColorJitter(0.05, 0.05, 0.05, 0.02, p=0.7),
K.RandomHorizontalFlip(p=0.5),
).to(DEVICE)
t0 = time.time()
for i in range(int(steps)):
z = z0 + dz
img = sdxl_vae_decode(m, z).clamp(0, 1)
# Multi-view CLIP loss (EOT)
per_view_losses = []
for _ in range(int(views_per_step)):
view = augment(img)
if torch.rand(()) < 0.3:
view = KF.gaussian_blur2d(view, (3, 3), (0.6, 0.6))
vI = clip_image_embed(m, view)
# absolute alignment
loss_abs = 1.0 - cosine_sim(vI, vT1)
# directional alignment
dI = vI - vI0
dT = vT1 - vT0
loss_dir = 1.0 - cosine_sim(dI, dT)
loss_clip = float(alpha_directional) * loss_dir + (1.0 - float(alpha_directional)) * loss_abs
per_view_losses.append(loss_clip.squeeze(0))
L_clip = trimmed_mean(torch.stack(per_view_losses), float(trim_ratio))
# Regularizers
L_id = (img - img0).abs().mean()
L_lat = dz.pow(2).mean()
L_tv = total_variation(img)
L = float(lambda_clip) * L_clip + float(lambda_identity) * L_id + float(lambda_latent) * L_lat + float(lambda_tv) * L_tv
opt.zero_grad(set_to_none=True)
L.backward()
opt.step()
# Low-frequency projection of dz
with torch.no_grad():
if lowfreq_mode == "gaussian":
dz.copy_(lowpass_gaussian_latent(dz, kernel_size=5, sigma=float(gaussian_sigma)))
elif lowfreq_mode == "fft":
dz.copy_(lowpass_fft_latent(dz, keep_frac=float(fft_keep)))
if dz_clamp and dz_clamp > 0:
dz.clamp_(-float(dz_clamp), float(dz_clamp))
if (i + 1) % max(1, steps // 20) == 0 or (i + 1) == steps:
progress((i + 1) / steps, desc=f"Optimizing Δz: step {i+1}/{steps}")
elapsed = time.time() - t0
with torch.no_grad():
out = sdxl_vae_decode(m, z0 + dz).clamp(0, 1)
info = (
f"Device: {DEVICE} | Time: {elapsed:.1f}s | Steps: {steps} | Views/Step: {views_per_step} | "
f"α_dir: {alpha_directional:.2f} | LowFreq: {lowfreq_mode} | "
f"L≈{float(L.item()):.4f} (clip {float(L_clip.item()):.4f}, id {float(L_id.item()):.4f})"
)
return torch_to_np_image(out), info
# -------------------------
# Gradio UI (Paper naming)
# -------------------------
CSS = """
#lavise-title {font-size: 1.5rem; font-weight: 800;}
.note {opacity: 0.85; font-size: 0.95rem;}
"""
with gr.Blocks(title="LaViSE — Latent-space Vision-Semantic Editing") as demo:
gr.Markdown(
"## LaViSE — Latent-space Vision-Semantic Editing\n"
"<div class='note'>Training-free, per-image latent optimization in SDXL VAE space "
"guided by multi-view CLIP + directional semantics.</div>",
elem_id="lavise-title",
)
if DEVICE != "cuda":
gr.Markdown(
"⚠️ **GPU not available (running on CPU).** "
"LaViSE will be very slow. For Hugging Face Spaces: enable **GPU hardware** in Settings.",
elem_classes=["note"],
)
with gr.Row():
inp = gr.Image(label="Input Image", type="numpy")
out = gr.Image(label="Edited Image (LaViSE Output)", type="numpy")
with gr.Row():
base_prompt = gr.Textbox(
label="Base Prompt (T₀) — describes the original image",
placeholder="e.g., 'a photo of a city street in daylight'",
lines=2,
)
target_prompt = gr.Textbox(
label="Target Prompt (T₁) — desired edit",
placeholder="e.g., 'a cinematic cyberpunk city street at night, neon lights, rain'",
lines=2,
)
with gr.Row():
steps = gr.Slider(50, 1200, value=400, step=10, label="Optimization Steps")
learning_rate = gr.Slider(1e-4, 5e-2, value=1e-2, step=1e-4, label="Learning Rate")
views_per_step = gr.Slider(4, 64, value=16, step=1, label="EOT Views per Step (Multi-Crop K)")
with gr.Accordion("LaViSE Stability Controls", open=True):
with gr.Row():
trim_ratio = gr.Slider(0.0, 0.3, value=0.1, step=0.01, label="Trimmed Mean Ratio")
alpha_directional = gr.Slider(0.0, 1.0, value=0.7, step=0.05, label="Directional Weight α (0=abs, 1=dir)")
with gr.Row():
lowfreq_mode = gr.Radio(["gaussian", "fft", "none"], value="gaussian", label="Low-Frequency Δz Projection")
gaussian_sigma = gr.Slider(0.3, 2.5, value=1.0, step=0.05, label="Gaussian σ (gaussian mode)")
fft_keep = gr.Slider(0.10, 0.60, value=0.25, step=0.01, label="FFT keep fraction (fft mode)")
with gr.Row():
lambda_clip = gr.Slider(0.1, 5.0, value=1.0, step=0.05, label="λ_clip")
lambda_identity = gr.Slider(0.0, 80.0, value=20.0, step=1.0, label="λ_identity (higher = preserve structure)")
lambda_latent = gr.Slider(0.0, 5.0, value=0.2, step=0.05, label="λ_latent")
lambda_tv = gr.Slider(0.0, 0.5, value=0.05, step=0.01, label="λ_tv")
with gr.Row():
dz_clamp = gr.Slider(0.0, 10.0, value=3.0, step=0.1, label="Δz clamp (0 disables)")
seed = gr.Slider(-1, 999999, value=-1, step=1, label="Seed (-1 random)")
btn = gr.Button("Run LaViSE Edit", variant="primary")
info = gr.Textbox(label="Run Log", lines=2)
def _run(
image_np, base, target, steps, lr, views, trim, alpha, lowfreq,
gs, fk, lclip, lid, llat, ltv, clamp, seed, progress=gr.Progress()
):
mode = lowfreq if lowfreq != "none" else "none"
return lavise_edit(
image_np=image_np,
base_prompt=base,
target_prompt=target,
steps=int(steps),
learning_rate=float(lr),
views_per_step=int(views),
trim_ratio=float(trim),
alpha_directional=float(alpha),
lowfreq_mode=mode,
gaussian_sigma=float(gs),
fft_keep=float(fk),
lambda_clip=float(lclip),
lambda_identity=float(lid),
lambda_latent=float(llat),
lambda_tv=float(ltv),
dz_clamp=float(clamp),
seed=int(seed),
progress=progress,
)
btn.click(
fn=_run,
inputs=[
inp, base_prompt, target_prompt, steps, learning_rate, views_per_step,
trim_ratio, alpha_directional, lowfreq_mode, gaussian_sigma, fft_keep,
lambda_clip, lambda_identity, lambda_latent, lambda_tv, dz_clamp, seed
],
outputs=[out, info],
)
gr.Markdown(
"**Recommended presets:**\n"
"- *Structure-preserving edit:* λ_identity=25–60, α=0.7, lowfreq=gaussian.\n"
"- *Stronger change:* λ_identity=10–20, α=0.4–0.6.\n"
"- *If artifacts appear:* increase views, enable lowfreq, reduce learning rate.",
elem_classes=["note"],
)
if __name__ == "__main__":
# queue() is fine; SSR off reduces asyncio shutdown oddities
demo.queue(max_size=16).launch(
css=CSS,
ssr_mode=False,
show_error=True,
) |