Pixelkram commited on
Commit
aab73d2
·
verified ·
1 Parent(s): 1a99c6d

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +40 -6
  2. app.py +314 -0
  3. requirements.txt +5 -0
README.md CHANGED
@@ -1,14 +1,48 @@
1
  ---
2
- title: SD Explorer Intro
3
- emoji: 🔥
4
- colorFrom: pink
5
  colorTo: pink
6
  sdk: gradio
7
  sdk_version: 6.30.0
8
- python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
11
- short_description: exploring stable diffusion 1.5
 
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Stable Diffusion Lab
3
+ emoji: 🎨
4
+ colorFrom: indigo
5
  colorTo: pink
6
  sdk: gradio
7
  sdk_version: 6.30.0
8
+ python_version: "3.12"
9
  app_file: app.py
10
  pinned: false
11
+ license: creativeml-openrail-m
12
+ short_description: Explore Stable Diffusion with live denoising previews
13
  ---
14
 
15
+ # Stable Diffusion Lab
16
+
17
+ A teaching Space for exploring text-to-image diffusion. Students can set:
18
+
19
+ - positive and negative prompt
20
+ - CFG scale (0.0 to 15.0) and denoising steps (4 to 48)
21
+ - sampler: Euler, Euler Ancestral, DDIM, UniPC
22
+ - checkpoint: Stable Diffusion 1.5 or Realistic Vision V6.0
23
+ - seed (or a random seed) and resolution (512x512 by default, 256 to 768 px)
24
+
25
+ While an image is generated, a live preview of the denoising is streamed to the page.
26
+
27
+ ## Hardware
28
+
29
+ Designed for a dedicated GPU (fp16, about 6 GB VRAM for both checkpoints). It also runs on CPU, but slowly. Both checkpoints load at startup, so the first build takes a few minutes while the weights download.
30
+
31
+ ## How the live preview works
32
+
33
+ The app runs its own denoising loop. At every step the U-Net predicts the noise, and from that prediction the app computes the model's current guess of the final image. That guess is decoded with TAESD, a tiny and fast VAE decoder. The final step uses the full VAE of the checkpoint.
34
+
35
+ ## Settings (Space variables)
36
+
37
+ | Variable | Default | Meaning |
38
+ | --- | --- | --- |
39
+ | `SAFETY_CHECKER` | `1` | Set to `0` to turn off the NSFW filter (it can flag harmless art) |
40
+ | `MAX_CONCURRENT` | `1` | Generations running at the same time |
41
+ | `PRELOAD` | `1` | Load both checkpoints at startup instead of on first use |
42
+ | `SD15_REPO` | `sd-legacy/stable-diffusion-v1-5` | Base model repo (the original runwayml repo is deprecated) |
43
+ | `RV_REPO`, `RV_FILE` | Realistic Vision V6.0 B1 noVAE, fp16 file | Finetuned checkpoint |
44
+ | `RV_VAE_REPO` | `stabilityai/sd-vae-ft-mse` | VAE for Realistic Vision, whose repo ships without one |
45
+
46
+ ## Licenses
47
+
48
+ Both checkpoints use the CreativeML OpenRAIL-M license.
app.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stable Diffusion Lab: a teaching Space for BA Design students.
3
+
4
+ Students can explore how the main knobs of Stable Diffusion 1.5 change an image:
5
+ prompt / negative prompt, CFG scale, number of denoising steps, sampler, checkpoint,
6
+ seed and resolution. While the image is being generated, a live preview of the
7
+ denoising process is streamed to the browser.
8
+
9
+ How the live preview works
10
+ --------------------------
11
+ We run our own (short) denoising loop instead of calling pipe(...). At every step the
12
+ U-Net predicts the noise. From that prediction we compute the model's current guess of
13
+ the final, clean latent ("x0 prediction") and decode it with TAESD, a tiny and very
14
+ fast VAE decoder. The last step is decoded with the full-quality VAE of the checkpoint.
15
+
16
+ Runs on a dedicated GPU (fp16) but also works on CPU for local testing (slow).
17
+ """
18
+
19
+ import os
20
+ import random
21
+ import threading
22
+
23
+ import gradio as gr
24
+ import numpy as np
25
+ import torch
26
+ from diffusers import (
27
+ AutoencoderKL,
28
+ AutoencoderTiny,
29
+ DDIMScheduler,
30
+ EulerAncestralDiscreteScheduler,
31
+ EulerDiscreteScheduler,
32
+ StableDiffusionPipeline,
33
+ UniPCMultistepScheduler,
34
+ )
35
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
36
+ from huggingface_hub import hf_hub_download
37
+ from PIL import Image
38
+ from transformers import CLIPImageProcessor
39
+
40
+ # ----------------------------------------------------------------------------
41
+ # Configuration (all overridable with Space variables / environment variables)
42
+ # ----------------------------------------------------------------------------
43
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
44
+ DTYPE = getattr(torch, os.getenv("DTYPE", "float16" if DEVICE == "cuda" else "float32"))
45
+
46
+ SD15_REPO = os.getenv("SD15_REPO", "sd-legacy/stable-diffusion-v1-5")
47
+ RV_REPO = os.getenv("RV_REPO", "SG161222/Realistic_Vision_V6.0_B1_noVAE")
48
+ RV_FILE = os.getenv("RV_FILE", "Realistic_Vision_V6.0_NV_B1_fp16.safetensors")
49
+ # Realistic Vision "noVAE" needs an external VAE (the author recommends sd-vae-ft-mse).
50
+ RV_VAE_REPO = os.getenv("RV_VAE_REPO", "stabilityai/sd-vae-ft-mse")
51
+ TAESD_REPO = os.getenv("TAESD_REPO", "madebyollin/taesd")
52
+ SAFETY_REPO = os.getenv("SAFETY_REPO", "CompVis/stable-diffusion-safety-checker")
53
+
54
+ USE_SAFETY_CHECKER = os.getenv("SAFETY_CHECKER", "1") == "1"
55
+ PRELOAD = os.getenv("PRELOAD", "1") == "1" # load both checkpoints at startup
56
+ MAX_CONCURRENT = int(os.getenv("MAX_CONCURRENT", "1")) # generations running at once
57
+
58
+ MODEL_NAMES = ["Stable Diffusion 1.5", "Realistic Vision V6.0"]
59
+ DEFAULT_MODEL = MODEL_NAMES[0]
60
+
61
+ SAMPLERS = {
62
+ "Euler": EulerDiscreteScheduler,
63
+ "Euler Ancestral": EulerAncestralDiscreteScheduler,
64
+ "DDIM": DDIMScheduler,
65
+ "UniPC": UniPCMultistepScheduler,
66
+ }
67
+
68
+ DEFAULTS = dict(steps=20, cfg=7.5, width=512, height=512, seed=42, sampler="Euler")
69
+
70
+ # ----------------------------------------------------------------------------
71
+ # Model loading
72
+ # ----------------------------------------------------------------------------
73
+ _pipes: dict = {}
74
+ _taesd = None
75
+ _safety = None
76
+ _load_lock = threading.Lock()
77
+
78
+
79
+ def _load_sd15() -> StableDiffusionPipeline:
80
+ return StableDiffusionPipeline.from_pretrained(
81
+ SD15_REPO,
82
+ torch_dtype=DTYPE,
83
+ variant="fp16",
84
+ use_safetensors=True,
85
+ safety_checker=None, # we run the safety checker ourselves (see below)
86
+ requires_safety_checker=False,
87
+ )
88
+
89
+
90
+ def _load_realistic_vision() -> StableDiffusionPipeline:
91
+ vae = AutoencoderKL.from_pretrained(RV_VAE_REPO, torch_dtype=DTYPE)
92
+ ckpt = hf_hub_download(RV_REPO, RV_FILE)
93
+ return StableDiffusionPipeline.from_single_file(
94
+ ckpt,
95
+ torch_dtype=DTYPE,
96
+ vae=vae,
97
+ config=SD15_REPO, # SD 1.5 architecture, so the config files can come from there
98
+ safety_checker=None,
99
+ requires_safety_checker=False,
100
+ )
101
+
102
+
103
+ _LOADERS = {
104
+ "Stable Diffusion 1.5": _load_sd15,
105
+ "Realistic Vision V6.0": _load_realistic_vision,
106
+ }
107
+
108
+
109
+ def get_pipe(name: str) -> StableDiffusionPipeline:
110
+ with _load_lock:
111
+ if name not in _pipes:
112
+ print(f"Loading {name} ...")
113
+ pipe = _LOADERS[name]().to(DEVICE)
114
+ pipe.set_progress_bar_config(disable=True)
115
+ _pipes[name] = pipe
116
+ return _pipes[name]
117
+
118
+
119
+ def get_taesd() -> AutoencoderTiny:
120
+ global _taesd
121
+ with _load_lock:
122
+ if _taesd is None:
123
+ _taesd = AutoencoderTiny.from_pretrained(TAESD_REPO, torch_dtype=DTYPE).to(DEVICE)
124
+ return _taesd
125
+
126
+
127
+ def get_safety():
128
+ global _safety
129
+ with _load_lock:
130
+ if _safety is None:
131
+ checker = StableDiffusionSafetyChecker.from_pretrained(SAFETY_REPO, torch_dtype=DTYPE).to(DEVICE)
132
+ extractor = CLIPImageProcessor.from_pretrained(SAFETY_REPO)
133
+ _safety = (checker, extractor)
134
+ return _safety
135
+
136
+
137
+ # ----------------------------------------------------------------------------
138
+ # Helpers
139
+ # ----------------------------------------------------------------------------
140
+ def to_pil(x: torch.Tensor) -> Image.Image:
141
+ """(1, 3, H, W) tensor in [-1, 1] -> PIL image."""
142
+ x = (x.float() / 2 + 0.5).clamp(0, 1)[0].permute(1, 2, 0).cpu().numpy()
143
+ return Image.fromarray((x * 255).round().astype(np.uint8))
144
+
145
+
146
+ def predict_x0(scheduler, x_in: torch.Tensor, eps: torch.Tensor, t) -> torch.Tensor:
147
+ """
148
+ The model's current guess of the final clean latent, given the noisy latent and the
149
+ predicted noise: x0 = (x_t - sqrt(1 - abar) * eps) / sqrt(abar).
150
+
151
+ `x_in` is the scheduler-scaled model input, i.e. the sample in "variance preserving"
152
+ form. For the Euler samplers abar follows from sigma (abar = 1 / (sigma^2 + 1)),
153
+ for DDIM and UniPC it is read from the training noise schedule.
154
+ """
155
+ if isinstance(scheduler, (EulerDiscreteScheduler, EulerAncestralDiscreteScheduler)):
156
+ sigma = float(scheduler.sigmas[scheduler.step_index])
157
+ abar = 1.0 / (sigma**2 + 1.0)
158
+ else:
159
+ abar = float(scheduler.alphas_cumprod[int(t)])
160
+ return (x_in.float() - (1.0 - abar) ** 0.5 * eps.float()) / abar**0.5
161
+
162
+
163
+ def apply_safety_checker(image: Image.Image):
164
+ """Returns (image, was_blocked)."""
165
+ if not USE_SAFETY_CHECKER:
166
+ return image, False
167
+ checker, extractor = get_safety()
168
+ clip_input = extractor(images=image, return_tensors="pt").pixel_values.to(DEVICE, DTYPE)
169
+ arr = np.asarray(image).astype(np.float32)[None] / 255.0
170
+ arr, flagged = checker(images=arr, clip_input=clip_input)
171
+ if flagged and flagged[0]:
172
+ return Image.fromarray((arr[0] * 255).astype(np.uint8)), True
173
+ return image, False
174
+
175
+
176
+ # ----------------------------------------------------------------------------
177
+ # Generation (a generator: every yield updates the UI)
178
+ # ----------------------------------------------------------------------------
179
+ @torch.inference_mode()
180
+ def generate(model_name, prompt, negative_prompt, cfg, steps, sampler_name, seed, randomize_seed, width, height):
181
+ steps, width, height = int(steps), int(width), int(height)
182
+ seed = random.randint(0, 2**32 - 1) if randomize_seed or seed is None else int(seed)
183
+
184
+ pipe = get_pipe(model_name)
185
+ taesd = get_taesd()
186
+
187
+ # A fresh scheduler per request: schedulers keep internal state, and several
188
+ # students may be using the same pipeline.
189
+ scheduler = SAMPLERS[sampler_name].from_config(pipe.scheduler.config, timestep_spacing="leading")
190
+ scheduler.set_timesteps(steps, device=DEVICE)
191
+
192
+ # Text conditioning. Batch order is [negative, positive] for classifier-free guidance.
193
+ prompt_embeds, negative_embeds = pipe.encode_prompt(
194
+ prompt or "", DEVICE, 1, True, negative_prompt=negative_prompt or ""
195
+ )[:2]
196
+ text_embeds = torch.cat([negative_embeds, prompt_embeds])
197
+
198
+ # Seeded starting noise. Created on the CPU so a seed gives the same noise on any machine.
199
+ generator = torch.Generator("cpu").manual_seed(seed)
200
+ latents = torch.randn((1, pipe.unet.config.in_channels, height // 8, width // 8), generator=generator)
201
+ latents = latents.to(DEVICE, DTYPE) * scheduler.init_noise_sigma
202
+
203
+ step_kwargs = {"generator": generator} if isinstance(scheduler, EulerAncestralDiscreteScheduler) else {}
204
+
205
+ for i, t in enumerate(scheduler.timesteps):
206
+ x_in = scheduler.scale_model_input(torch.cat([latents, latents]), t)
207
+ eps = pipe.unet(x_in, t, encoder_hidden_states=text_embeds).sample
208
+ eps_uncond, eps_cond = eps.chunk(2)
209
+ # Classifier-free guidance: 0 = ignore the prompt, 1 = plain prompt, >1 = push harder.
210
+ eps = eps_uncond + cfg * (eps_cond - eps_uncond)
211
+
212
+ if i < len(scheduler.timesteps) - 1:
213
+ x0 = predict_x0(scheduler, x_in.chunk(2)[0], eps, t)
214
+ preview = to_pil(taesd.decode(x0.to(DTYPE)).sample)
215
+ latents = scheduler.step(eps, t, latents, **step_kwargs).prev_sample
216
+ yield preview, seed, f"Step {i + 1} of {steps}: preview of the model's current guess"
217
+ else:
218
+ latents = scheduler.step(eps, t, latents, **step_kwargs).prev_sample
219
+
220
+ # Final image with the full VAE of the checkpoint.
221
+ vae = pipe.vae
222
+ image = to_pil(vae.decode(latents / vae.config.scaling_factor).sample)
223
+ image, blocked = apply_safety_checker(image)
224
+ if blocked:
225
+ gr.Warning("The safety filter blocked this image. Try a different prompt or seed.")
226
+ yield image, seed, f"Done: {steps} steps, seed {seed}" + (" (blocked by safety filter)" if blocked else "")
227
+
228
+
229
+ # ----------------------------------------------------------------------------
230
+ # UI
231
+ # ----------------------------------------------------------------------------
232
+ EXAMPLES = [
233
+ ["a cozy reading nook with a large window, soft morning light, plants, film photo", "blurry, low quality"],
234
+ ["portrait of an old fisherman, weathered face, dramatic side light, 85mm photo", "cartoon, painting, deformed"],
235
+ ["a futuristic tram station in the rain at night, neon reflections, wide angle", "text, watermark"],
236
+ ["a ceramic teapot shaped like a mountain, studio product photo", ""],
237
+ ]
238
+
239
+ with gr.Blocks(title="Stable Diffusion Lab") as demo:
240
+ gr.Markdown(
241
+ "# Stable Diffusion Lab\n"
242
+ "Explore how text-to-image diffusion works. Change one setting at a time and keep the "
243
+ "**seed** fixed to see exactly what that setting does. Watch the image emerge from noise "
244
+ "in the live preview."
245
+ )
246
+ with gr.Row():
247
+ with gr.Column(scale=5):
248
+ model = gr.Dropdown(
249
+ MODEL_NAMES,
250
+ value=DEFAULT_MODEL,
251
+ label="Checkpoint",
252
+ info="Stable Diffusion 1.5 is the base model. Realistic Vision V6.0 is a finetune of it "
253
+ "that was trained further towards photorealistic images.",
254
+ )
255
+ prompt = gr.Textbox(label="Prompt", lines=3, placeholder="Describe what you want to see")
256
+ negative = gr.Textbox(
257
+ label="Negative prompt",
258
+ lines=2,
259
+ placeholder="What the image should avoid, e.g. blurry, low quality, extra fingers",
260
+ )
261
+ with gr.Row():
262
+ sampler = gr.Dropdown(
263
+ list(SAMPLERS),
264
+ value=DEFAULTS["sampler"],
265
+ label="Sampler",
266
+ info="The algorithm that walks from noise to image. Euler Ancestral adds fresh noise "
267
+ "at every step, so it never fully settles.",
268
+ )
269
+ steps = gr.Slider(
270
+ 4, 48, value=DEFAULTS["steps"], step=1, label="Denoising steps",
271
+ info="More steps = finer refinement, but slower.",
272
+ )
273
+ cfg = gr.Slider(
274
+ 0.0, 15.0, value=DEFAULTS["cfg"], step=0.1, label="CFG scale",
275
+ info="How strongly the prompt is enforced. 0 ignores the prompt, 1 follows it plainly, "
276
+ "high values get rigid and oversaturated.",
277
+ )
278
+ with gr.Row():
279
+ width = gr.Slider(
280
+ 256, 768, value=DEFAULTS["width"], step=64, label="Width (px)",
281
+ info="Both models were trained at 512 px. Much larger sizes tend to repeat objects.",
282
+ )
283
+ height = gr.Slider(256, 768, value=DEFAULTS["height"], step=64, label="Height (px)")
284
+ with gr.Row():
285
+ seed = gr.Number(
286
+ value=DEFAULTS["seed"], precision=0, minimum=0, maximum=2**32 - 1, label="Seed",
287
+ info="Same seed + same settings = same image.",
288
+ )
289
+ randomize = gr.Checkbox(value=False, label="Random seed", info="Pick a new seed on every run.")
290
+ run = gr.Button("Generate", variant="primary")
291
+ with gr.Column(scale=5):
292
+ output = gr.Image(label="Result (live preview while generating)", type="pil", interactive=False)
293
+ status = gr.Markdown()
294
+
295
+ gr.Examples(EXAMPLES, inputs=[prompt, negative], label="Example prompts")
296
+
297
+ inputs = [model, prompt, negative, cfg, steps, sampler, seed, randomize, width, height]
298
+ outputs = [output, seed, status]
299
+ for trigger in (run.click, prompt.submit):
300
+ trigger(
301
+ generate, inputs, outputs,
302
+ show_progress="hidden", concurrency_limit=MAX_CONCURRENT, api_name="generate" if trigger == run.click else False,
303
+ )
304
+
305
+ demo.queue(max_size=40)
306
+
307
+ if __name__ == "__main__":
308
+ if PRELOAD:
309
+ for _name in MODEL_NAMES:
310
+ get_pipe(_name)
311
+ get_taesd()
312
+ if USE_SAFETY_CHECKER:
313
+ get_safety()
314
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch
2
+ diffusers==0.41.0
3
+ transformers==5.19.0
4
+ accelerate==1.15.0
5
+ safetensors