Spaces:
Running on Zero
Running on Zero
File size: 14,929 Bytes
00ff9d7 c081eb2 135986d c081eb2 135986d 00ff9d7 135986d 00ff9d7 135986d 00ff9d7 135986d 00ff9d7 135986d 00ff9d7 135986d 00ff9d7 135986d 00ff9d7 135986d 00ff9d7 135986d 00ff9d7 135986d 00ff9d7 135986d 00ff9d7 135986d 00ff9d7 135986d | 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 431 432 433 434 435 436 | """Interactive text-to-image demo for data-archetype/dflow_2b."""
import spaces # ZeroGPU: must be imported before torch.
import json
import random
import time
import gradio as gr
from dflow.guidance import (
CfgGuidance,
ConstantPdgScale,
GuidanceSettings,
PdgGuidance,
PdgMode,
)
from dflow.inference import GenerationSettings, SamplingSettings
from dflow.pipeline import DFlowPipeline
from dflow.schedules import ScheduleKind, TimeSchedule
from dflow.solvers import Solver
MAX_SEED = 2**63 - 1
# Size presets: (width, height) in pixels. Layout JSON compiles to the chosen
# size; plain prompts work at any of these sizes.
SIZE_PRESETS = {
"832 × 1216 (2:3 portrait)": (832, 1216),
"1216 × 832 (3:2 landscape)": (1216, 832),
"1120 × 1664 (2:3 portrait, 1.4 MP)": (1120, 1664),
"1664 × 1120 (3:2 landscape, 1.4 MP)": (1664, 1120),
"1216 × 1088 (10:9)": (1216, 1088),
"1024 × 1024 (square)": (1024, 1024),
}
pipe = DFlowPipeline.from_pretrained("data-archetype/dflow_2b", compile=False)
def _estimate_duration(prompt: str, size_choice: str, seed: int, steps: int,
*args, **kwargs) -> int:
"""Reserve GPU seconds sized to this run, following the ZeroGPU
methodology (measured worst case × 1.4).
ZeroGPU forwards the decorated function's own positional arguments, so
this signature mirrors the first four parameters of ``generate`` and
swallows the rest. Measured on ZeroGPU: ~17 s at 50 steps / 1.0 MP and
~40 s at 50 steps / 1.9 MP, i.e. roughly 0.33 and 0.78 seconds per step
at those sizes, plus a small fixed cost for text encoding and the VAE
decode.
"""
steps = max(1, int(steps))
width, height = SIZE_PRESETS.get(size_choice, (832, 1216))
megapixels = (width * height) / 1e6
per_step = max(0.3, 0.52 * megapixels - 0.19)
seconds = steps * per_step + 8
return int(min(360, max(30, round(seconds * 1.4))))
@spaces.GPU(duration=_estimate_duration)
def generate(
prompt: str,
size_choice: str,
seed: int,
steps: int,
noise_scale: float,
pdg_scale: float,
suffix_caption_bias: float,
self_attention_gain: float,
use_cfg: bool,
cfg_scale: float,
negative_prompt: str,
randomize_seed: bool,
progress: gr.Progress = gr.Progress(track_tqdm=True),
) -> tuple:
"""Generate an image from a text prompt with dflow_2b.
Args:
prompt: Text prompt, or a stored JSON layout (summary/frame/items
with 0-1000 boxes) which the pipeline compiles to the size.
size_choice: One of the size preset labels.
seed: Seed of the random draws, in [0, 2**63 - 1].
steps: Number of ER-SDE solver updates (50 in the reference).
noise_scale: Noise multiplier of the stochastic solver.
pdg_scale: Constant path-drop guidance scale (2.5 in the reference).
suffix_caption_bias: PDG reference caption-logit bias (-4 in the
reference; more negative reads the prompt less).
self_attention_gain: Self-attention gain (-0.03 by default).
use_cfg: Add classifier-free guidance against the negative prompt,
alternating steps with PDG (off in the reference; plain PDG-full
and CFG cannot share the same steps, so enabling this switches
PDG to the alternating mode).
cfg_scale: CFG scale, used only when use_cfg is True.
negative_prompt: Text of the CFG negative branch; empty selects the
learned null text.
randomize_seed: Draw and return a fresh seed instead of using the
given one.
Returns:
(image, seed_used, seconds): the generated PIL image, the seed it
was generated with, and the wall-clock seconds spent generating.
"""
if randomize_seed:
seed = random.randint(0, MAX_SEED)
seed = int(seed) % (MAX_SEED + 1)
width, height = SIZE_PRESETS.get(size_choice, (832, 1216))
# CFG-full and PDG-full cannot share steps (the library rejects it);
# enabling CFG switches PDG to the alternating mode that runs CFG on its
# own steps — the "CFG and PDG on alternate steps" recipe from the
# manual, keeping the positive-prompt PDG branch.
pdg_mode = PdgMode.ALTERNATE_POSITIVE_PDG_FIRST if use_cfg else PdgMode.FULL
settings = GenerationSettings(
width=width,
height=height,
seed=seed,
sampling=SamplingSettings(
solver=Solver.ER_SDE,
noise_scale=float(noise_scale),
schedule=TimeSchedule(
kind=ScheduleKind.BETA_1_25,
steps=int(steps),
beta_mean=0.5,
beta_concentration=0.6,
),
),
guidance=GuidanceSettings(
pdg=PdgGuidance(
mode=pdg_mode,
scale=ConstantPdgScale(scale=float(pdg_scale)),
suffix_caption_bias=max(-10.0, min(0.0, float(suffix_caption_bias))),
),
cfg=CfgGuidance(
enabled=False,
scale=max(1.0, float(cfg_scale)) if use_cfg else None,
),
self_attention_gain=max(-0.5, min(0.1, float(self_attention_gain))),
),
negative_prompt=str(negative_prompt),
)
started = time.perf_counter()
output = pipe(prompt, settings)
elapsed = time.perf_counter() - started
return output.images[0], seed, round(elapsed, 1)
_JAZZ_LAYOUT = json.dumps(
{
"summary": {
"meta": ["concert_poster", "flat_illustration", "mid_century_modern"],
"canvas": "single",
"caption": (
"A mid-century style jazz festival poster shows a saxophonist in "
"silhouette against a large orange sun on a deep teal background. "
'The title "BLUE HARBOR JAZZ" runs across the top in cream capitals '
'and the line "JULY 12 – 14, 1996" sits at the bottom.'
),
},
"frame": {
"caption": (
"The saxophonist stands in the centre, cut off at the knees, with "
"the sun behind his shoulders. The title fills the top fifth and "
"the date line sits in a band along the bottom edge. Flat colour "
"shapes with a light paper grain."
),
"tags": ["flat_color", "centered_composition", "paper_grain"],
"palette": ["#0F4C5C", "#F28C28", "#F5E9D0", "#1B1B1B"],
},
"items": [
{
"label": "object",
"caption": "A large flat orange circle, the sun, behind the musician.",
"tags": ["sun", "circle"],
"palette": ["#F28C28"],
"box_2d": [230, 170, 720, 830],
},
{
"label": "character",
"caption": (
"A black silhouette of a man in a hat playing a tenor saxophone, "
"facing right, leaning back slightly."
),
"tags": ["saxophonist", "silhouette", "hat"],
"palette": ["#1B1B1B"],
"box_2d": [260, 250, 880, 760],
},
{
"label": "text",
"caption": (
'The title "BLUE HARBOR JAZZ" in bold condensed cream capitals '
"on one line."
),
"text": "BLUE HARBOR JAZZ",
"tags": ["title", "condensed_sans", "uppercase"],
"palette": ["#F5E9D0"],
"box_2d": [60, 70, 180, 930],
},
{
"label": "text",
"caption": (
'The date line "JULY 12 – 14, 1996" in small spaced cream capitals.'
),
"text": "JULY 12 – 14, 1996",
"tags": ["date", "small_caps"],
"palette": ["#F5E9D0"],
"box_2d": [905, 300, 950, 700],
},
],
}
)
# Each row: the authors' gallery prompt with the seed and size it was shown at
# (self-attention gain as the authors used for that image; CFG off everywhere).
_EXAMPLE_ROWS = [
[
"A bright orange and black rooster standing on a damp garden path, "
"surrounded by lush green tropical plants and trees, its red comb upright "
"and long dark tail feathers curving down over the wet concrete.",
"832 × 1216 (2:3 portrait)",
42,
50,
1.0,
2.5,
-4.0,
-0.03,
False,
4.0,
"",
False,
],
[
"Leopard lying down in a tree at night.",
"1216 × 832 (3:2 landscape)",
43,
50,
1.0,
2.5,
-4.0,
-0.03,
False,
4.0,
"",
False,
],
[
'A traditional japanese woodblock print, "the great wave off kanagawa" by '
"hokusai, depicts a massive blue and white wave crashing towards the viewer "
"against a pale blue sky.",
"1024 × 1024 (square)",
424,
50,
1.0,
2.5,
-4.0,
-0.03,
False,
4.0,
"",
False,
],
[
"An oil painting of a landscape with sheep and farmers near a mill by John "
"Constable",
"1216 × 1088 (10:9)",
44,
50,
1.0,
2.5,
-4.0,
-0.02,
False,
4.0,
"",
False,
],
[
_JAZZ_LAYOUT,
"832 × 1216 (2:3 portrait)",
42,
50,
1.0,
2.5,
-4.0,
-0.03,
False,
4.0,
"",
False,
],
]
css = """
#col-container { margin: 0 auto; max-width: 1100px; }
.dark .gradio-container { color: var(--body-text-color); }
"""
with gr.Blocks() as demo:
gr.Markdown(
"""
# dflow_2b — text-to-image
**dflow_2b** is a 2B-parameter flow-matching text-to-image model from
[data-archetype](https://huggingface.co/data-archetype/dflow_2b)
(preview, version 0.2). It samples with a 50-step ER-SDE solver on a
Beta(1.25, 1.25) schedule and uses **path-drop guidance** (PDG) instead
of classifier-free guidance by default.
Prompts may be plain text — with `(phrase:weight)` emphasis markup and
`"quoted text"` tokenized letter-by-letter — **or a stored JSON layout**
(summary / frame / items with 0–1000 `box_2d` coordinates) which the
pipeline compiles to the chosen image size automatically. Try the
examples below.
*Weights: MG-BY-NC-2.0 (non-commercial); text encoder under Gemma
terms. Preview model — some seeds are uneven.*
"""
)
with gr.Column(elem_id="col-container"):
with gr.Row():
with gr.Column(scale=1):
prompt = gr.Textbox(
label="Prompt (text or JSON layout)",
placeholder=(
"A bright orange and black rooster standing on a damp "
"garden path…"
),
lines=5,
max_lines=14,
)
with gr.Row():
size_choice = gr.Dropdown(
choices=list(SIZE_PRESETS.keys()),
value="832 × 1216 (2:3 portrait)",
label="Image size",
filterable=False,
)
seed = gr.Number(
value=0,
minimum=0,
maximum=MAX_SEED,
label="Seed",
precision=0,
)
randomize_seed = gr.Checkbox(
value=True, label="Randomize seed on every run"
)
with gr.Accordion("Guidance", open=True):
pdg_scale = gr.Slider(
0.0, 6.0, value=2.5, step=0.1, label="PDG scale"
)
suffix_caption_bias = gr.Slider(
-10.0, 0.0, value=-4.0, step=0.5, label="Suffix caption bias"
)
self_attention_gain = gr.Slider(
-0.50,
0.10,
value=-0.03,
step=0.01,
label="Self-attention gain",
)
use_cfg = gr.Checkbox(
value=False,
label="Add CFG (alternates steps with PDG; uses the negative prompt)",
)
negative_prompt = gr.Textbox(
label="Negative prompt (CFG only)",
value="",
lines=2,
placeholder="blurry, watermark…",
)
cfg_scale = gr.Slider(
1.0, 12.0, value=4.0, step=0.1, label="CFG scale"
)
with gr.Accordion("Sampler", open=False):
steps = gr.Slider(1, 100, value=50, step=1, label="Steps")
noise_scale = gr.Slider(
0.0, 2.0, value=1.0, step=0.05, label="Noise scale"
)
run = gr.Button("Generate", variant="primary")
with gr.Column(scale=1):
image = gr.Image(label="Generated image", type="pil")
seed_used = gr.Number(label="Seed used", precision=0)
elapsed = gr.Number(label="Seconds", precision=1)
run.click(
fn=generate,
inputs=[
prompt,
size_choice,
seed,
steps,
noise_scale,
pdg_scale,
suffix_caption_bias,
self_attention_gain,
use_cfg,
cfg_scale,
negative_prompt,
randomize_seed,
],
outputs=[image, seed_used, elapsed],
api_name="generate",
show_progress=True,
)
gr.Examples(
examples=_EXAMPLE_ROWS,
inputs=[
prompt,
size_choice,
seed,
steps,
noise_scale,
pdg_scale,
suffix_caption_bias,
self_attention_gain,
use_cfg,
cfg_scale,
negative_prompt,
randomize_seed,
],
fn=generate,
outputs=[image, seed_used, elapsed],
cache_examples=True,
cache_mode="lazy",
label="Examples from the model's gallery (authors' prompts, seeds and sizes)",
)
demo.launch(theme=gr.themes.Citrus(), css=css, mcp_server=True)
|