Spaces:
Running on Zero
Running on Zero
Download app.py from hugging-apps/dflow-2b: direct link, hf CLI and curl.
- Browser
- Download file 14.9 kB
-
https://huggingface.co/spaces/hugging-apps/dflow-2b/resolve/main/app.py
- Command line
-
hf download hf://spaces/hugging-apps/dflow-2b/app.py
-
curl -L -o app.py https://huggingface.co/spaces/hugging-apps/dflow-2b/resolve/main/app.py
14.9 kB
| """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)))) | |
| 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) | |