import spaces # must be imported before torch / diffusers import random import gradio as gr import numpy as np import torch import transformers # Transformers v5 removed the slow/fast tokenizer split, so the T5TokenizerFast # name that diffusers (and the base model's model_index.json) still references no # longer exists. In v5, T5Tokenizer *is* the fast TokenizersBackend implementation, # so aliasing the old name restores the behavior diffusers expects. if not hasattr(transformers, "T5TokenizerFast"): transformers.T5TokenizerFast = transformers.T5Tokenizer from diffusers import StableDiffusion3Pipeline BASE_MODEL = "stabilityai/stable-diffusion-3.5-medium" LORA_REPO = "ShimaRinC/StepX-OPD-SD3.5" MAX_SEED = np.iinfo(np.int32).max DEFAULT_STEPS = 4 # the distilled student is trained to be sampled in 4 steps MAX_IMAGE_SIZE = 1024 # Official recipe from the StepX-OPD model card: SD3.5-Medium in bf16 with the # folded StepX-OPD inference LoRA on top, sampled in 4 steps without CFG on the # pre-shift sigma grid np.linspace(1.0, 1/N, N). pipe = StableDiffusion3Pipeline.from_pretrained( BASE_MODEL, torch_dtype=torch.bfloat16 ).to("cuda") pipe.load_lora_weights(LORA_REPO) @spaces.GPU(duration=10) def generate( prompt, negative_prompt="", seed=0, randomize_seed=True, width=512, height=512, guidance_scale=1.0, num_inference_steps=DEFAULT_STEPS, progress=gr.Progress(track_tqdm=True), ): """Generate an image from a text prompt with StepX-OPD, a 4-step distilled SD 3.5 Medium.""" if not prompt or not prompt.strip(): raise gr.Error("Please enter a prompt first.") if randomize_seed: seed = random.randint(0, MAX_SEED) seed = int(seed) generator = torch.Generator("cuda").manual_seed(seed) num_inference_steps = int(num_inference_steps) sigmas = np.linspace(1.0, 1.0 / num_inference_steps, num_inference_steps) image = pipe( prompt=prompt, negative_prompt=negative_prompt, guidance_scale=guidance_scale, num_inference_steps=num_inference_steps, sigmas=sigmas, width=int(width), height=int(height), generator=generator, ).images[0] return image, seed examples = [ ["a corgi wearing sunglasses, studio photo"], ["a photo of two toilets"], ["a photo of a dog right of a teddy bear"], ["a photo of a red cake and a purple chair"], [ "A vibrant science fair poster titled \"Volcano Experiment\", featuring " "a detailed illustration of a volcanic eruption with lava flowing down " "its slopes, surrounded by labeled diagrams and facts about volcanic " "processes, all set against a bright, engaging background." ], ["cat knight in the style of darkest dungeon"], ["realistic cartoon mouse with a birthday candle"], ] css = """ #col-container { margin: 0 auto; max-width: 900px; } .dark .gradio-container { color: var(--body-text-color); } """ with gr.Blocks() as demo: with gr.Column(elem_id="col-container"): gr.Markdown( "# ⚡ StepX-OPD\n" "**StepX-OPD** distills Stable Diffusion 3.5 Medium into a " "**4-step** generator via multi-teacher on-policy distillation — " "full-quality images in seconds, without classifier-free guidance.\n\n" "[Paper](https://huggingface.co/papers/2611.04386) · " "[Code](https://github.com/WinterCCC/StepX-OPD) · " "[Project page](https://winterccc.github.io/Step-OPD/) · " "[Weights](https://huggingface.co/ShimaRinC/StepX-OPD-SD3.5) · " "[Base model](https://huggingface.co/stabilityai/stable-diffusion-3.5-medium)" ) with gr.Row(): prompt = gr.Text( label="Prompt", show_label=False, max_lines=1, placeholder="Enter your prompt", container=False, scale=4, ) run_button = gr.Button("Run", variant="primary", scale=1) result = gr.Image(label="Result", show_label=False) with gr.Accordion("Advanced settings", open=False): negative_prompt = gr.Text( label="Negative prompt", max_lines=1, placeholder="Only used when Guidance scale > 1.0", info="The distilled student is trained to run at guidance 1.0 (no CFG); a negative prompt only takes effect above 1.0.", ) seed = gr.Slider( label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, ) randomize_seed = gr.Checkbox(label="Randomize seed", value=True) with gr.Row(): width = gr.Slider( label="Width", minimum=384, maximum=MAX_IMAGE_SIZE, step=64, value=512, ) height = gr.Slider( label="Height", minimum=384, maximum=MAX_IMAGE_SIZE, step=64, value=512, ) guidance_scale = gr.Slider( label="Guidance scale", minimum=1.0, maximum=7.5, step=0.1, value=1.0, info="1.0 matches the training recipe of the distilled student.", ) num_inference_steps = gr.Slider( label="Number of inference steps", minimum=1, maximum=8, step=1, value=DEFAULT_STEPS, info="4 steps is the distilled setting; the sigma grid adapts to the step count.", ) gr.Examples( examples=examples, inputs=[prompt], outputs=[result, seed], fn=generate, cache_examples=True, cache_mode="lazy", ) gr.on( triggers=[run_button.click, prompt.submit], fn=generate, inputs=[ prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps, ], outputs=[result, seed], ) if __name__ == "__main__": demo.launch(theme=gr.themes.Citrus(), css=css, mcp_server=True)