import os os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") import spaces # noqa: E402 (must precede torch) import json # noqa: E402 import random # noqa: E402 import tempfile # noqa: E402 import time # noqa: E402 from pathlib import Path # noqa: E402 import gradio as gr # noqa: E402 import torch # noqa: E402 from PIL import Image # noqa: E402 from transformers import AutoModelForCausalLM, AutoTokenizer # noqa: E402 from rdflow import Pipeline, parse_hex # noqa: E402 from rdflow.prompting import finalize, messages # noqa: E402 MAX_SEED = 2**31 - 1 SHORT_WORDS = 40 # same threshold generate.py uses to warn about short prompts LLM_ID = "Qwen/Qwen3-4B-Instruct-2507" # --- RD Flow 64: prompt reader (27-layer Qwen3-VL-4B cut) + 271M drawing model, both on the GPU ------------------- pipe = Pipeline.load(text_device="cuda", model_device="cuda", precision="bf16") print(f"RD Flow 64 loaded: {pipe.placement}") # --- Caption writer: a small local LLM driven by the authors' system prompt (rdflow/prompting.py) ----------------- llm_tok = AutoTokenizer.from_pretrained(LLM_ID) llm = AutoModelForCausalLM.from_pretrained(LLM_ID, dtype=torch.bfloat16).to("cuda").eval() EXAMPLES = json.loads(Path(__file__).with_name("examples").joinpath("examples.json").read_text(encoding="utf-8")) SHOWN = ["dragon.png", "owl.png", "astronaut.png", "chef-cat.png", "mushroom-frog.png", "flaming-sword.png", "pirate-ship.png", "desert-oasis.png", "night-city.png", "cozy-bedroom.png"] EX_ROWS = [e for f in SHOWN for e in EXAMPLES if e["file"] == f] def _write_caption(request: str, transparent: bool, palette, seed: int, attempts: int = 3) -> str: """Expand a short idea into the 120-200 word caption RD Flow 64 was trained on (mirrors rdflow.llm.write_caption).""" for i in range(attempts): msgs = messages(request, transparent, palette, seed + i) text = llm_tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True) ids = llm_tok(text, return_tensors="pt").to("cuda") torch.manual_seed(seed + i) out = llm.generate(**ids, max_new_tokens=450, do_sample=True, temperature=0.5 + 0.1 * i, top_p=0.9) raw = llm_tok.decode(out[0, ids["input_ids"].shape[1]:], skip_special_tokens=True) caption = finalize(raw, transparent) if caption: return caption return request def _gpu_duration(prompt, transparent=True, caption_writer="Auto", *args, **kwargs): # measured on ZeroGPU: LLM caption expansion ~8-10 s + reading/drawing ~1-1.5 s; drawing alone ~1-1.5 s expand = caption_writer == "Always" or (caption_writer == "Auto" and len((prompt or "").split()) < SHORT_WORDS) return 15 if expand else 8 @spaces.GPU(duration=_gpu_duration) def generate( prompt: str, transparent: bool = True, caption_writer: str = "Auto", num_images: int = 4, seed: int = 0, randomize_seed: bool = True, steps: int = 16, guidance: float = 4.0, palette: str = "", progress=gr.Progress(track_tqdm=True), ): """Draw 64x64 pixel art (with its own palette and real transparency) from a caption with RD Flow 64. Args: prompt: a short idea ("a red potion") or a full 120-200 word caption. transparent: True for a transparent sprite, False for a full-frame opaque picture. caption_writer: "Auto" expands prompts under 40 words with an LLM, "Always" always expands, "Off" never does. num_images: how many images to draw (seeds seed, seed+1, ...). seed: first seed. randomize_seed: pick a random seed instead of `seed`. steps: sampling steps (16 is the default; more gives the same images). guidance: classifier-free guidance; 3-4 is best. palette: optional comma-separated hex colours to lock every pixel to, e.g. "#1a1c2c,#5d275d,#b13e53". Returns: A gallery of 8x nearest-neighbour previews, the raw 64x64 PNG files, the caption used and the seed used. """ prompt = (prompt or "").strip() if not prompt: raise gr.Error("Please enter a prompt.") if randomize_seed: seed = random.randint(0, MAX_SEED) seed = int(seed) pal = None if palette and palette.strip(): try: pal = parse_hex([c for c in palette.replace(";", ",").replace(" ", ",").split(",") if c.strip()]) except ValueError as exc: raise gr.Error(str(exc)) t0 = time.perf_counter() expand = caption_writer == "Always" or (caption_writer == "Auto" and len(prompt.split()) < SHORT_WORDS) caption = _write_caption(prompt, transparent, pal, seed) if expand else prompt t1 = time.perf_counter() images = pipe(caption, n=int(num_images), seed=seed, transparent=transparent, palette=pal, steps=int(steps), guidance=float(guidance)) t2 = time.perf_counter() print(f"caption {t1 - t0:.2f}s (expanded={expand}) | prompt read {pipe.timings['prompt_s']}s | " f"draw {pipe.timings['draw_s']}s | total {t2 - t0:.2f}s") outdir = Path(tempfile.mkdtemp()) previews, files = [], [] for im, s in zip(images, pipe.timings["seeds"]): p = outdir / f"rd-flow-64-{s}.png" im.save(p) files.append(str(p)) previews.append((im.resize((512, 512), Image.NEAREST), f"seed {s}")) return previews, files, caption, seed CSS = """ #col-container { max-width: 1100px; margin: 0 auto; } .dark .gradio-container { color: var(--body-text-color); } #gallery img { image-rendering: pixelated; } """ with gr.Blocks(title="RD Flow 64") as demo: with gr.Column(elem_id="col-container"): gr.Markdown( "# RD Flow 64\n" "A 271M-parameter text-to-image model by [Retro Diffusion](https://retrodiffusion.ai) that draws real " "**64 x 64 pixel art** pixel by pixel, with its own palette and real transparency. " "It was trained on long 120-200 word captions: type a short idea and a local LLM " "(Qwen3-4B-Instruct) expands it with the authors' caption rules, or paste a full caption. \n" "[Model](https://huggingface.co/Retro-Diffusion/rd-flow-64) · " "[Code](https://github.com/Retro-Diffusion/rd-flow-64) · " "[Prompting guide](https://github.com/Retro-Diffusion/rd-flow-64/blob/main/PROMPTING.md) · " "[Technical report](https://retrodiffusion.ai/blog/rd-flow-64-technical-report) · " "Weights: CC BY-NC 4.0" ) with gr.Row(): with gr.Column(scale=1): prompt = gr.Textbox(label="Prompt", lines=4, placeholder="A short idea (\"a red health potion\") or a full 120-200 word caption") transparent = gr.Checkbox(label="Transparent sprite (off = full-frame picture)", value=True) run = gr.Button("Generate", variant="primary") with gr.Accordion("Advanced settings", open=False): caption_writer = gr.Radio(["Auto", "Always", "Off"], value="Auto", label="Caption writer (LLM)", info="Auto expands prompts shorter than 40 words") num_images = gr.Slider(1, 8, value=4, step=1, label="Images") with gr.Row(): seed = gr.Number(label="Seed", value=0, precision=0) randomize_seed = gr.Checkbox(label="Randomize seed", value=True) steps = gr.Slider(4, 50, value=16, step=1, label="Steps") guidance = gr.Slider(1.0, 8.0, value=4.0, step=0.1, label="Guidance", info="3-4 is best") palette = gr.Textbox(label="Lock palette (optional)", placeholder="#1a1c2c,#5d275d,#b13e53,#ef7d57,#ffcd75,#a7f070,#38b764") with gr.Column(scale=1): gallery = gr.Gallery(label="Result (8x preview)", columns=2, height="auto", format="png", elem_id="gallery") files = gr.File(label="64 x 64 PNGs", file_count="multiple") caption_out = gr.Textbox(label="Caption used", lines=5, interactive=False) gr.Examples( examples=[[e["caption"], e["transparent"]] for e in EX_ROWS], example_labels=[e["request"] + ("" if e["transparent"] else " (opaque)") for e in EX_ROWS], inputs=[prompt, transparent], outputs=[gallery, files, caption_out, seed], fn=generate, cache_examples=True, cache_mode="lazy", label="Examples (the authors' expanded captions)", ) gr.on([run.click, prompt.submit], generate, inputs=[prompt, transparent, caption_writer, num_images, seed, randomize_seed, steps, guidance, palette], outputs=[gallery, files, caption_out, seed], api_name="generate") if __name__ == "__main__": demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)