"""Simplified Hugging Face Space (Gradio + ZeroGPU) for `statedrive` Sana steering. Features: - Switch between Sana-0.6B (fast 28-block DiT, D=1152) and Sana-1.6B (higher-quality 20-block DiT, D=2240) sharing a single Gemma-2B text encoder, DC-AE VAE, and curved `SharedCore`. - 2D Spatial / Positional Sink Scrubbing (`sana_spatial_sinks.npz`) removing prompt-invariant patch-coordinate bias across semantic & readout blocks. - Bidirectional Stiefel + Orthogonal Procrustes Layer Bridges (`bridge_sana_06_to_16.npz`, `bridge_sana_16_to_06.npz`) lifting newly taught off-core directions across architectures. - Selective Spatial Object-Slot Steering (`slots_sana_*.npz`) allowing users to steer either the whole image or an isolated semantic object/region slot (or its background complement). - Order-independent Symmetric Löwdin pullback mixing by default & flicker-free baseline caching. Runs both on Hugging Face ZeroGPU (`zero-a10g`) and locally via: python app.py --host 127.0.0.1 --port 7860 """ from __future__ import annotations # `spaces` MUST be imported before `torch` / CUDA libraries on HF ZeroGPU. try: import spaces except ImportError: class _DummySpaces: def GPU(self, *args, **kwargs): def _dec(fn): return fn if args and callable(args[0]): return args[0] return _dec spaces = _DummySpaces() import argparse import copy import os from pathlib import Path import sys import time from typing import Any, Dict, List, Optional, Tuple import re ROOT = Path(__file__).resolve().parent if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) # Local dev convenience: auto-wire HF cache, local Sana-0.6B dir & sibling packages when present. if not os.environ.get("HF_HOME") and Path("/mnt/Data2/second_home/.cache/huggingface").is_dir(): os.environ["HF_HOME"] = "/mnt/Data2/second_home/.cache/huggingface" _REPO_PKGS = ROOT.parent.parent / "code" / "packages" if _REPO_PKGS.is_dir(): for _pkg in ("multiobserver", "unbundle", "statedrive"): _p = _REPO_PKGS / _pkg if _p.is_dir() and str(_p) not in sys.path: sys.path.insert(0, str(_p)) import gradio as gr import numpy as np from PIL import Image import torch from diffusers import SanaPipeline, SanaTransformer2DModel import statedrive as sd from atlas_runtime import CompactBridge, CompactSlotBank, load_spatial_sinks_into_views ARTIFACTS_DIR = ROOT / "artifacts" _LOCAL_SANA_06B = "/mnt/Data2/data/models/sana-600m-512" MODEL_ID_06B = os.environ.get( "STATEDRIVE_SANA_DIR", _LOCAL_SANA_06B if Path(_LOCAL_SANA_06B).is_dir() else "Efficient-Large-Model/Sana_600M_512px_diffusers", ) MODEL_ID_16B = "Efficient-Large-Model/Sana_1600M_512px_diffusers" MODEL_CHOICES = [ ("Sana-0.6B (Fast · 28-block DiT)", "sana_0_6b"), ("Sana-1.6B (Better Quality · 20-block DiT)", "sana_1_6b"), ] CAMERA_FILES = { "sana_0_6b": "sana-0.6b-512-camera-v2.pt", "sana_1_6b": "sana-1.6b-512-camera-v2.pt", } BRIDGE_FILES = { ("sana_0_6b", "sana_1_6b"): "bridge_sana_06_to_16.npz", ("sana_1_6b", "sana_0_6b"): "bridge_sana_16_to_06.npz", } SLOT_FILES = { "sana_0_6b": "slots_sana_0_6b.npz", "sana_1_6b": "slots_sana_1_6b.npz", } SLOT_CHOICES = [ ("Whole Image (Global Steering)", "all"), ("Building / Cabin / Architecture Slot", "building-architecture"), ("Water / Lake / Ocean Slot", "water-lake"), ("Trees / Forest / Foliage Slot", "trees-foliage"), ("Mountain / Cliff / Rock Slot", "mountain-cliff"), ("Sky / Clouds Slot", "sky-clouds"), ("Person / Subject Slot", "person-subject"), ("Animal / Creature Slot", "animal-creature"), ("Vehicle / Boat Slot", "vehicle-boat"), ] DEFAULT_MODEL = "sana_0_6b" DEFAULT_STEPS = 14 DEFAULT_STYLE_STRENGTH = 1.3 DEFAULT_DIAL_STRENGTH = 1.0 MIN_DESCRIPTION_WORDS = 3 def _word_count(text: str) -> int: """Count word-like tokens; `stained-glass` and `80s` each count as one word.""" return len( [w for w in str(text or "").split() if re.search(r"[A-Za-z0-9]", w)] ) def _require_style_description(text: str) -> str: """Reject single/double-word style descriptions before spending GPU time.""" clean = str(text or "").strip() n_words = _word_count(clean) if n_words < MIN_DESCRIPTION_WORDS: raise gr.Error( f"Describe the style in at least {MIN_DESCRIPTION_WORDS} words " f"(got {n_words}): one or two words is not enough to separate the " f"style from the subject. Try e.g. 'Gothic stained glass with lead " f"cames and jewel tones'." ) return clean # --------------------------------------------------------------------------- # Load calibration artifacts, 2D spatial sinks, Procrustes bridges & slot banks on CPU # --------------------------------------------------------------------------- print("[startup] Loading statedrive shared core, Sana layer views & cross-atlas...", flush=True) BASE_CORE = sd.SharedCore.load(ARTIFACTS_DIR / "canonical_image_core.pt", device="cpu") BASE_VIEWS_MAP: Dict[str, sd.ModelLayerViews] = { k: sd.ModelLayerViews.load(ARTIFACTS_DIR / fn, device="cpu") for k, fn in CAMERA_FILES.items() if (ARTIFACTS_DIR / fn).is_file() } _SINK_COUNTS = load_spatial_sinks_into_views(ARTIFACTS_DIR / "sana_spatial_sinks.npz", BASE_VIEWS_MAP) BRIDGES: Dict[Tuple[str, str], CompactBridge] = { pair: CompactBridge(ARTIFACTS_DIR / fn) for pair, fn in BRIDGE_FILES.items() if (ARTIFACTS_DIR / fn).is_file() } SLOT_BANKS: Dict[str, CompactSlotBank] = { k: CompactSlotBank(ARTIFACTS_DIR / fn) for k, fn in SLOT_FILES.items() if (ARTIFACTS_DIR / fn).is_file() } PERCEIVER = ( sd.ImagePerceiver.load(ARTIFACTS_DIR / "image_ref_perceiver.pt", device="cpu") if (ARTIFACTS_DIR / "image_ref_perceiver.pt").is_file() else None ) _presets_path = ARTIFACTS_DIR / "image_style_presets.pt" if _presets_path.is_file(): _guard_blob = torch.load(_presets_path, map_location="cpu", weights_only=False) GUARD = sd.FlowManifoldGuard( base_radius_max=float(_guard_blob["base_radius_max"]), logp_floor=float(_guard_blob["logp_floor"]), ) else: GUARD = sd.FlowManifoldGuard.analytical(BASE_CORE.d_latent, q=0.995) ADAPTERS = {k: sd.get_adapter(k) for k in BASE_VIEWS_MAP} BASE_STYLES: List[str] = sorted(BASE_CORE.directions.keys()) BASE_DIALS: List[str] = list(BASE_CORE.dials.names) if BASE_CORE.dials is not None else [] DEFAULT_SELECTED_STYLES: List[str] = ["watercolor"] if "watercolor" in BASE_STYLES else BASE_STYLES[:1] MODEL_DIAG: Dict[str, Dict[str, Any]] = {} for _mk, _vw in BASE_VIEWS_MAP.items(): _g = _vw.layer_geometry(BASE_CORE) _sem_l, _sem_r, _ = _vw.select_layers(BASE_CORE, goal="semantic", max_steer_layers=4) _look_l, _, _ = _vw.select_layers(BASE_CORE, goal="look_keep_shapes", max_steer_layers=2) MODEL_DIAG[_mk] = { "geom": _g, "sem_layers": list(_sem_l), "sem_read": int(_sem_r), "look_layers": list(_look_l), "sink_layers": int(_SINK_COUNTS.get(_mk, 0)), } print( f"[startup] {_mk}: peak=L{_g['semantic_peak_layer']} " f"(R2={_g['style_r2'][_g['semantic_peak_layer']]:.3f}), " f"sem={_sem_l}, look={_look_l}, sink_scrubbed_layers={_SINK_COUNTS.get(_mk, 0)}", flush=True, ) # --------------------------------------------------------------------------- # Load Sana-0.6B + Sana-1.6B sharing Gemma-2B text encoder & DC-AE VAE # --------------------------------------------------------------------------- _USE_CUDA = torch.cuda.is_available() _PIPE_DTYPE = torch.bfloat16 if _USE_CUDA else torch.float32 def _load_pretrained_prefer_cache(cls: Any, repo_or_dir: str, **kwargs: Any) -> Any: if Path(repo_or_dir).is_dir(): return cls.from_pretrained(repo_or_dir, local_files_only=True, **kwargs) try: return cls.from_pretrained(repo_or_dir, local_files_only=True, **kwargs) except Exception: return cls.from_pretrained(repo_or_dir, **kwargs) print(f"[startup] Loading Sana-0.6B + Sana-1.6B pipelines (dtype={_PIPE_DTYPE})...", flush=True) _t_load = time.time() _PIPE_06B = _load_pretrained_prefer_cache( SanaPipeline, MODEL_ID_06B, variant="fp16", torch_dtype=_PIPE_DTYPE, ) if _USE_CUDA: _PIPE_06B.to("cuda") _PIPE_06B.set_progress_bar_config(disable=True) PIPES: Dict[str, Any] = {"sana_0_6b": _PIPE_06B} if "sana_1_6b" in BASE_VIEWS_MAP: _TR_16B = _load_pretrained_prefer_cache( SanaTransformer2DModel, MODEL_ID_16B, subfolder="transformer", variant="fp16", torch_dtype=_PIPE_DTYPE, ) if _USE_CUDA: _TR_16B.to("cuda") _PIPE_16B = SanaPipeline( tokenizer=_PIPE_06B.tokenizer, text_encoder=_PIPE_06B.text_encoder, vae=_PIPE_06B.vae, transformer=_TR_16B, scheduler=copy.deepcopy(_PIPE_06B.scheduler), ) _PIPE_16B.set_progress_bar_config(disable=True) PIPES["sana_1_6b"] = _PIPE_16B print( f"[startup] Loaded models {list(PIPES.keys())} in {time.time() - _t_load:.1f}s " f"(bridges={len(BRIDGES)}, slot_banks={list(SLOT_BANKS.keys())}).", flush=True, ) # --------------------------------------------------------------------------- # Session-isolated replay + Procrustes cross-model transfer helpers # --------------------------------------------------------------------------- def _serialize_direction(cd: sd.ChartDirection) -> Dict[str, Any]: return { "name": str(cd.name), "label": str(cd.label), "category": str(cd.category), "delta_u": np.asarray(cd.delta_u, dtype=np.float32), "mu0_s": np.asarray(cd.mu0_s, dtype=np.float64), "mu1_s": np.asarray(cd.mu1_s, dtype=np.float64), "cov0_s": np.asarray(cd.cov0_s, dtype=np.float64) if cd.cov0_s is not None else None, "cov1_s": np.asarray(cd.cov1_s, dtype=np.float64) if cd.cov1_s is not None else None, "readout_w": np.asarray(cd.readout_w, dtype=np.float64) if cd.readout_w is not None else None, "pairs": int(cd.pairs), } def _deserialize_direction(blob: Dict[str, Any]) -> sd.ChartDirection: return sd.ChartDirection( name=blob["name"], label=blob["label"], category=blob.get("category", "custom"), delta_u=np.asarray(blob["delta_u"], dtype=np.float32), mu0_s=np.asarray(blob["mu0_s"], dtype=np.float64), mu1_s=np.asarray(blob["mu1_s"], dtype=np.float64), cov0_s=np.asarray(blob["cov0_s"], dtype=np.float64) if blob.get("cov0_s") is not None else None, cov1_s=np.asarray(blob["cov1_s"], dtype=np.float64) if blob.get("cov1_s") is not None else None, readout_w=np.asarray(blob["readout_w"], dtype=np.float64) if blob.get("readout_w") is not None else None, pairs=int(blob.get("pairs", 8)), ) def _extract_rank1_views_delta( A_before: Dict[int, np.ndarray], mu_before: Dict[int, np.ndarray], views_after: sd.ModelLayerViews, ) -> Tuple[Optional[np.ndarray], Dict[int, np.ndarray], Dict[int, np.ndarray]]: diffs: Dict[int, np.ndarray] = {} mu_deltas: Dict[int, np.ndarray] = {} best_norm = 0.0 best_row: Optional[np.ndarray] = None for l, A_old in A_before.items(): diff = views_after.A_layers[l] - A_old diffs[l] = diff mu_deltas[l] = (views_after.mu_layers[l] - mu_before[l]).astype(np.float32) row_norms = np.linalg.norm(diff, axis=1) idx = int(np.argmax(row_norms)) nrm = float(row_norms[idx]) if nrm > best_norm: best_norm = nrm best_row = diff[idx] if best_row is None or best_norm <= 1e-12: return None, {}, mu_deltas v_unit = (best_row / best_norm).astype(np.float64) u_by_layer = {l: (diff @ v_unit).astype(np.float32) for l, diff in diffs.items()} return v_unit, u_by_layer, mu_deltas def _build_session_core_and_views( model_key: str, custom_dirs: Optional[List[Dict[str, Any]]], ) -> Tuple[sd.SharedCore, sd.ModelLayerViews, List[str]]: """Shallow-copy base core & views; replay exact teacher updates or Stiefel-Procrustes cross-model lifts.""" mkey = model_key if model_key in BASE_VIEWS_MAP else DEFAULT_MODEL base_views = BASE_VIEWS_MAP[mkey] core_w = copy.copy(BASE_CORE) core_w.directions = dict(BASE_CORE.directions) views_w = copy.copy(base_views) views_w.A_layers = {int(l): a.copy() for l, a in base_views.A_layers.items()} views_w.mu_layers = {int(l): m.copy() for l, m in base_views.mu_layers.items()} procrustes_lifted: List[str] = [] for entry in custom_dirs or []: cd = _deserialize_direction(entry["cd"]) core_w.register_direction(cd) teacher = entry.get("teacher_model") v_unit = entry.get("v_unit") u_by_layer = entry.get("u_by_layer") or {} mu_deltas = entry.get("mu_deltas") or {} if teacher == mkey: if v_unit is not None: v64 = np.asarray(v_unit, dtype=np.float64) for l, u_vec in u_by_layer.items(): il = int(l) if il in views_w.A_layers: views_w.A_layers[il] = views_w.A_layers[il] + np.outer( np.asarray(u_vec, dtype=np.float64), v64 ) for l, md in mu_deltas.items(): il = int(l) if il in views_w.mu_layers: views_w.mu_layers[il] = views_w.mu_layers[il] + np.asarray(md, dtype=np.float64) elif teacher in BASE_VIEWS_MAP and (teacher, mkey) in BRIDGES: ok = BRIDGES[(teacher, mkey)].transfer_rank1_entry( core_w, BASE_VIEWS_MAP[teacher], views_w, cd, v_unit, u_by_layer, ) if ok: procrustes_lifted.append(cd.name) return core_w, views_w, procrustes_lifted # --------------------------------------------------------------------------- # GPU Functions (wired directly to Gradio events for HF ZeroGPU) # --------------------------------------------------------------------------- @spaces.GPU(duration=45) def generate_comparison_gpu( model_key: str, prompt: str, seed: float, selected_styles: List[str], selected_dials: List[str], strengths: Dict[str, float], custom_dirs: List[Dict[str, Any]], regime: str, ortho_mode: str, target_slot: str, invert_slot: bool, baseline_cache: Optional[Dict[str, Any]], ) -> Tuple[Image.Image, str, Dict[str, Any]]: prompt_clean = str(prompt or "").strip() if not prompt_clean: raise gr.Error("Please enter a prompt.") t0 = time.time() dev = "cuda" if torch.cuda.is_available() else "cpu" mkey = model_key if model_key in PIPES else DEFAULT_MODEL seed_int = int(seed) steps = DEFAULT_STEPS pipe = PIPES[mkey] adapter = ADAPTERS[mkey] diag = MODEL_DIAG[mkey] core_w, views_w, lifted_names = _build_session_core_and_views(mkey, custom_dirs) if regime == "semantic_all": chosen_layers = list(diag["sem_layers"]) start_f, ramp_f = 0.0, 0.0 elif regime == "look_keep_shapes": chosen_layers = list(diag["look_layers"]) start_f, ramp_f = 0.65, 0.15 else: chosen_layers = list(diag["sem_layers"]) start_f, ramp_f = 0.35, 0.15 sched = sd.late_step_schedule(steps, start_frac=start_f, ramp_frac=ramp_f) if start_f > 0 else None styles_sel = list(selected_styles or []) dials_sel = [d for d in (selected_dials or []) if d not in styles_sel] selected_names = styles_sel + dials_sel strengths_map = dict(strengths or {}) use_ortho = ortho_mode if ortho_mode in ("auto", "symmetric", "sequential", "none") else "auto" chart_axes = [] for idx, nm in enumerate(selected_names): default_val = DEFAULT_DIAL_STRENGTH if nm in BASE_DIALS and nm not in core_w.directions else DEFAULT_STYLE_STRENGTH val = float(strengths_map.get(nm, default_val)) if abs(val) > 1e-6: chart_axes.append( sd.ChartAxis( direction=nm, layers=chosen_layers, strength=val, priority=(len(selected_names) - idx) if use_ortho == "sequential" else 0, schedule=sched, floor=False, ) ) slot_note = "global" if chart_axes: plan = sd.ChartPlan( axes=chart_axes, pins=[], protect_content=True, ortho_mode=use_ortho, ortho_metric="pullback", guard=GUARD, feedback_regime=sd.FeedbackRegime.CLOSED_LOOP, floor=False, ) hook = sd.compile_chart_plan(core_w, views_w, plan, device=dev) oinfo = getattr(hook, "ortho_info", {"mode": "none", "max_abs_cos": 0.0}) if target_slot and target_slot != "all" and mkey in SLOT_BANKS: hook = SLOT_BANKS[mkey].wrap_edit_hook(hook, target_slot, invert=bool(invert_slot)) slot_note = f"outside `{target_slot}`" if invert_slot else f"slot `{target_slot}`" else: hook = None oinfo = {"mode": "none", "max_abs_cos": 0.0} cache_key = (mkey, prompt_clean, seed_int, steps) reused_baseline = ( isinstance(baseline_cache, dict) and baseline_cache.get("key") == cache_key and isinstance(baseline_cache.get("img"), Image.Image) ) if reused_baseline: dry_img = baseline_cache["img"] else: dry_img = adapter.generate_image( pipe, prompt_clean, edit_fn=None, device=dev, num_inference_steps=steps, seed=seed_int, ) if hook is not None: steered_img = adapter.generate_image( pipe, prompt_clean, edit_fn=hook, device=dev, num_inference_steps=steps, seed=seed_int, ) else: steered_img = dry_img.copy() edge_r = float(sd.sobel_edge_correlation(np.asarray(dry_img), np.asarray(steered_img))) elapsed = time.time() - t0 if chart_axes: mix_desc = " + ".join(f"`{ax.direction}` ({ax.strength:+.1f})" for ax in chart_axes) else: mix_desc = "`(all directions disabled / zero strength — unsteered)`" base_note = " · baseline reused" if reused_baseline else "" active_lifted = [nm for nm in selected_names if nm in lifted_names] bridge_note = f" · Procrustes-lifted: `{active_lifted}`" if active_lifted else "" model_short = "Sana-1.6B" if mkey == "sana_1_6b" else "Sana-0.6B" telemetry = ( f"**Model:** `{model_short}` · **Region:** {slot_note} · **Active Mix:** {mix_desc} \n" f"**Sobel Shape-Lock:** `r = {edge_r:.3f}` · " f"**Layers:** `{chosen_layers}` (2D sinks scrubbed) · " f"**Pullback Mixing:** `{oinfo['mode']}` (`max |cos_g| = {oinfo['max_abs_cos']:.3f}`) · " f"**Time:** `{elapsed:.1f}s`{base_note}{bridge_note}" ) return steered_img, telemetry, {"key": cache_key, "img": dry_img, "reused": reused_baseline} @spaces.GPU(duration=65) def teach_direction_gpu( model_key: str, name: str, target: str, neutral: str, custom_dirs: List[Dict[str, Any]], strengths: Dict[str, float], ) -> Tuple[List[Dict[str, Any]], Dict[str, float], str, str]: nm_raw = str(name or "").strip() tg_raw = str(target or "").strip() neu_raw = str(neutral or "").strip() if not nm_raw or not tg_raw: raise gr.Error("Enter both a Style Name and a Target Style Description.") tg_raw = _require_style_description(tg_raw) t0 = time.time() dev = "cuda" if torch.cuda.is_available() else "cpu" mkey = model_key if model_key in PIPES else DEFAULT_MODEL pipe = PIPES[mkey] adapter = ADAPTERS[mkey] core_w, views_w, _ = _build_session_core_and_views(mkey, custom_dirs) A_before = {l: a.copy() for l, a in views_w.A_layers.items()} mu_before = {l: m.copy() for l, m in views_w.mu_layers.items()} perceiver_dev = PERCEIVER.to(dev).eval() if PERCEIVER is not None else None cd = sd.teach_image_direction( core_w, views_w, adapter, pipe, name=nm_raw, target=tg_raw, neutral=neu_raw, guard=GUARD, perceiver=perceiver_dev, device=dev, ) v_unit, u_by_layer, mu_deltas = _extract_rank1_views_delta(A_before, mu_before, views_w) entry = { "name": cd.name, "label": nm_raw, "target": tg_raw, "neutral": neu_raw, "teacher_model": mkey, "cd": _serialize_direction(cd), "v_unit": v_unit, "u_by_layer": u_by_layer, "mu_deltas": mu_deltas, } next_custom = [e for e in (custom_dirs or []) if e["name"] != cd.name] + [entry] next_strengths = dict(strengths or {}) next_strengths[cd.name] = DEFAULT_STYLE_STRENGTH norm_du = float(np.linalg.norm(cd.delta_u)) elapsed = time.time() - t0 teacher_short = "Sana-1.6B" if mkey == "sana_1_6b" else "Sana-0.6B" other_short = "Sana-0.6B" if mkey == "sana_1_6b" else "Sana-1.6B" status_md = ( f"Created & enabled **`{cd.name}`** (`||Δu|| = {norm_du:.2f}`) on `{teacher_short}` in `{elapsed:.1f}s` " f"*(lifts full-fiber to `{other_short}` via Stiefel + Orthogonal Procrustes bridge)*. " f"Adjust its strength below or click **Generate Comparison** to test it." ) return next_custom, next_strengths, cd.name, status_md # --------------------------------------------------------------------------- # Lightweight CPU UI state callbacks # --------------------------------------------------------------------------- def _sync_dry_image(cache: Optional[Dict[str, Any]]): if not isinstance(cache, dict) or cache.get("reused"): return gr.skip() return cache.get("img") def _format_diag_md(model_key: str) -> str: mkey = model_key if model_key in MODEL_DIAG else DEFAULT_MODEL d = MODEL_DIAG[mkey] vw = BASE_VIEWS_MAP[mkey] pk = d["geom"]["semantic_peak_layer"] label = "Sana-1.6B" if mkey == "sana_1_6b" else "Sana-0.6B" other = "sana_0_6b" if mkey == "sana_1_6b" else "sana_1_6b" br_str = "" if (other, mkey) in BRIDGES: u_c, p_c, _ = BRIDGES[(other, mkey)].mean_cosines(d["sem_layers"]) br_str = f" · `Procrustes bridge cos = {p_c:.3f}` *(vs unrotated `{u_c:+.3f}`)*" return ( f"**{label} Intrinsic Diagnostics:** " f"`chart_read_layer = L{vw.chart_read_layer}` · " f"`semantic_peak = L{pk}` (`R² = {d['geom']['style_r2'][pk]:.3f}`) · " f"`semantic_layers = {d['sem_layers']}` · " f"`2D_sinks_scrubbed = {d['sink_layers']} blocks`{br_str}" ) def _validate_teach_inputs(name: str, target: str) -> None: if not str(name or "").strip() or not str(target or "").strip(): raise gr.Error("Enter both a Style Name and a Target Style Description.") _require_style_description(target) def _apply_created_direction_ui( custom_dirs: List[Dict[str, Any]], selected_styles: List[str], created_slug: str, rev: float, rgen: float, ): custom_names = [e["name"] for e in (custom_dirs or []) if e["name"] not in BASE_STYLES] all_choices = BASE_STYLES + custom_names cur_sel = list(selected_styles or []) already_selected = bool(created_slug and created_slug in cur_sel) if created_slug and not already_selected: cur_sel.append(created_slug) return ( gr.update(choices=all_choices, value=cur_sel), int(rev) + 1, int(rgen) + (1 if already_selected else 0), "", "", ) def _disable_all_directions(): return [], [] def _reset_strengths( selected_styles: List[str], selected_dials: List[str], strengths: Dict[str, float], rev: float, reset_gen: float, ): nxt = dict(strengths or {}) for s in selected_styles or []: nxt[s] = DEFAULT_STYLE_STRENGTH for d in selected_dials or []: nxt[d] = DEFAULT_DIAL_STRENGTH return nxt, int(rev) + 1, int(reset_gen) + 1 # --------------------------------------------------------------------------- # Gradio Interface # --------------------------------------------------------------------------- CSS = """ .compact-dir-row { align-items: center !important; gap: 8px !important; } .disable-x-btn { min-width: 38px !important; max-width: 44px !important; } """ with gr.Blocks() as demo: custom_dirs_state = gr.State([]) strengths_state = gr.State({nm: DEFAULT_STYLE_STRENGTH for nm in DEFAULT_SELECTED_STYLES}) baseline_cache_state = gr.State(None) last_created_slug = gr.State("") render_rev = gr.Number(value=0, visible=False) reset_gen = gr.Number(value=0, visible=False) gr.Markdown( """ # `statedrive` · Curved Shared-Manifold & Procrustes Slot Steering (`Sana-0.6B` / `Sana-1.6B`) Toggle and scale calibrated style & photometric directions with **2D positional sink scrubbing**, steer either the **whole image** or a **specific object/region slot** (`cabin`, `water`, `trees`, `sky`, ...), and teach new styles that lift across **Sana-0.6B ↔ Sana-1.6B** via **Stiefel + Orthogonal Procrustes** bridges. [GitHub Repository](https://github.com/robertdbak/multiview) """ ) with gr.Row(): prompt_in = gr.Textbox( label="Prompt", value="a wooden cabin beside a calm mountain lake with pine trees", scale=5, ) model_in = gr.Dropdown( choices=[c for c in MODEL_CHOICES if c[1] in PIPES], value=DEFAULT_MODEL, label="Model", interactive=True, scale=2, ) seed_in = gr.Number(label="Seed", value=42, precision=0, minimum=0, maximum=99999, scale=1) gen_btn = gr.Button("Generate Comparison", variant="primary", scale=2) with gr.Row(): dry_out = gr.Image(label="Unsteered Baseline", type="pil") steered_out = gr.Image(label="Steered Output", type="pil") telemetry_out = gr.Markdown( "Pick or create directions below, choose Whole Image or a Spatial Object Slot, and click **Generate Comparison**." ) gr.Markdown("---") with gr.Row(): with gr.Column(scale=3): gr.Markdown("### 1. Toggle & Scale Directions") selected_styles = gr.CheckboxGroup( choices=BASE_STYLES, value=DEFAULT_SELECTED_STYLES, label="Style Directions (check to enable, uncheck to disable)", ) selected_dials = gr.CheckboxGroup( choices=BASE_DIALS, value=[], label="Photometric Dials (optional)", ) with gr.Row(): slot_in = gr.Dropdown( choices=SLOT_CHOICES, value="all", label="Target Region / Object Slot (Procrustes-aligned patch simplex)", interactive=True, scale=3, ) invert_slot_in = gr.Checkbox( value=False, label="Invert Slot (steer background only)", interactive=True, scale=2, ) with gr.Row(): disable_all_btn = gr.Button("Disable All", size="sm") reset_str_btn = gr.Button("Reset Strengths", size="sm") gr.Markdown("#### Active Direction Strengths") @gr.render( inputs=[selected_styles, selected_dials, strengths_state, render_rev, reset_gen], triggers=[ selected_styles.change, selected_dials.change, render_rev.change, demo.load, ], ) def render_active_sliders(styles, dials, cur_strengths, _rev, rgen): styles_list = list(styles or []) dials_list = [d for d in (dials or []) if d not in styles_list] active = styles_list + dials_list if not active: gr.Markdown( "*All directions disabled — generation will output the unsteered baseline.*" ) return s_map = dict(cur_strengths or {}) for nm in active: default_v = ( DEFAULT_DIAL_STRENGTH if nm in BASE_DIALS and nm not in styles_list else DEFAULT_STYLE_STRENGTH ) val = float(s_map.get(nm, default_v)) val = max(-2.0, min(2.0, val)) with gr.Row(elem_classes=["compact-dir-row"]): slider = gr.Slider( minimum=-2.0, maximum=2.0, step=0.1, value=val, label=f"{nm}", interactive=True, key=f"slider-{nm}-{int(rgen)}", preserved_by_key=["value", "interactive"], scale=8, ) off_btn = gr.Button( "✕", size="sm", interactive=True, elem_classes=["disable-x-btn"], key=f"disable-{nm}-{int(rgen)}", scale=0, ) def _on_slider_change(new_val, cur_dict, dir_name=nm): nxt = dict(cur_dict or {}) nxt[dir_name] = float(new_val) return nxt def _on_disable_click(cur_styles, cur_dials, dir_name=nm): return ( [x for x in (cur_styles or []) if x != dir_name], [x for x in (cur_dials or []) if x != dir_name], ) slider.change( fn=_on_slider_change, inputs=[slider, strengths_state], outputs=[strengths_state], queue=False, show_progress="hidden", ) off_btn.click( fn=_on_disable_click, inputs=[selected_styles, selected_dials], outputs=[selected_styles, selected_dials], queue=False, show_progress="hidden", ) with gr.Column(scale=2): gr.Markdown("### 2. Create a New Style Direction") gr.Markdown( "*Self-taught on sink-scrubbed CFG trajectories across 8 subjects. " "Lifts full-fiber between Sana-0.6B and Sana-1.6B via Stiefel + Orthogonal Procrustes bridges.*" ) teach_name = gr.Textbox( label="New Style Name", placeholder="e.g. ukiyo-e, stained-glass, claymation", ) teach_target = gr.Textbox( label=f"Target Style Description (min {MIN_DESCRIPTION_WORDS} words)", placeholder="e.g. Japanese ukiyo-e woodblock print by Hokusai, bold ink outlines and flat mineral pigments", lines=3, ) teach_neutral = gr.Textbox( label="Neutral Baseline (optional)", value="photograph", ) teach_btn = gr.Button("Create & Enable Style (~12s on GPU)", variant="secondary") teach_status = gr.Markdown("") with gr.Accordion("Steering Options", open=False): ortho_in = gr.Dropdown( choices=[ ("Auto (Symmetric Löwdin when overlapping · recommended)", "auto"), ("Symmetric (Löwdin Polar — equal weight)", "symmetric"), ("Sequential (Priority Gram-Schmidt — first wins)", "sequential"), ("None (Raw Chart Sum)", "none"), ], value="auto", label="Multi-Axis Mixing", interactive=True, ) regime_in = gr.Radio( choices=[ ("Semantic Core + Late Steps (clean style, shapes locked)", "semantic_late"), ("Semantic Core · All Steps (stronger artistic restyling)", "semantic_all"), ("Final Readout + Late Steps (subtle photometric grade)", "look_keep_shapes"), ], value="semantic_late", label="Layer & Step Regime", interactive=True, ) diag_md = gr.Markdown(_format_diag_md(DEFAULT_MODEL)) gr.Examples( examples=[ ["a wooden cabin beside a calm mountain lake with pine trees", 42], ["a red fox sitting in a sunlit forest clearing", 7], ["a cobblestone street in a small European town at dusk", 19], ["a lighthouse on a dramatic rocky coast with waves", 101], ], inputs=[prompt_in, seed_in], label="Example Prompts", ) gen_inputs = [ model_in, prompt_in, seed_in, selected_styles, selected_dials, strengths_state, custom_dirs_state, regime_in, ortho_in, slot_in, invert_slot_in, baseline_cache_state, ] gen_gpu_outputs = [steered_out, telemetry_out, baseline_cache_state] gen_btn.click( fn=generate_comparison_gpu, inputs=gen_inputs, outputs=gen_gpu_outputs, show_progress_on=[steered_out, telemetry_out], ).success( fn=_sync_dry_image, inputs=[baseline_cache_state], outputs=[dry_out], queue=False, show_progress="hidden", ) prompt_in.submit( fn=generate_comparison_gpu, inputs=gen_inputs, outputs=gen_gpu_outputs, show_progress_on=[steered_out, telemetry_out], ).success( fn=_sync_dry_image, inputs=[baseline_cache_state], outputs=[dry_out], queue=False, show_progress="hidden", ) model_in.change( fn=_format_diag_md, inputs=[model_in], outputs=[diag_md], queue=False, show_progress="hidden", ) disable_all_btn.click( fn=_disable_all_directions, inputs=[], outputs=[selected_styles, selected_dials], queue=False, show_progress="hidden", ) reset_str_btn.click( fn=_reset_strengths, inputs=[selected_styles, selected_dials, strengths_state, render_rev, reset_gen], outputs=[strengths_state, render_rev, reset_gen], queue=False, show_progress="hidden", ) teach_btn.click( fn=_validate_teach_inputs, inputs=[teach_name, teach_target], outputs=[], queue=False, show_progress="hidden", ).success( fn=teach_direction_gpu, inputs=[model_in, teach_name, teach_target, teach_neutral, custom_dirs_state, strengths_state], outputs=[custom_dirs_state, strengths_state, last_created_slug, teach_status], ).success( fn=_apply_created_direction_ui, inputs=[custom_dirs_state, selected_styles, last_created_slug, render_rev, reset_gen], outputs=[selected_styles, render_rev, reset_gen, teach_name, teach_target], queue=False, show_progress="hidden", ) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run StateDrive Sana steering Gradio demo.") parser.add_argument("--host", default=os.environ.get("GRADIO_SERVER_NAME", "0.0.0.0")) parser.add_argument("--port", type=int, default=int(os.environ.get("GRADIO_SERVER_PORT", "7860"))) parser.add_argument("--share", action="store_true") cli_args, _ = parser.parse_known_args() demo.launch( server_name=cli_args.host, server_port=cli_args.port, share=cli_args.share, theme=gr.themes.Soft(), css=CSS, )