Spaces:
Running on Zero
Running on Zero
Preload upsampler + pipeline on GPU via @spaces.GPU startup warmup
Browse files91 unmodified lines92939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261272 unmodified lines13013113213313413513613713813914014114214314414525 unmodified lines17117217317417517618 unmodified lines1951961971981992002012025 unmodified lines20820921021121221321421521621721821922022191 unmodified linesSYSTEM_PROMPT = _SEC["system"]USER_TEMPLATE = _SEC.get("user", "User idea: {{original_prompt}}")_enhancer = None # Qwen3VLForConditionalGeneration sharing the pipe's encoder body_logits_processor = None # Outlines structural constraint (built once)def _build_enhancer():"""Graft the hosted lm_head onto pipe.text_encoder -> a generative model (no second body)."""global _enhancer, _logits_processorif _enhancer is not None:return _enhancerdevice = pipe.text_encoder.devicehead = load_file(LM_HEAD_PATH)["lm_head.weight"] # [vocab, hidden] bf16with init_empty_weights():gen = Qwen3VLForConditionalGeneration(pipe.text_encoder.config)gen.model = pipe.text_encoder # reuse the loaded (nf4) encoder body — no extra body in VRAMlm = nn.Linear(head.shape[1], head.shape[0], bias=False).to(device=device, dtype=torch.bfloat16)with torch.no_grad():lm.weight.copy_(head.to(device=device, dtype=torch.bfloat16))gen.lm_head = lmgen.eval()_enhancer = genif OUTLINES_AVAILABLE:ol_model = outlines.from_transformers(gen, upsampler_proc.tokenizer)_logits_processor = outlines.Generator(ol_model, Caption).logits_processorreturn gendef upsample_prompt(prompt: str, width: int, height: int) -> str:from math import gcdgen = _build_enhancer()d = gcd(width, height) or 1aspect_ratio = f"{width // d}:{height // d}"user = USER_TEMPLATE.replace("{{aspect_ratio}}", aspect_ratio).replace("{{original_prompt}}", prompt)2 unmodified linesmessages, add_generation_prompt=True, tokenize=True, return_tensors="pt", return_dict=True).to(gen.device)gen_kwargs = dict(max_new_tokens=1024, do_sample=True, temperature=1.0, use_cache=True)if _logits_processor is not None:_logits_processor.reset()gen_kwargs["logits_processor"] = [_logits_processor]out = gen.generate(**inputs, **gen_kwargs)return upsampler_proc.batch_decode(out[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)[0].strip()@spaces.GPU(duration=180, size="xlarge")def generate(prompt: str,mode: str,25 unmodified linesreturn image, seed, final_promptwith gr.Blocks(theme=gr.themes.Citrus(), title="Ideogram 4 (NF4) — diffusers preview") as demo:gr.Markdown("## Ideogram 4 (NF4) — diffusers preview\n"18 unmodified linesrun = gr.Button("Generate", variant="primary")with gr.Accordion("Advanced", open=False):enhance = gr.Checkbox(label="Prompt upsampling",value=True,info="Rewrite the prompt into Ideogram's native JSON caption before generating."+ ("" if OUTLINES_AVAILABLE else " ⚠ outlines not installed — runs unconstrained."),)5 unmodified linesrandomize = gr.Checkbox(label="Randomize seed", value=True)with gr.Column():out_image = gr.Image(label="Output", type="pil")out_caption = gr.Textbox(label="Caption fed to the model (upsampled when enabled)",)run.click(generate,inputs=[prompt, mode, enhance, width, height, seed, randomize],outputs=[out_image, seed, out_caption],)demo.queue().launch()91 unmodified lines92939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461472 unmodified lines15015115215315415515615715815916016116216316416525 unmodified lines19119219319419519619719819920020120220320420520620720820921021121221321421521621721818 unmodified lines2372382392402412422432445 unmodified lines25025125225325425525625725825926026126226326426526691 unmodified linesSYSTEM_PROMPT = _SEC["system"]USER_TEMPLATE = _SEC.get("user", "User idea: {{original_prompt}}")def _build_enhancer():"""Graft the hosted lm_head onto pipe.text_encoder -> a generative model (no second body).Done ONCE at import time so nothing heavy happens on the first GPU request. Only the newbf16 lm_head is `.to('cuda')` (ZeroGPU defers it); the shared nf4 body is already moved by `pipe`."""head = load_file(LM_HEAD_PATH)["lm_head.weight"] # [vocab, hidden] bf16with init_empty_weights():gen = Qwen3VLForConditionalGeneration(pipe.text_encoder.config)gen.model = pipe.text_encoder # reuse the loaded (nf4) encoder body — no extra body in VRAMlm = nn.Linear(head.shape[1], head.shape[0], bias=False)with torch.no_grad():lm.weight.copy_(head.to(torch.bfloat16))gen.lm_head = lm.to(torch.bfloat16)gen.lm_head.to("cuda") # ZeroGPU-deferred move of just the headgen.eval()lp = Noneif OUTLINES_AVAILABLE:ol_model = outlines.from_transformers(gen, upsampler_proc.tokenizer)lp = outlines.Generator(ol_model, Caption).logits_processor # compiles schema->FSM nowreturn gen, lp# Assemble the generative enhancer + structural constraint at STARTUP (not on first request).try:ENHANCER, LOGITS_PROCESSOR = _build_enhancer()except Exception as e: # don't let a graft hiccup block the demo / the bf16 OOM testprint(f"[enhancer] graft failed, prompt upsampling disabled: {e!r}")ENHANCER, LOGITS_PROCESSOR = None, None# --- bf16 path: dequantize both transformers nf4 -> bf16 (kept resident; YOLO OOM test) ---# diffusers ModelMixin.dequantize() replaces the bnb 4-bit layers with bf16 and drops the quantizer.# Done lazily on first GPU request (ZeroGPU: no CUDA at import, and bnb dequant needs the weights on GPU)._BF16_DONE = Falsedef _ensure_bf16_transformers():global _BF16_DONEif _BF16_DONE:returnpipe.transformer.dequantize()pipe.unconditional_transformer.dequantize()torch.cuda.empty_cache()_BF16_DONE = Truedef upsample_prompt(prompt: str, width: int, height: int) -> str:from math import gcdgen = ENHANCERd = gcd(width, height) or 1aspect_ratio = f"{width // d}:{height // d}"user = USER_TEMPLATE.replace("{{aspect_ratio}}", aspect_ratio).replace("{{original_prompt}}", prompt)2 unmodified linesmessages, add_generation_prompt=True, tokenize=True, return_tensors="pt", return_dict=True).to(gen.device)gen_kwargs = dict(max_new_tokens=1024, do_sample=True, temperature=1.0, use_cache=True)if LOGITS_PROCESSOR is not None:LOGITS_PROCESSOR.reset()gen_kwargs["logits_processor"] = [LOGITS_PROCESSOR]out = gen.generate(**inputs, **gen_kwargs)return upsampler_proc.batch_decode(out[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)[0].strip()@spaces.GPU(duration=240)def generate(prompt: str,mode: str,25 unmodified linesreturn image, seed, final_prompt@spaces.GPUdef _warmup():"""Force the upsampler + pipeline onto GPU and warm their kernels at STARTUP, so request #1isn't slow. On ZeroGPU, module-level loading is CPU-only; GPU placement + JIT warmup otherwisehappen on the first request."""try:if ENHANCER is not None:upsample_prompt("a red apple on a wooden table", 1024, 1024)print("[warmup] upsampler ready on GPU", flush=True)except Exception as e:print(f"[warmup] upsampler warmup skipped: {e!r}", flush=True)try:g = torch.Generator(device="cuda").manual_seed(0)pipe(prompt="a red apple", width=1024, height=1024, generator=g, **MODES["Turbo · 12 steps"])print("[warmup] pipeline ready on GPU", flush=True)except Exception as e:print(f"[warmup] pipeline warmup skipped: {e!r}", flush=True)_warmup()with gr.Blocks(theme=gr.themes.Citrus(), title="Ideogram 4 (NF4) — diffusers preview") as demo:gr.Markdown("## Ideogram 4 (NF4) — diffusers preview\n"18 unmodified linesrun = gr.Button("Generate", variant="primary")with gr.Accordion("Advanced", open=False):enhance = gr.Checkbox(label="Prompt upsampling (Outlines)",value=False,info="Rewrite the prompt into Ideogram's native JSON caption before generating."+ ("" if OUTLINES_AVAILABLE else " ⚠ outlines not installed — runs unconstrained."),)5 unmodified linesrandomize = gr.Checkbox(label="Randomize seed", value=True)with gr.Column():out_image = gr.Image(label="Output", type="pil")out_seed = gr.Number(label="Seed used", interactive=False, precision=0)out_caption = gr.Textbox(label="Caption fed to the model (upsampled when enabled)",lines=4,show_copy_button=True,)run.click(generate,inputs=[prompt, mode, enhance, width, height, seed, randomize],outputs=[out_image, out_seed, out_caption],)demo.queue().launch()
app.py+67-22