Spaces:
Running on Zero
Running on Zero
File size: 6,434 Bytes
0b7970e 7931d3b 0b7970e 1583f14 0b7970e 1583f14 0b7970e 1583f14 0b7970e 9c30c3f 0b7970e 9c30c3f | 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 | import spaces # ZeroGPU: must be imported before torch / transformers
import random
import time
from PIL import Image
import torch
import gradio as gr
from transformers import AutoModel
MODEL_ID = "ernie-research/Beers-base"
# Load the full model eagerly at module scope. ZeroGPU intercepts .to("cuda"),
# packs the weights, and streams them into VRAM on the first @spaces.GPU call.
model = AutoModel.from_pretrained(
MODEL_ID,
trust_remote_code=True,
dtype=torch.bfloat16,
).to("cuda")
model.eval()
# Grid sizes must be even (the model halves them internally for sequence packing).
RESOLUTIONS = {
"1024 × 1024": (64, 64),
"1024 × 1536 (portrait)": (96, 64),
"1536 × 1024 (landscape)": (64, 96),
"2048 × 2048 (model default)": (128, 128),
}
@spaces.GPU(duration=180)
def generate(
prompt: str,
negative_prompt: str = "",
resolution: str = "1024 × 1024",
num_steps: int = 48,
cfg_scale: float = 4.0,
shift: float = 3.0,
kappa: float = 0.35,
seed: int = -1,
progress=gr.Progress(track_tqdm=True),
):
"""Generate an image from a text prompt with Beers-Base (pixel-space diffusion).
Args:
prompt: Text description of the image to generate.
negative_prompt: Qualities to avoid (empty disables nothing).
resolution: Output resolution; the model generates at grid*16 pixels.
num_steps: Flow-matching denoising steps (model default: 75).
cfg_scale: Text classifier-free guidance scale (1.0 disables).
shift: Flow scheduler shift (model default: 3.0).
kappa: Two-end-dense sigma schedule parameter (model default: 0.35).
seed: Random seed; -1 picks a random seed each run.
Returns:
(PIL image, seed used, generation wall time in seconds)
"""
if not prompt or not prompt.strip():
raise gr.Error("Please enter a text prompt.")
if resolution not in RESOLUTIONS:
raise gr.Error(f"Unknown resolution: {resolution}")
grid_h, grid_w = RESOLUTIONS[resolution]
used_seed = random.randint(0, 2**31 - 1) if seed < 0 else int(seed)
t0 = time.time()
image = model.generate_image(
prompt=prompt.strip(),
height=grid_h,
width=grid_w,
num_steps=int(num_steps),
shift=float(shift),
cfg_scale=float(cfg_scale),
kappa=float(kappa),
ssg_scale=1.0,
negative_prompt=negative_prompt or "",
seed=used_seed,
)
elapsed = time.time() - t0
# generate_image returns a float tensor [3, H*16, W*16] in [0, 1].
pil_image = Image.fromarray((image.clamp(0, 1).permute(1, 2, 0).cpu().numpy() * 255).astype("uint8"))
return pil_image, used_seed, f"{elapsed:.1f}s"
# The model card's own showcased text-to-image prompts.
EXAMPLES = [
["A white cat lying on the grass under warm afternoon light", ""],
["A small red cabin beside a quiet lake, detailed landscape photography", "blurry, distorted, low quality"],
]
def build_ui():
with gr.Blocks(title="Beers-Base — Pixel-Space Text-to-Image") as demo:
gr.Markdown(
"""
# 🍺 Beers-Base — Pixel-Space Text-to-Image
**Beers** unlocks pixel-space image generation inside a pretrained
vision-language model (Qwen3-VL 4B). This demo runs the
[Beers-Base](https://huggingface.co/ernie-research/Beers-base) Stage-3
checkpoint with its native flow-matching sampler — no VAE, the model
diffuses raw RGB pixels.
"""
)
with gr.Row():
with gr.Column():
prompt = gr.Textbox(
label="Prompt",
placeholder="Describe the image you want…",
lines=3,
autofocus=True,
)
negative_prompt = gr.Textbox(
label="Negative prompt (optional)",
placeholder="e.g. blurry, distorted, low quality",
lines=1,
)
resolution = gr.Dropdown(
choices=list(RESOLUTIONS.keys()),
value="1024 × 1024",
label="Resolution",
)
generate_btn = gr.Button("Generate", variant="primary")
with gr.Accordion("Advanced settings", open=False):
num_steps = gr.Slider(4, 75, value=48, step=1, label="Denoising steps")
cfg_scale = gr.Slider(1.0, 10.0, value=4.0, step=0.1, label="CFG scale (text)")
shift = gr.Slider(1.0, 8.0, value=3.0, step=0.1, label="Scheduler shift")
kappa = gr.Slider(0.0, 0.9, value=0.35, step=0.05, label="Kappa (sigma schedule)")
seed = gr.Number(value=-1, label="Seed (-1 = random)", precision=0)
with gr.Column():
output_image = gr.Image(label="Generated image", type="pil", height=640)
with gr.Row():
used_seed = gr.Number(label="Seed used", precision=0, interactive=False)
gen_time = gr.Textbox(label="Generation time", interactive=False)
gr.Examples(
examples=EXAMPLES,
inputs=[prompt, negative_prompt],
fn=generate,
outputs=[output_image, used_seed, gen_time],
cache_examples=True,
cache_mode="lazy",
label="Try an example",
)
gr.Markdown(
"""
---
**Model**: [ernie-research/Beers-base](https://huggingface.co/ernie-research/Beers-base) ·
Qwen3-VL 4B backbone · Apache-2.0 ·
[Paper](https://arxiv.org/pdf/2612.03216) ·
[GitHub](https://github.com/ernie-research/Beers)
Defaults are tuned for a snappy demo (48 steps, 1024²). The model card
reference is 75 steps at 2048² — pick that resolution and step count in
Advanced settings for full quality.
"""
)
generate_btn.click(
fn=generate,
inputs=[prompt, negative_prompt, resolution, num_steps, cfg_scale, shift, kappa, seed],
outputs=[output_image, used_seed, gen_time],
api_name="generate",
)
return demo
demo = build_ui()
if __name__ == "__main__":
demo.launch(theme=gr.themes.Citrus(), mcp_server=True)
|