import os os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") import spaces # before torch / transformers import random import time import gradio as gr import torch from integral import IntegralForConditionalGeneration, IntegralProcessor MODEL_ID = "the-jb/Integral-9B" DEFAULT_STEPS = 50 DEFAULT_GUIDANCE = 4.0 DEFAULT_TIME_SHIFT = 4.0 DEFAULT_SIZE = 512 # SDPA everywhere: torch-native, supported by both the text model (ALL_ATTENTION_FUNCTIONS # interface) and the visual generation blocks (VISUAL_GENERATION_ATTENTION_FUNCTIONS). # The optional causal_conv1d / flash-linear-attention kernels fall back to pure-torch # implementations when absent; the model runs and generates correctly without them. model = IntegralForConditionalGeneration.from_pretrained( MODEL_ID, dtype=torch.bfloat16, ).to("cuda").eval() processor = IntegralProcessor.from_pretrained(MODEL_ID) def _estimate_gpu_duration(*args, **kwargs): """Reserve ZeroGPU time from the inputs: measured 4.9s at 50 steps/512x512 and 31.5s at 100 steps/1024x1024, so ~2s fixed + 0.075s per step per 512^2 of pixels, with 40% margin and a floor for cold-worker weight streaming.""" def pick(index, name, fallback): value = args[index] if len(args) > index else kwargs.get(name, fallback) try: return int(value) except (TypeError, ValueError): return fallback steps = min(100, max(2, pick(3, "steps", DEFAULT_STEPS))) height = min(1024, max(256, pick(6, "height", DEFAULT_SIZE))) width = min(1024, max(256, pick(7, "width", DEFAULT_SIZE))) scale = (height * width) / (DEFAULT_SIZE * DEFAULT_SIZE) return min(60, max(25, int(1.4 * (2.0 + 0.075 * steps * scale)) + 5)) @spaces.GPU(duration=_estimate_gpu_duration) def generate( prompt: str, seed: int = 42, randomize_seed: bool = True, steps: int = DEFAULT_STEPS, guidance_scale: float = DEFAULT_GUIDANCE, time_shift: float = DEFAULT_TIME_SHIFT, height: int = DEFAULT_SIZE, width: int = DEFAULT_SIZE, ): """Generate an image from a text prompt with Integral-9B. Args: prompt: What to draw. seed: RNG seed for reproducibility. randomize_seed: Pick a fresh seed each run instead of the given one. steps: Number of sampler steps (DPM-Solver++ 2M). guidance_scale: Classifier-free guidance scale. time_shift: Timestep schedule shift. height: Image height in pixels, multiple of 32. width: Image width in pixels, multiple of 32. """ prompt = (prompt or "").strip() if not prompt: raise gr.Error("Please enter a text prompt.") if randomize_seed: seed = random.randint(0, 2**31 - 1) seed = int(seed) height, width = int(height), int(width) steps = int(steps) if steps < 2: steps = 2 height -= height % 32 width -= width % 32 start = time.perf_counter() inputs = processor.prepare_image_generation([prompt], height=height, width=width) out = model.generate_image( **inputs, solver="dpm_solver++", num_inference_steps=steps, guidance_scale=float(guidance_scale), time_shift=float(time_shift), generator=torch.Generator().manual_seed(seed), ) image = out.images[0] elapsed = time.perf_counter() - start print(f"[integral] {steps} steps, {width}x{height}, prompt={prompt!r}: {elapsed:.1f}s") return image, seed CSS = """ #col-container { max-width: 1100px; margin: 0 auto; } .dark .gradio-container { color: var(--body-text-color); } """ with gr.Blocks(theme=gr.themes.Citrus(), css=CSS) as demo: with gr.Column(elem_id="col-container"): gr.Markdown( """ # đŸ§© Integral-9B **Let Vision-Language Models Generate Images through Their Representations** ([arXiv:2611.31237](https://arxiv.org/abs/2611.31237)) — one 9B model that both *understands* and *generates* images, generation flowing through the same visual representations used for understanding. """ ) with gr.Row(): prompt = gr.Textbox( label="Prompt", show_label=False, placeholder="Describe the image to generate…", lines=2, scale=4, autofocus=True, ) run = gr.Button("Generate", variant="primary", scale=1) image_out = gr.Image(label="Generated image", height=512, type="pil") with gr.Accordion("Advanced settings", open=False): with gr.Row(): seed = gr.Number(label="Seed", value=42, precision=0, minimum=-1) randomize_seed = gr.Checkbox(label="Randomize seed", value=True) with gr.Row(): steps = gr.Slider(label="Steps", minimum=2, maximum=100, value=DEFAULT_STEPS, step=1) guidance_scale = gr.Slider(label="Guidance scale", minimum=1.0, maximum=10.0, value=DEFAULT_GUIDANCE, step=0.1) with gr.Row(): time_shift = gr.Slider(label="Time shift", minimum=1.0, maximum=8.0, value=DEFAULT_TIME_SHIFT, step=0.1) with gr.Row(): height = gr.Slider(label="Height", minimum=256, maximum=1024, value=DEFAULT_SIZE, step=32) width = gr.Slider(label="Width", minimum=256, maximum=1024, value=DEFAULT_SIZE, step=32) gr.Examples( examples=[ # The authors' showcased prompts (project page, https://thejb.ai/integral/). ["A photograph of a cat wearing a white T-shirt with the word 'Integral' printed across the chest in bold black capital letters."], ["The mountain most closely associated with the country where Tokyo is located"], ["A cold soda can left outside on a humid day, highlighting the state of the can"], ["Potassium permanganate crystal dissolving in water"], ["The orchard watch hut when the first bats begin leaving the trees."], ["The state of a leaf after a cold night"], ["Show a large animal that lives in the arctic and subarctic, known for its thick white fur"], ["The stepped field landscape associated with the island where Ubud is located"], ], inputs=[prompt], outputs=[image_out], fn=generate, cache_examples=True, cache_mode="lazy", ) prompt.submit(generate, inputs=[prompt, seed, randomize_seed, steps, guidance_scale, time_shift, height, width], outputs=[image_out, seed], api_name="generate") run.click(generate, inputs=[prompt, seed, randomize_seed, steps, guidance_scale, time_shift, height, width], outputs=[image_out, seed], api_name="generate") demo.launch(mcp_server=True)